blob: 99b05389b2b494e080ae256f0b85aa3818efd116 [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 }
Chris Lattner18c7f802012-02-05 02:29:43 +0000259
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
Chris Lattner18c7f802012-02-05 02:29:43 +0000262 StringRef 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 Lattner18c7f802012-02-05 02:29:43 +0000266 // Compute the offset, make sure to handle the case when we're searching for
267 // zero (a weird way to spell strlen).
268 size_t I = CharC->getSExtValue() == 0 ?
269 Str.size() : Str.find(CharC->getSExtValue());
270 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
Benjamin Kramere2609902010-09-29 22:29:12 +0000271 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000272
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000273 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000274 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000275 }
276};
277
278//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000279// 'strrchr' Optimizations
280
281struct StrRChrOpt : public LibCallOptimization {
282 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
283 // Verify the "strrchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000284 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000285 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000286 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000287 FT->getParamType(0) != FT->getReturnType() ||
288 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000289 return 0;
290
291 Value *SrcStr = CI->getArgOperand(0);
292 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
293
294 // Cannot fold anything if we're not looking for a constant.
295 if (!CharC)
296 return 0;
297
Chris Lattner18c7f802012-02-05 02:29:43 +0000298 StringRef Str;
299 if (!getConstantStringInfo(SrcStr, Str)) {
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000300 // strrchr(s, 0) -> strchr(s, 0)
301 if (TD && CharC->isZero())
302 return EmitStrChr(SrcStr, '\0', B, TD);
303 return 0;
304 }
305
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000306 // Compute the offset.
Chris Lattner18c7f802012-02-05 02:29:43 +0000307 size_t I = CharC->getSExtValue() == 0 ?
308 Str.size() : Str.rfind(CharC->getSExtValue());
309 if (I == StringRef::npos) // Didn't find the char. Return null.
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000310 return Constant::getNullValue(CI->getType());
311
312 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000313 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000314 }
315};
316
317//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000318// 'strcmp' Optimizations
319
Chris Lattner3e8b6632009-09-02 06:11:42 +0000320struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000321 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000322 // Verify the "strcmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000323 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000324 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000325 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000326 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000327 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000328 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000329
Gabor Greifaee5dc12010-06-24 10:42:46 +0000330 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000331 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000332 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000333
Chris Lattner18c7f802012-02-05 02:29:43 +0000334 StringRef Str1, Str2;
335 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
336 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000337
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000338 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000339 if (HasStr1 && HasStr2)
Chris Lattner18c7f802012-02-05 02:29:43 +0000340 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
Eli Friedman79286082011-10-05 22:27:16 +0000341
342 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
343 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
344 CI->getType()));
345
346 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
347 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000348
349 // strcmp(P, "x") -> memcmp(P, "x", 2)
350 uint64_t Len1 = GetStringLength(Str1P);
351 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000352 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000353 // These optimizations require TargetData.
354 if (!TD) return 0;
355
Nick Lewycky13a09e22008-12-21 00:19:21 +0000356 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000357 ConstantInt::get(TD->getIntPtrType(*Context),
Eric Christopherb6174e32010-03-05 22:25:30 +0000358 std::min(Len1, Len2)), B, TD);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000359 }
360
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000361 return 0;
362 }
363};
364
365//===---------------------------------------===//
366// 'strncmp' Optimizations
367
Chris Lattner3e8b6632009-09-02 06:11:42 +0000368struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000369 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000370 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000372 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000373 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000374 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000375 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000376 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000377 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000378
Gabor Greifaee5dc12010-06-24 10:42:46 +0000379 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000380 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000381 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000382
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000383 // Get the length argument if it is constant.
384 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000385 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386 Length = LengthArg->getZExtValue();
387 else
388 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000389
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000390 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000391 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000392
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000393 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000394 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000395
Chris Lattner18c7f802012-02-05 02:29:43 +0000396 StringRef Str1, Str2;
397 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
398 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000399
Eli Friedman79286082011-10-05 22:27:16 +0000400 // strncmp(x, y) -> cnst (if both x and y are constant strings)
401 if (HasStr1 && HasStr2) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000402 StringRef SubStr1 = Str1.substr(0, Length);
403 StringRef SubStr2 = Str2.substr(0, Length);
Eli Friedman79286082011-10-05 22:27:16 +0000404 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
405 }
406
407 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
408 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
409 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000410
Bill Wendling0582ae92009-03-13 04:39:26 +0000411 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000412 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000413
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000414 return 0;
415 }
416};
417
418
419//===---------------------------------------===//
420// 'strcpy' Optimizations
421
Chris Lattner3e8b6632009-09-02 06:11:42 +0000422struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000423 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
424
425 StrCpyOpt(bool c) : OptChkCall(c) {}
426
Eric Christopher7a61d702008-08-08 19:39:37 +0000427 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000428 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000429 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000430 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000431 if (FT->getNumParams() != NumParams ||
432 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000433 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000434 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000435 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000436
Gabor Greifaee5dc12010-06-24 10:42:46 +0000437 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000438 if (Dst == Src) // strcpy(x,x) -> x
439 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000440
Dan Gohmanf14d9192009-08-18 00:48:13 +0000441 // These optimizations require TargetData.
442 if (!TD) return 0;
443
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000444 // See if we can get the length of the input string.
445 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000446 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000447
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000448 // We have enough information to now generate the memcpy call to do the
449 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000450 if (OptChkCall)
451 EmitMemCpyChk(Dst, Src,
452 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Gabor Greifaee5dc12010-06-24 10:42:46 +0000453 CI->getArgOperand(2), B, TD);
Evan Cheng0289b412010-03-23 15:48:04 +0000454 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000455 B.CreateMemCpy(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000457 return Dst;
458 }
459};
460
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000461//===---------------------------------------===//
David Majnemerac782662012-05-15 11:46:21 +0000462// 'stpcpy' Optimizations
463
464struct StpCpyOpt: public LibCallOptimization {
465 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
466
467 StpCpyOpt(bool c) : OptChkCall(c) {}
468
469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
470 // Verify the "stpcpy" function prototype.
471 unsigned NumParams = OptChkCall ? 3 : 2;
472 FunctionType *FT = Callee->getFunctionType();
473 if (FT->getNumParams() != NumParams ||
474 FT->getReturnType() != FT->getParamType(0) ||
475 FT->getParamType(0) != FT->getParamType(1) ||
476 FT->getParamType(0) != B.getInt8PtrTy())
477 return 0;
478
479 // These optimizations require TargetData.
480 if (!TD) return 0;
481
482 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
483 if (Dst == Src) // stpcpy(x,x) -> x+strlen(x)
484 return B.CreateInBoundsGEP(Dst, EmitStrLen(Src, B, TD));
485
486 // See if we can get the length of the input string.
487 uint64_t Len = GetStringLength(Src);
488 if (Len == 0) return 0;
489
490 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
491 Value *DstEnd = B.CreateGEP(Dst,
492 ConstantInt::get(TD->getIntPtrType(*Context),
493 Len - 1));
494
495 // We have enough information to now generate the memcpy call to do the
496 // copy for us. Make a memcpy to copy the nul byte with align = 1.
497 if (OptChkCall)
498 EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD);
499 else
500 B.CreateMemCpy(Dst, Src, LenV, 1);
501 return DstEnd;
502 }
503};
504
505//===---------------------------------------===//
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000506// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000507
Chris Lattner3e8b6632009-09-02 06:11:42 +0000508struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000509 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000510 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000511 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
512 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000513 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000514 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000515 return 0;
516
Gabor Greifaee5dc12010-06-24 10:42:46 +0000517 Value *Dst = CI->getArgOperand(0);
518 Value *Src = CI->getArgOperand(1);
519 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000520
521 // See if we can get the length of the input string.
522 uint64_t SrcLen = GetStringLength(Src);
523 if (SrcLen == 0) return 0;
524 --SrcLen;
525
526 if (SrcLen == 0) {
527 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000528 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000529 return Dst;
530 }
531
532 uint64_t Len;
533 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
534 Len = LengthArg->getZExtValue();
535 else
536 return 0;
537
538 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
539
Dan Gohmanf14d9192009-08-18 00:48:13 +0000540 // These optimizations require TargetData.
541 if (!TD) return 0;
542
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000543 // Let strncpy handle the zero padding
544 if (Len > SrcLen+1) return 0;
545
546 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000547 B.CreateMemCpy(Dst, Src,
548 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000549
550 return Dst;
551 }
552};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000553
554//===---------------------------------------===//
555// 'strlen' Optimizations
556
Chris Lattner3e8b6632009-09-02 06:11:42 +0000557struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000558 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000559 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000560 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000561 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000562 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000563 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000564
Gabor Greifaee5dc12010-06-24 10:42:46 +0000565 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000566
567 // Constant folding: strlen("xyz") -> 3
568 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000569 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000570
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000571 // strlen(x) != 0 --> *x != 0
572 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000573 if (IsOnlyUsedInZeroEqualityComparison(CI))
574 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
575 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000576 }
577};
578
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000579
580//===---------------------------------------===//
581// 'strpbrk' Optimizations
582
583struct StrPBrkOpt : public LibCallOptimization {
584 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000585 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000586 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000587 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000588 FT->getParamType(1) != FT->getParamType(0) ||
589 FT->getReturnType() != FT->getParamType(0))
590 return 0;
591
Chris Lattner18c7f802012-02-05 02:29:43 +0000592 StringRef S1, S2;
593 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
594 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000595
596 // strpbrk(s, "") -> NULL
597 // strpbrk("", s) -> NULL
598 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
599 return Constant::getNullValue(CI->getType());
600
601 // Constant folding.
602 if (HasS1 && HasS2) {
603 size_t I = S1.find_first_of(S2);
604 if (I == std::string::npos) // No match.
605 return Constant::getNullValue(CI->getType());
606
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000607 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000608 }
609
610 // strpbrk(s, "a") -> strchr(s, 'a')
611 if (TD && HasS2 && S2.size() == 1)
612 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
613
614 return 0;
615 }
616};
617
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000618//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000619// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000620
Chris Lattner3e8b6632009-09-02 06:11:42 +0000621struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000622 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000623 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000624 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000625 !FT->getParamType(0)->isPointerTy() ||
626 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000627 return 0;
628
Gabor Greifaee5dc12010-06-24 10:42:46 +0000629 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000630 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000631 // With a null EndPtr, this function won't capture the main argument.
632 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000633 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000634 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000635
636 return 0;
637 }
638};
639
Chris Lattner24604112009-12-16 09:32:05 +0000640//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000641// 'strspn' Optimizations
642
643struct StrSpnOpt : public LibCallOptimization {
644 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000645 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000646 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000647 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000648 FT->getParamType(1) != FT->getParamType(0) ||
649 !FT->getReturnType()->isIntegerTy())
650 return 0;
651
Chris Lattner18c7f802012-02-05 02:29:43 +0000652 StringRef S1, S2;
653 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
654 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000655
656 // strspn(s, "") -> 0
657 // strspn("", s) -> 0
658 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
659 return Constant::getNullValue(CI->getType());
660
661 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000662 if (HasS1 && HasS2) {
663 size_t Pos = S1.find_first_not_of(S2);
664 if (Pos == StringRef::npos) Pos = S1.size();
665 return ConstantInt::get(CI->getType(), Pos);
666 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000667
668 return 0;
669 }
670};
671
672//===---------------------------------------===//
673// 'strcspn' Optimizations
674
675struct StrCSpnOpt : public LibCallOptimization {
676 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000677 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000678 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000679 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000680 FT->getParamType(1) != FT->getParamType(0) ||
681 !FT->getReturnType()->isIntegerTy())
682 return 0;
683
Chris Lattner18c7f802012-02-05 02:29:43 +0000684 StringRef S1, S2;
685 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
686 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000687
688 // strcspn("", s) -> 0
689 if (HasS1 && S1.empty())
690 return Constant::getNullValue(CI->getType());
691
692 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000693 if (HasS1 && HasS2) {
694 size_t Pos = S1.find_first_of(S2);
695 if (Pos == StringRef::npos) Pos = S1.size();
696 return ConstantInt::get(CI->getType(), Pos);
697 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000698
699 // strcspn(s, "") -> strlen(s)
700 if (TD && HasS2 && S2.empty())
701 return EmitStrLen(CI->getArgOperand(0), B, TD);
702
703 return 0;
704 }
705};
706
707//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000708// 'strstr' Optimizations
709
710struct StrStrOpt : public LibCallOptimization {
711 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000712 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000713 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000714 !FT->getParamType(0)->isPointerTy() ||
715 !FT->getParamType(1)->isPointerTy() ||
716 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000717 return 0;
718
719 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000720 if (CI->getArgOperand(0) == CI->getArgOperand(1))
721 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000722
Benjamin Kramer386e9182010-06-15 21:34:25 +0000723 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000724 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
725 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
726 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer386e9182010-06-15 21:34:25 +0000727 StrLen, B, TD);
728 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
729 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000730 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000731 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
732 ConstantInt::getNullValue(StrNCmp->getType()),
733 "cmp");
734 Old->replaceAllUsesWith(Cmp);
735 Old->eraseFromParent();
736 }
737 return CI;
738 }
739
Chris Lattner24604112009-12-16 09:32:05 +0000740 // See if either input string is a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000741 StringRef SearchStr, ToFindStr;
742 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
743 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000744
Chris Lattner24604112009-12-16 09:32:05 +0000745 // fold strstr(x, "") -> x.
746 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000747 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000748
Chris Lattner24604112009-12-16 09:32:05 +0000749 // If both strings are known, constant fold it.
750 if (HasStr1 && HasStr2) {
751 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000752
Chris Lattner18c7f802012-02-05 02:29:43 +0000753 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Chris Lattner24604112009-12-16 09:32:05 +0000754 return Constant::getNullValue(CI->getType());
755
756 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000757 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000758 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
759 return B.CreateBitCast(Result, CI->getType());
760 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000761
Chris Lattner24604112009-12-16 09:32:05 +0000762 // fold strstr(x, "y") -> strchr(x, 'y').
763 if (HasStr2 && ToFindStr.size() == 1)
Gabor Greifa3997812010-07-22 10:37:47 +0000764 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
765 ToFindStr[0], B, TD), CI->getType());
Chris Lattner24604112009-12-16 09:32:05 +0000766 return 0;
767 }
768};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000769
Nick Lewycky4c498412009-02-13 15:31:46 +0000770
771//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000772// 'memcmp' Optimizations
773
Chris Lattner3e8b6632009-09-02 06:11:42 +0000774struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000775 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000776 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000777 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
778 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000779 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000780 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000781
Gabor Greifaee5dc12010-06-24 10:42:46 +0000782 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000783
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000784 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000785 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000786
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000787 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000788 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000789 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000790 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000791
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000792 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000793 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000794
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000795 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
796 if (Len == 1) {
797 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
798 CI->getType(), "lhsv");
799 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
800 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000801 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000802 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000803
Benjamin Kramer992a6372009-11-05 17:44:22 +0000804 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Chris Lattner18c7f802012-02-05 02:29:43 +0000805 StringRef LHSStr, RHSStr;
806 if (getConstantStringInfo(LHS, LHSStr) &&
807 getConstantStringInfo(RHS, RHSStr)) {
Benjamin Kramer992a6372009-11-05 17:44:22 +0000808 // Make sure we're not reading out-of-bounds memory.
Chris Lattner18c7f802012-02-05 02:29:43 +0000809 if (Len > LHSStr.size() || Len > RHSStr.size())
Benjamin Kramer992a6372009-11-05 17:44:22 +0000810 return 0;
811 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
812 return ConstantInt::get(CI->getType(), Ret);
813 }
814
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000815 return 0;
816 }
817};
818
819//===---------------------------------------===//
820// 'memcpy' Optimizations
821
Chris Lattner3e8b6632009-09-02 06:11:42 +0000822struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000823 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000824 // These optimizations require TargetData.
825 if (!TD) return 0;
826
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000827 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000828 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000829 !FT->getParamType(0)->isPointerTy() ||
830 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000831 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000832 return 0;
833
834 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000835 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
836 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000837 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000838 }
839};
840
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000841//===---------------------------------------===//
842// 'memmove' Optimizations
843
Chris Lattner3e8b6632009-09-02 06:11:42 +0000844struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000845 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000846 // These optimizations require TargetData.
847 if (!TD) return 0;
848
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000849 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000850 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000851 !FT->getParamType(0)->isPointerTy() ||
852 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000853 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000854 return 0;
855
856 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000857 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
858 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000859 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000860 }
861};
862
863//===---------------------------------------===//
864// 'memset' Optimizations
865
Chris Lattner3e8b6632009-09-02 06:11:42 +0000866struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000867 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000868 // These optimizations require TargetData.
869 if (!TD) return 0;
870
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000871 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000872 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000873 !FT->getParamType(0)->isPointerTy() ||
874 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000875 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000876 return 0;
877
878 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000879 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
880 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000881 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000882 }
883};
884
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000885//===----------------------------------------------------------------------===//
886// Math Library Optimizations
887//===----------------------------------------------------------------------===//
888
889//===---------------------------------------===//
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000890// 'cos*' Optimizations
891
892struct CosOpt : public LibCallOptimization {
893 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
894 FunctionType *FT = Callee->getFunctionType();
895 // Just make sure this has 1 argument of FP type, which matches the
896 // result type.
897 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
898 !FT->getParamType(0)->isFloatingPointTy())
899 return 0;
900
901 // cos(-x) -> cos(x)
902 Value *Op1 = CI->getArgOperand(0);
903 if (BinaryOperator::isFNeg(Op1)) {
904 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
905 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
906 }
907 return 0;
908 }
909};
910
911//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000912// 'pow*' Optimizations
913
Chris Lattner3e8b6632009-09-02 06:11:42 +0000914struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000915 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000916 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000917 // Just make sure this has 2 arguments of the same FP type, which match the
918 // result type.
919 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
920 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000921 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000922 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000923
Gabor Greifaee5dc12010-06-24 10:42:46 +0000924 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000925 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
926 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
927 return Op1C;
928 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000929 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000930 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000931
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000932 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
933 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000934
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000935 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000936 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000937
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000938 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000939 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
940 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000941 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +0000942 // TODO: In fast-math mode, this could be just sqrt(x).
943 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000944 Value *Inf = ConstantFP::getInfinity(CI->getType());
945 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000946 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
947 Callee->getAttributes());
948 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
949 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000950 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
951 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000952 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000953 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000954
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000955 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
956 return Op1;
957 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000958 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000959 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000960 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000961 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000962 return 0;
963 }
964};
965
966//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000967// 'exp2' Optimizations
968
Chris Lattner3e8b6632009-09-02 06:11:42 +0000969struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000970 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000971 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000972 // Just make sure this has 1 argument of FP type, which matches the
973 // result type.
974 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000975 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000976 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000977
Gabor Greifaee5dc12010-06-24 10:42:46 +0000978 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000979 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
980 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
981 Value *LdExpArg = 0;
982 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
983 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000984 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000985 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
986 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000987 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000988 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000989
Chris Lattnere818f772008-05-02 18:43:35 +0000990 if (LdExpArg) {
991 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000992 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000993 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000994 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000995 Name = "ldexp";
996 else
997 Name = "ldexpl";
998
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000999 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001000 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001001 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001002
1003 Module *M = Caller->getParent();
1004 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +00001005 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001006 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001007 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1008 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1009 CI->setCallingConv(F->getCallingConv());
1010
1011 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001012 }
1013 return 0;
1014 }
1015};
Chris Lattnere818f772008-05-02 18:43:35 +00001016
1017//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001018// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1019
Chris Lattner3e8b6632009-09-02 06:11:42 +00001020struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001021 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001022 FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001023 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1024 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001025 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001026
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001027 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001028 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001029 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001030 return 0;
1031
1032 // floor((double)floatval) -> (double)floorf(floatval)
1033 Value *V = Cast->getOperand(0);
Benjamin Kramerb5ccb252011-11-15 19:12:09 +00001034 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001035 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001036 }
1037};
1038
1039//===----------------------------------------------------------------------===//
1040// Integer Optimizations
1041//===----------------------------------------------------------------------===//
1042
1043//===---------------------------------------===//
1044// 'ffs*' Optimizations
1045
Chris Lattner3e8b6632009-09-02 06:11:42 +00001046struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001047 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001048 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001049 // Just make sure this has 2 arguments of the same FP type, which match the
1050 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001051 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +00001052 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +00001053 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001054 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001055
Gabor Greifaee5dc12010-06-24 10:42:46 +00001056 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001057
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001058 // Constant fold.
1059 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1060 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001061 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001062 // ffs(c) -> cttz(c)+1
1063 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001064 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001065
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001066 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001067 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001068 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001069 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001070 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001071 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1072 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001073
Benjamin Kramera9390a42011-09-27 20:39:19 +00001074 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001075 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001076 }
1077};
1078
1079//===---------------------------------------===//
1080// 'isdigit' Optimizations
1081
Chris Lattner3e8b6632009-09-02 06:11:42 +00001082struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001083 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001084 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001085 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001086 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001087 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001088 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001089
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001090 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001091 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001092 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1093 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001094 return B.CreateZExt(Op, CI->getType());
1095 }
1096};
1097
1098//===---------------------------------------===//
1099// 'isascii' Optimizations
1100
Chris Lattner3e8b6632009-09-02 06:11:42 +00001101struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001102 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001103 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001104 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001105 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001106 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001107 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001108
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001109 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001110 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001111 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001112 return B.CreateZExt(Op, CI->getType());
1113 }
1114};
Eric Christopher37c8b862009-10-07 21:14:25 +00001115
Chris Lattner313f0e62008-06-09 08:26:51 +00001116//===---------------------------------------===//
1117// 'abs', 'labs', 'llabs' Optimizations
1118
Chris Lattner3e8b6632009-09-02 06:11:42 +00001119struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001120 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001121 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001122 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001123 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001124 FT->getParamType(0) != FT->getReturnType())
1125 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001126
Chris Lattner313f0e62008-06-09 08:26:51 +00001127 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001128 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001129 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001130 "ispos");
1131 Value *Neg = B.CreateNeg(Op, "neg");
1132 return B.CreateSelect(Pos, Op, Neg);
1133 }
1134};
Eric Christopher37c8b862009-10-07 21:14:25 +00001135
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001136
1137//===---------------------------------------===//
1138// 'toascii' Optimizations
1139
Chris Lattner3e8b6632009-09-02 06:11:42 +00001140struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001141 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001142 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001143 // We require i32(i32)
1144 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001145 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001146 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001147
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001148 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001149 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001150 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001151 }
1152};
1153
1154//===----------------------------------------------------------------------===//
1155// Formatting and IO Optimizations
1156//===----------------------------------------------------------------------===//
1157
1158//===---------------------------------------===//
1159// 'printf' Optimizations
1160
Chris Lattner3e8b6632009-09-02 06:11:42 +00001161struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001162 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1163 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001164 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001165 StringRef FormatStr;
1166 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001167 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001168
1169 // Empty format string -> noop.
1170 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001171 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001172 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001173
Daniel Dunbard02be242011-02-12 18:19:57 +00001174 // Do not do any of the following transformations if the printf return value
1175 // is used, in general the printf return value is not compatible with either
1176 // putchar() or puts().
1177 if (!CI->use_empty())
1178 return 0;
1179
1180 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001181 if (FormatStr.size() == 1) {
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001182 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
Chris Lattner74965f22009-11-09 04:57:04 +00001183 if (CI->use_empty()) return CI;
1184 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001185 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001186
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001187 // printf("foo\n") --> puts("foo")
1188 if (FormatStr[FormatStr.size()-1] == '\n' &&
1189 FormatStr.find('%') == std::string::npos) { // no format characters.
1190 // Create a string literal with no \n on it. We expect the constant merge
1191 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +00001192 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001193 Value *GV = B.CreateGlobalString(FormatStr, "str");
1194 EmitPutS(GV, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +00001195 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001196 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001197 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001198
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001199 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001200 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001201 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001202 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1203 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001204
Chris Lattner74965f22009-11-09 04:57:04 +00001205 if (CI->use_empty()) return CI;
1206 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001207 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001208
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001209 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001210 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001211 CI->getArgOperand(1)->getType()->isPointerTy()) {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001212 EmitPutS(CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001213 return CI;
1214 }
1215 return 0;
1216 }
Richard Osborne36498242011-03-03 13:17:51 +00001217
1218 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1219 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001220 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001221 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1222 !(FT->getReturnType()->isIntegerTy() ||
1223 FT->getReturnType()->isVoidTy()))
1224 return 0;
1225
1226 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1227 return V;
1228 }
1229
1230 // printf(format, ...) -> iprintf(format, ...) if no floating point
1231 // arguments.
1232 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1233 Module *M = B.GetInsertBlock()->getParent()->getParent();
1234 Constant *IPrintFFn =
1235 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1236 CallInst *New = cast<CallInst>(CI->clone());
1237 New->setCalledFunction(IPrintFFn);
1238 B.Insert(New);
1239 return New;
1240 }
1241 return 0;
1242 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001243};
1244
1245//===---------------------------------------===//
1246// 'sprintf' Optimizations
1247
Chris Lattner3e8b6632009-09-02 06:11:42 +00001248struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001249 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1250 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001251 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001252 StringRef FormatStr;
1253 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001254 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001255
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001256 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001257 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001258 // Make sure there's no % in the constant array. We could try to handle
1259 // %% -> % in the future if we cared.
1260 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1261 if (FormatStr[i] == '%')
1262 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001263
1264 // These optimizations require TargetData.
1265 if (!TD) return 0;
1266
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001267 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001268 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1269 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1270 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001271 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001272 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001273
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001274 // The remaining optimizations require the format string to be "%s" or "%c"
1275 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001276 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1277 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001278 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001279
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001280 // Decode the second character of the format string.
1281 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001282 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001283 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001284 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001285 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001286 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001287 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1288 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001289
Owen Andersoneed707b2009-07-24 23:12:02 +00001290 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001291 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001292
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001293 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001294 // These optimizations require TargetData.
1295 if (!TD) return 0;
1296
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001297 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001298 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001299
Gabor Greifaee5dc12010-06-24 10:42:46 +00001300 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001301 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001302 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001303 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001304 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001305
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001306 // The sprintf result is the unincremented number of bytes in the string.
1307 return B.CreateIntCast(Len, CI->getType(), false);
1308 }
1309 return 0;
1310 }
Richard Osborne419454a2011-03-03 14:09:28 +00001311
1312 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1313 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001314 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001315 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1316 !FT->getParamType(1)->isPointerTy() ||
1317 !FT->getReturnType()->isIntegerTy())
1318 return 0;
1319
1320 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1321 return V;
1322 }
1323
Richard Osborneea2578c2011-03-03 14:21:22 +00001324 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001325 // point arguments.
1326 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1327 Module *M = B.GetInsertBlock()->getParent()->getParent();
1328 Constant *SIPrintFFn =
1329 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1330 CallInst *New = cast<CallInst>(CI->clone());
1331 New->setCalledFunction(SIPrintFFn);
1332 B.Insert(New);
1333 return New;
1334 }
1335 return 0;
1336 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001337};
1338
1339//===---------------------------------------===//
1340// 'fwrite' Optimizations
1341
Chris Lattner3e8b6632009-09-02 06:11:42 +00001342struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001343 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001344 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001345 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001346 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1347 !FT->getParamType(1)->isIntegerTy() ||
1348 !FT->getParamType(2)->isIntegerTy() ||
1349 !FT->getParamType(3)->isPointerTy() ||
1350 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001351 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001352
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001353 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001354 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1355 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001356 if (!SizeC || !CountC) return 0;
1357 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001358
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001359 // If this is writing zero records, remove the call (it's a noop).
1360 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001361 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001362
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001363 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001364 // This optimisation is only valid, if the return value is unused.
1365 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001366 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1367 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001368 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001369 }
1370
1371 return 0;
1372 }
1373};
1374
1375//===---------------------------------------===//
1376// 'fputs' Optimizations
1377
Chris Lattner3e8b6632009-09-02 06:11:42 +00001378struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001379 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001380 // These optimizations require TargetData.
1381 if (!TD) return 0;
1382
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001383 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001384 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001385 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1386 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001387 !CI->use_empty())
1388 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001389
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001390 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001391 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001392 if (!Len) return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001393 EmitFWrite(CI->getArgOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00001394 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Eli Friedman9d434db2011-11-17 01:27:36 +00001395 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001396 return CI; // Known to have no uses (see above).
1397 }
1398};
1399
1400//===---------------------------------------===//
1401// 'fprintf' Optimizations
1402
Chris Lattner3e8b6632009-09-02 06:11:42 +00001403struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001404 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1405 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001406 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001407 StringRef FormatStr;
1408 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001409 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001410
1411 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001412 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001413 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1414 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001415 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001416
1417 // These optimizations require TargetData.
1418 if (!TD) return 0;
1419
Gabor Greifaee5dc12010-06-24 10:42:46 +00001420 EmitFWrite(CI->getArgOperand(1),
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001421 ConstantInt::get(TD->getIntPtrType(*Context),
1422 FormatStr.size()),
Eli Friedman9d434db2011-11-17 01:27:36 +00001423 CI->getArgOperand(0), B, TD, TLI);
Owen Andersoneed707b2009-07-24 23:12:02 +00001424 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001425 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001426
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001427 // The remaining optimizations require the format string to be "%s" or "%c"
1428 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001429 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1430 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001431 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001432
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001433 // Decode the second character of the format string.
1434 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001435 // fprintf(F, "%c", chr) --> fputc(chr, F)
1436 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1437 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001438 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001439 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001440
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001441 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001442 // fprintf(F, "%s", str) --> fputs(str, F)
1443 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001444 return 0;
Eli Friedman9d434db2011-11-17 01:27:36 +00001445 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001446 return CI;
1447 }
1448 return 0;
1449 }
Richard Osborne022708f2011-03-03 14:20:22 +00001450
1451 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1452 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001453 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001454 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1455 !FT->getParamType(1)->isPointerTy() ||
1456 !FT->getReturnType()->isIntegerTy())
1457 return 0;
1458
1459 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1460 return V;
1461 }
1462
1463 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1464 // floating point arguments.
1465 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1466 Module *M = B.GetInsertBlock()->getParent()->getParent();
1467 Constant *FIPrintFFn =
1468 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1469 CallInst *New = cast<CallInst>(CI->clone());
1470 New->setCalledFunction(FIPrintFFn);
1471 B.Insert(New);
1472 return New;
1473 }
1474 return 0;
1475 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001476};
1477
Anders Carlsson303023d2010-11-30 06:19:18 +00001478//===---------------------------------------===//
1479// 'puts' Optimizations
1480
1481struct PutsOpt : public LibCallOptimization {
1482 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1483 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001484 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001485 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1486 !(FT->getReturnType()->isIntegerTy() ||
1487 FT->getReturnType()->isVoidTy()))
1488 return 0;
1489
1490 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001491 StringRef Str;
1492 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +00001493 return 0;
1494
Daniel Dunbard02be242011-02-12 18:19:57 +00001495 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001496 // puts("") -> putchar('\n')
1497 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1498 if (CI->use_empty()) return CI;
1499 return B.CreateIntCast(Res, CI->getType(), true);
1500 }
1501
1502 return 0;
1503 }
1504};
1505
Bill Wendlingac178222008-05-05 21:37:59 +00001506} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001507
1508//===----------------------------------------------------------------------===//
1509// SimplifyLibCalls Pass Implementation
1510//===----------------------------------------------------------------------===//
1511
1512namespace {
1513 /// This pass optimizes well known library functions from libc and libm.
1514 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001515 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001516 TargetLibraryInfo *TLI;
1517
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001518 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001519 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001520 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
David Majnemerac782662012-05-15 11:46:21 +00001521 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1522 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1523 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1524 StrNCpyOpt StrNCpy;
1525 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001526 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001527 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001528 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001529 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001530 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001531 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1532 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001533 // Formatting and IO Optimizations
1534 SPrintFOpt SPrintF; PrintFOpt PrintF;
1535 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001536 PutsOpt Puts;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001537
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001538 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001539 public:
1540 static char ID; // Pass identification
David Majnemerac782662012-05-15 11:46:21 +00001541 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1542 StpCpy(false), StpCpyChk(true) {
Owen Anderson081c34b2010-10-19 17:21:58 +00001543 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1544 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001545 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001546 void InitOptimizations();
1547 bool runOnFunction(Function &F);
1548
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001549 void setDoesNotAccessMemory(Function &F);
1550 void setOnlyReadsMemory(Function &F);
1551 void setDoesNotThrow(Function &F);
1552 void setDoesNotCapture(Function &F, unsigned n);
1553 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001554 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001555
Chris Lattnere265ad82011-02-24 07:12:12 +00001556 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001557 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001558 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001559 }
1560 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001561} // end anonymous namespace.
1562
Chris Lattnerafbf4832011-02-24 07:16:14 +00001563char SimplifyLibCalls::ID = 0;
1564
1565INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1566 "Simplify well-known library calls", false, false)
1567INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1568INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1569 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001570
1571// Public interface to the Simplify LibCalls pass.
1572FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001573 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001574}
1575
Eli Friedman9d434db2011-11-17 01:27:36 +00001576void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1577 if (TLI->has(F))
1578 Optimizations[TLI->getName(F)] = Opt;
1579}
1580
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001581/// Optimizations - Populate the Optimizations map with all the optimizations
1582/// we know.
1583void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584 // String and Memory LibCall Optimizations
1585 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001586 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001587 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001588 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001589 Optimizations["strcmp"] = &StrCmp;
1590 Optimizations["strncmp"] = &StrNCmp;
1591 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001592 Optimizations["strncpy"] = &StrNCpy;
David Majnemerac782662012-05-15 11:46:21 +00001593 Optimizations["stpcpy"] = &StpCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001594 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001595 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001596 Optimizations["strtol"] = &StrTo;
1597 Optimizations["strtod"] = &StrTo;
1598 Optimizations["strtof"] = &StrTo;
1599 Optimizations["strtoul"] = &StrTo;
1600 Optimizations["strtoll"] = &StrTo;
1601 Optimizations["strtold"] = &StrTo;
1602 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001603 Optimizations["strspn"] = &StrSpn;
1604 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001605 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001606 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001607 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001608 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001609 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001610
Evan Cheng0289b412010-03-23 15:48:04 +00001611 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001612 Optimizations["__strcpy_chk"] = &StrCpyChk;
David Majnemerac782662012-05-15 11:46:21 +00001613 Optimizations["__stpcpy_chk"] = &StpCpyChk;
Evan Cheng0289b412010-03-23 15:48:04 +00001614
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001615 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001616 Optimizations["cosf"] = &Cos;
1617 Optimizations["cos"] = &Cos;
1618 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001619 Optimizations["powf"] = &Pow;
1620 Optimizations["pow"] = &Pow;
1621 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001622 Optimizations["llvm.pow.f32"] = &Pow;
1623 Optimizations["llvm.pow.f64"] = &Pow;
1624 Optimizations["llvm.pow.f80"] = &Pow;
1625 Optimizations["llvm.pow.f128"] = &Pow;
1626 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001627 Optimizations["exp2l"] = &Exp2;
1628 Optimizations["exp2"] = &Exp2;
1629 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001630 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1631 Optimizations["llvm.exp2.f128"] = &Exp2;
1632 Optimizations["llvm.exp2.f80"] = &Exp2;
1633 Optimizations["llvm.exp2.f64"] = &Exp2;
1634 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001635
Joe Groffd5bda5e2012-04-17 23:05:54 +00001636 if (TLI->has(LibFunc::floor) && TLI->has(LibFunc::floorf))
1637 Optimizations["floor"] = &UnaryDoubleFP;
1638 if (TLI->has(LibFunc::ceil) && TLI->has(LibFunc::ceilf))
1639 Optimizations["ceil"] = &UnaryDoubleFP;
1640 if (TLI->has(LibFunc::round) && TLI->has(LibFunc::roundf))
1641 Optimizations["round"] = &UnaryDoubleFP;
1642 if (TLI->has(LibFunc::rint) && TLI->has(LibFunc::rintf))
1643 Optimizations["rint"] = &UnaryDoubleFP;
1644 if (TLI->has(LibFunc::nearbyint) && TLI->has(LibFunc::nearbyintf))
1645 Optimizations["nearbyint"] = &UnaryDoubleFP;
Eric Christopher37c8b862009-10-07 21:14:25 +00001646
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001647 // Integer Optimizations
1648 Optimizations["ffs"] = &FFS;
1649 Optimizations["ffsl"] = &FFS;
1650 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001651 Optimizations["abs"] = &Abs;
1652 Optimizations["labs"] = &Abs;
1653 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001654 Optimizations["isdigit"] = &IsDigit;
1655 Optimizations["isascii"] = &IsAscii;
1656 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001657
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001658 // Formatting and IO Optimizations
1659 Optimizations["sprintf"] = &SPrintF;
1660 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001661 AddOpt(LibFunc::fwrite, &FWrite);
1662 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001663 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001664 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001665}
1666
1667
1668/// runOnFunction - Top level algorithm.
1669///
1670bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001671 TLI = &getAnalysis<TargetLibraryInfo>();
1672
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001673 if (Optimizations.empty())
1674 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001675
Dan Gohmanf14d9192009-08-18 00:48:13 +00001676 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001677
Owen Andersone922c022009-07-22 00:24:57 +00001678 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001679
1680 bool Changed = false;
1681 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1682 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1683 // Ignore non-calls.
1684 CallInst *CI = dyn_cast<CallInst>(I++);
1685 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001686
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001687 // Ignore indirect calls and calls to non-external functions.
1688 Function *Callee = CI->getCalledFunction();
1689 if (Callee == 0 || !Callee->isDeclaration() ||
1690 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1691 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001692
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001693 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001694 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1695 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001696
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001697 // Set the builder to the instruction after the call.
1698 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001699
Devang Patela2ab3992011-03-09 21:27:52 +00001700 // Use debug location of CI for all new instructions.
1701 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1702
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001703 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001704 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001705 if (Result == 0) continue;
1706
David Greene6a6b90e2010-01-05 01:27:21 +00001707 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1708 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001709
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001710 // Something changed!
1711 Changed = true;
1712 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001713
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001714 // Inspect the instruction after the call (which was potentially just
1715 // added) next.
1716 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001717
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001718 if (CI != Result && !CI->use_empty()) {
1719 CI->replaceAllUsesWith(Result);
1720 if (!Result->hasName())
1721 Result->takeName(CI);
1722 }
1723 CI->eraseFromParent();
1724 }
1725 }
1726 return Changed;
1727}
1728
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001729// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001730
1731void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1732 if (!F.doesNotAccessMemory()) {
1733 F.setDoesNotAccessMemory();
1734 ++NumAnnotated;
1735 Modified = true;
1736 }
1737}
1738void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1739 if (!F.onlyReadsMemory()) {
1740 F.setOnlyReadsMemory();
1741 ++NumAnnotated;
1742 Modified = true;
1743 }
1744}
1745void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1746 if (!F.doesNotThrow()) {
1747 F.setDoesNotThrow();
1748 ++NumAnnotated;
1749 Modified = true;
1750 }
1751}
1752void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1753 if (!F.doesNotCapture(n)) {
1754 F.setDoesNotCapture(n);
1755 ++NumAnnotated;
1756 Modified = true;
1757 }
1758}
1759void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1760 if (!F.doesNotAlias(n)) {
1761 F.setDoesNotAlias(n);
1762 ++NumAnnotated;
1763 Modified = true;
1764 }
1765}
1766
Chris Lattnere265ad82011-02-24 07:12:12 +00001767
1768void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001769 FunctionType *FTy = F.getFunctionType();
Chris Lattnere265ad82011-02-24 07:12:12 +00001770
1771 StringRef Name = F.getName();
1772 switch (Name[0]) {
1773 case 's':
1774 if (Name == "strlen") {
1775 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1776 return;
1777 setOnlyReadsMemory(F);
1778 setDoesNotThrow(F);
1779 setDoesNotCapture(F, 1);
1780 } else if (Name == "strchr" ||
1781 Name == "strrchr") {
1782 if (FTy->getNumParams() != 2 ||
1783 !FTy->getParamType(0)->isPointerTy() ||
1784 !FTy->getParamType(1)->isIntegerTy())
1785 return;
1786 setOnlyReadsMemory(F);
1787 setDoesNotThrow(F);
1788 } else if (Name == "strcpy" ||
1789 Name == "stpcpy" ||
1790 Name == "strcat" ||
1791 Name == "strtol" ||
1792 Name == "strtod" ||
1793 Name == "strtof" ||
1794 Name == "strtoul" ||
1795 Name == "strtoll" ||
1796 Name == "strtold" ||
1797 Name == "strncat" ||
1798 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001799 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001800 Name == "strtoull") {
1801 if (FTy->getNumParams() < 2 ||
1802 !FTy->getParamType(1)->isPointerTy())
1803 return;
1804 setDoesNotThrow(F);
1805 setDoesNotCapture(F, 2);
1806 } else if (Name == "strxfrm") {
1807 if (FTy->getNumParams() != 3 ||
1808 !FTy->getParamType(0)->isPointerTy() ||
1809 !FTy->getParamType(1)->isPointerTy())
1810 return;
1811 setDoesNotThrow(F);
1812 setDoesNotCapture(F, 1);
1813 setDoesNotCapture(F, 2);
1814 } else if (Name == "strcmp" ||
1815 Name == "strspn" ||
1816 Name == "strncmp" ||
1817 Name == "strcspn" ||
1818 Name == "strcoll" ||
1819 Name == "strcasecmp" ||
1820 Name == "strncasecmp") {
1821 if (FTy->getNumParams() < 2 ||
1822 !FTy->getParamType(0)->isPointerTy() ||
1823 !FTy->getParamType(1)->isPointerTy())
1824 return;
1825 setOnlyReadsMemory(F);
1826 setDoesNotThrow(F);
1827 setDoesNotCapture(F, 1);
1828 setDoesNotCapture(F, 2);
1829 } else if (Name == "strstr" ||
1830 Name == "strpbrk") {
1831 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1832 return;
1833 setOnlyReadsMemory(F);
1834 setDoesNotThrow(F);
1835 setDoesNotCapture(F, 2);
1836 } else if (Name == "strtok" ||
1837 Name == "strtok_r") {
1838 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1839 return;
1840 setDoesNotThrow(F);
1841 setDoesNotCapture(F, 2);
1842 } else if (Name == "scanf" ||
1843 Name == "setbuf" ||
1844 Name == "setvbuf") {
1845 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1846 return;
1847 setDoesNotThrow(F);
1848 setDoesNotCapture(F, 1);
1849 } else if (Name == "strdup" ||
1850 Name == "strndup") {
1851 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1852 !FTy->getParamType(0)->isPointerTy())
1853 return;
1854 setDoesNotThrow(F);
1855 setDoesNotAlias(F, 0);
1856 setDoesNotCapture(F, 1);
1857 } else if (Name == "stat" ||
1858 Name == "sscanf" ||
1859 Name == "sprintf" ||
1860 Name == "statvfs") {
1861 if (FTy->getNumParams() < 2 ||
1862 !FTy->getParamType(0)->isPointerTy() ||
1863 !FTy->getParamType(1)->isPointerTy())
1864 return;
1865 setDoesNotThrow(F);
1866 setDoesNotCapture(F, 1);
1867 setDoesNotCapture(F, 2);
1868 } else if (Name == "snprintf") {
1869 if (FTy->getNumParams() != 3 ||
1870 !FTy->getParamType(0)->isPointerTy() ||
1871 !FTy->getParamType(2)->isPointerTy())
1872 return;
1873 setDoesNotThrow(F);
1874 setDoesNotCapture(F, 1);
1875 setDoesNotCapture(F, 3);
1876 } else if (Name == "setitimer") {
1877 if (FTy->getNumParams() != 3 ||
1878 !FTy->getParamType(1)->isPointerTy() ||
1879 !FTy->getParamType(2)->isPointerTy())
1880 return;
1881 setDoesNotThrow(F);
1882 setDoesNotCapture(F, 2);
1883 setDoesNotCapture(F, 3);
1884 } else if (Name == "system") {
1885 if (FTy->getNumParams() != 1 ||
1886 !FTy->getParamType(0)->isPointerTy())
1887 return;
1888 // May throw; "system" is a valid pthread cancellation point.
1889 setDoesNotCapture(F, 1);
1890 }
1891 break;
1892 case 'm':
1893 if (Name == "malloc") {
1894 if (FTy->getNumParams() != 1 ||
1895 !FTy->getReturnType()->isPointerTy())
1896 return;
1897 setDoesNotThrow(F);
1898 setDoesNotAlias(F, 0);
1899 } else if (Name == "memcmp") {
1900 if (FTy->getNumParams() != 3 ||
1901 !FTy->getParamType(0)->isPointerTy() ||
1902 !FTy->getParamType(1)->isPointerTy())
1903 return;
1904 setOnlyReadsMemory(F);
1905 setDoesNotThrow(F);
1906 setDoesNotCapture(F, 1);
1907 setDoesNotCapture(F, 2);
1908 } else if (Name == "memchr" ||
1909 Name == "memrchr") {
1910 if (FTy->getNumParams() != 3)
1911 return;
1912 setOnlyReadsMemory(F);
1913 setDoesNotThrow(F);
1914 } else if (Name == "modf" ||
1915 Name == "modff" ||
1916 Name == "modfl" ||
1917 Name == "memcpy" ||
1918 Name == "memccpy" ||
1919 Name == "memmove") {
1920 if (FTy->getNumParams() < 2 ||
1921 !FTy->getParamType(1)->isPointerTy())
1922 return;
1923 setDoesNotThrow(F);
1924 setDoesNotCapture(F, 2);
1925 } else if (Name == "memalign") {
1926 if (!FTy->getReturnType()->isPointerTy())
1927 return;
1928 setDoesNotAlias(F, 0);
1929 } else if (Name == "mkdir" ||
1930 Name == "mktime") {
1931 if (FTy->getNumParams() == 0 ||
1932 !FTy->getParamType(0)->isPointerTy())
1933 return;
1934 setDoesNotThrow(F);
1935 setDoesNotCapture(F, 1);
1936 }
1937 break;
1938 case 'r':
1939 if (Name == "realloc") {
1940 if (FTy->getNumParams() != 2 ||
1941 !FTy->getParamType(0)->isPointerTy() ||
1942 !FTy->getReturnType()->isPointerTy())
1943 return;
1944 setDoesNotThrow(F);
1945 setDoesNotAlias(F, 0);
1946 setDoesNotCapture(F, 1);
1947 } else if (Name == "read") {
1948 if (FTy->getNumParams() != 3 ||
1949 !FTy->getParamType(1)->isPointerTy())
1950 return;
1951 // May throw; "read" is a valid pthread cancellation point.
1952 setDoesNotCapture(F, 2);
1953 } else if (Name == "rmdir" ||
1954 Name == "rewind" ||
1955 Name == "remove" ||
1956 Name == "realpath") {
1957 if (FTy->getNumParams() < 1 ||
1958 !FTy->getParamType(0)->isPointerTy())
1959 return;
1960 setDoesNotThrow(F);
1961 setDoesNotCapture(F, 1);
1962 } else if (Name == "rename" ||
1963 Name == "readlink") {
1964 if (FTy->getNumParams() < 2 ||
1965 !FTy->getParamType(0)->isPointerTy() ||
1966 !FTy->getParamType(1)->isPointerTy())
1967 return;
1968 setDoesNotThrow(F);
1969 setDoesNotCapture(F, 1);
1970 setDoesNotCapture(F, 2);
1971 }
1972 break;
1973 case 'w':
1974 if (Name == "write") {
1975 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1976 return;
1977 // May throw; "write" is a valid pthread cancellation point.
1978 setDoesNotCapture(F, 2);
1979 }
1980 break;
1981 case 'b':
1982 if (Name == "bcopy") {
1983 if (FTy->getNumParams() != 3 ||
1984 !FTy->getParamType(0)->isPointerTy() ||
1985 !FTy->getParamType(1)->isPointerTy())
1986 return;
1987 setDoesNotThrow(F);
1988 setDoesNotCapture(F, 1);
1989 setDoesNotCapture(F, 2);
1990 } else if (Name == "bcmp") {
1991 if (FTy->getNumParams() != 3 ||
1992 !FTy->getParamType(0)->isPointerTy() ||
1993 !FTy->getParamType(1)->isPointerTy())
1994 return;
1995 setDoesNotThrow(F);
1996 setOnlyReadsMemory(F);
1997 setDoesNotCapture(F, 1);
1998 setDoesNotCapture(F, 2);
1999 } else if (Name == "bzero") {
2000 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2001 return;
2002 setDoesNotThrow(F);
2003 setDoesNotCapture(F, 1);
2004 }
2005 break;
2006 case 'c':
2007 if (Name == "calloc") {
2008 if (FTy->getNumParams() != 2 ||
2009 !FTy->getReturnType()->isPointerTy())
2010 return;
2011 setDoesNotThrow(F);
2012 setDoesNotAlias(F, 0);
2013 } else if (Name == "chmod" ||
2014 Name == "chown" ||
2015 Name == "ctermid" ||
2016 Name == "clearerr" ||
2017 Name == "closedir") {
2018 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2019 return;
2020 setDoesNotThrow(F);
2021 setDoesNotCapture(F, 1);
2022 }
2023 break;
2024 case 'a':
2025 if (Name == "atoi" ||
2026 Name == "atol" ||
2027 Name == "atof" ||
2028 Name == "atoll") {
2029 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2030 return;
2031 setDoesNotThrow(F);
2032 setOnlyReadsMemory(F);
2033 setDoesNotCapture(F, 1);
2034 } else if (Name == "access") {
2035 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2036 return;
2037 setDoesNotThrow(F);
2038 setDoesNotCapture(F, 1);
2039 }
2040 break;
2041 case 'f':
2042 if (Name == "fopen") {
2043 if (FTy->getNumParams() != 2 ||
2044 !FTy->getReturnType()->isPointerTy() ||
2045 !FTy->getParamType(0)->isPointerTy() ||
2046 !FTy->getParamType(1)->isPointerTy())
2047 return;
2048 setDoesNotThrow(F);
2049 setDoesNotAlias(F, 0);
2050 setDoesNotCapture(F, 1);
2051 setDoesNotCapture(F, 2);
2052 } else if (Name == "fdopen") {
2053 if (FTy->getNumParams() != 2 ||
2054 !FTy->getReturnType()->isPointerTy() ||
2055 !FTy->getParamType(1)->isPointerTy())
2056 return;
2057 setDoesNotThrow(F);
2058 setDoesNotAlias(F, 0);
2059 setDoesNotCapture(F, 2);
2060 } else if (Name == "feof" ||
2061 Name == "free" ||
2062 Name == "fseek" ||
2063 Name == "ftell" ||
2064 Name == "fgetc" ||
2065 Name == "fseeko" ||
2066 Name == "ftello" ||
2067 Name == "fileno" ||
2068 Name == "fflush" ||
2069 Name == "fclose" ||
2070 Name == "fsetpos" ||
2071 Name == "flockfile" ||
2072 Name == "funlockfile" ||
2073 Name == "ftrylockfile") {
2074 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2075 return;
2076 setDoesNotThrow(F);
2077 setDoesNotCapture(F, 1);
2078 } else if (Name == "ferror") {
2079 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2080 return;
2081 setDoesNotThrow(F);
2082 setDoesNotCapture(F, 1);
2083 setOnlyReadsMemory(F);
2084 } else if (Name == "fputc" ||
2085 Name == "fstat" ||
2086 Name == "frexp" ||
2087 Name == "frexpf" ||
2088 Name == "frexpl" ||
2089 Name == "fstatvfs") {
2090 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2091 return;
2092 setDoesNotThrow(F);
2093 setDoesNotCapture(F, 2);
2094 } else if (Name == "fgets") {
2095 if (FTy->getNumParams() != 3 ||
2096 !FTy->getParamType(0)->isPointerTy() ||
2097 !FTy->getParamType(2)->isPointerTy())
2098 return;
2099 setDoesNotThrow(F);
2100 setDoesNotCapture(F, 3);
2101 } else if (Name == "fread" ||
2102 Name == "fwrite") {
2103 if (FTy->getNumParams() != 4 ||
2104 !FTy->getParamType(0)->isPointerTy() ||
2105 !FTy->getParamType(3)->isPointerTy())
2106 return;
2107 setDoesNotThrow(F);
2108 setDoesNotCapture(F, 1);
2109 setDoesNotCapture(F, 4);
2110 } else if (Name == "fputs" ||
2111 Name == "fscanf" ||
2112 Name == "fprintf" ||
2113 Name == "fgetpos") {
2114 if (FTy->getNumParams() < 2 ||
2115 !FTy->getParamType(0)->isPointerTy() ||
2116 !FTy->getParamType(1)->isPointerTy())
2117 return;
2118 setDoesNotThrow(F);
2119 setDoesNotCapture(F, 1);
2120 setDoesNotCapture(F, 2);
2121 }
2122 break;
2123 case 'g':
2124 if (Name == "getc" ||
2125 Name == "getlogin_r" ||
2126 Name == "getc_unlocked") {
2127 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2128 return;
2129 setDoesNotThrow(F);
2130 setDoesNotCapture(F, 1);
2131 } else if (Name == "getenv") {
2132 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2133 return;
2134 setDoesNotThrow(F);
2135 setOnlyReadsMemory(F);
2136 setDoesNotCapture(F, 1);
2137 } else if (Name == "gets" ||
2138 Name == "getchar") {
2139 setDoesNotThrow(F);
2140 } else if (Name == "getitimer") {
2141 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2142 return;
2143 setDoesNotThrow(F);
2144 setDoesNotCapture(F, 2);
2145 } else if (Name == "getpwnam") {
2146 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2147 return;
2148 setDoesNotThrow(F);
2149 setDoesNotCapture(F, 1);
2150 }
2151 break;
2152 case 'u':
2153 if (Name == "ungetc") {
2154 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2155 return;
2156 setDoesNotThrow(F);
2157 setDoesNotCapture(F, 2);
2158 } else if (Name == "uname" ||
2159 Name == "unlink" ||
2160 Name == "unsetenv") {
2161 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2162 return;
2163 setDoesNotThrow(F);
2164 setDoesNotCapture(F, 1);
2165 } else if (Name == "utime" ||
2166 Name == "utimes") {
2167 if (FTy->getNumParams() != 2 ||
2168 !FTy->getParamType(0)->isPointerTy() ||
2169 !FTy->getParamType(1)->isPointerTy())
2170 return;
2171 setDoesNotThrow(F);
2172 setDoesNotCapture(F, 1);
2173 setDoesNotCapture(F, 2);
2174 }
2175 break;
2176 case 'p':
2177 if (Name == "putc") {
2178 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2179 return;
2180 setDoesNotThrow(F);
2181 setDoesNotCapture(F, 2);
2182 } else if (Name == "puts" ||
2183 Name == "printf" ||
2184 Name == "perror") {
2185 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2186 return;
2187 setDoesNotThrow(F);
2188 setDoesNotCapture(F, 1);
2189 } else if (Name == "pread" ||
2190 Name == "pwrite") {
2191 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2192 return;
2193 // May throw; these are valid pthread cancellation points.
2194 setDoesNotCapture(F, 2);
2195 } else if (Name == "putchar") {
2196 setDoesNotThrow(F);
2197 } else if (Name == "popen") {
2198 if (FTy->getNumParams() != 2 ||
2199 !FTy->getReturnType()->isPointerTy() ||
2200 !FTy->getParamType(0)->isPointerTy() ||
2201 !FTy->getParamType(1)->isPointerTy())
2202 return;
2203 setDoesNotThrow(F);
2204 setDoesNotAlias(F, 0);
2205 setDoesNotCapture(F, 1);
2206 setDoesNotCapture(F, 2);
2207 } else if (Name == "pclose") {
2208 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2209 return;
2210 setDoesNotThrow(F);
2211 setDoesNotCapture(F, 1);
2212 }
2213 break;
2214 case 'v':
2215 if (Name == "vscanf") {
2216 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2217 return;
2218 setDoesNotThrow(F);
2219 setDoesNotCapture(F, 1);
2220 } else if (Name == "vsscanf" ||
2221 Name == "vfscanf") {
2222 if (FTy->getNumParams() != 3 ||
2223 !FTy->getParamType(1)->isPointerTy() ||
2224 !FTy->getParamType(2)->isPointerTy())
2225 return;
2226 setDoesNotThrow(F);
2227 setDoesNotCapture(F, 1);
2228 setDoesNotCapture(F, 2);
2229 } else if (Name == "valloc") {
2230 if (!FTy->getReturnType()->isPointerTy())
2231 return;
2232 setDoesNotThrow(F);
2233 setDoesNotAlias(F, 0);
2234 } else if (Name == "vprintf") {
2235 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2236 return;
2237 setDoesNotThrow(F);
2238 setDoesNotCapture(F, 1);
2239 } else if (Name == "vfprintf" ||
2240 Name == "vsprintf") {
2241 if (FTy->getNumParams() != 3 ||
2242 !FTy->getParamType(0)->isPointerTy() ||
2243 !FTy->getParamType(1)->isPointerTy())
2244 return;
2245 setDoesNotThrow(F);
2246 setDoesNotCapture(F, 1);
2247 setDoesNotCapture(F, 2);
2248 } else if (Name == "vsnprintf") {
2249 if (FTy->getNumParams() != 4 ||
2250 !FTy->getParamType(0)->isPointerTy() ||
2251 !FTy->getParamType(2)->isPointerTy())
2252 return;
2253 setDoesNotThrow(F);
2254 setDoesNotCapture(F, 1);
2255 setDoesNotCapture(F, 3);
2256 }
2257 break;
2258 case 'o':
2259 if (Name == "open") {
2260 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2261 return;
2262 // May throw; "open" is a valid pthread cancellation point.
2263 setDoesNotCapture(F, 1);
2264 } else if (Name == "opendir") {
2265 if (FTy->getNumParams() != 1 ||
2266 !FTy->getReturnType()->isPointerTy() ||
2267 !FTy->getParamType(0)->isPointerTy())
2268 return;
2269 setDoesNotThrow(F);
2270 setDoesNotAlias(F, 0);
2271 setDoesNotCapture(F, 1);
2272 }
2273 break;
2274 case 't':
2275 if (Name == "tmpfile") {
2276 if (!FTy->getReturnType()->isPointerTy())
2277 return;
2278 setDoesNotThrow(F);
2279 setDoesNotAlias(F, 0);
2280 } else if (Name == "times") {
2281 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2282 return;
2283 setDoesNotThrow(F);
2284 setDoesNotCapture(F, 1);
2285 }
2286 break;
2287 case 'h':
2288 if (Name == "htonl" ||
2289 Name == "htons") {
2290 setDoesNotThrow(F);
2291 setDoesNotAccessMemory(F);
2292 }
2293 break;
2294 case 'n':
2295 if (Name == "ntohl" ||
2296 Name == "ntohs") {
2297 setDoesNotThrow(F);
2298 setDoesNotAccessMemory(F);
2299 }
2300 break;
2301 case 'l':
2302 if (Name == "lstat") {
2303 if (FTy->getNumParams() != 2 ||
2304 !FTy->getParamType(0)->isPointerTy() ||
2305 !FTy->getParamType(1)->isPointerTy())
2306 return;
2307 setDoesNotThrow(F);
2308 setDoesNotCapture(F, 1);
2309 setDoesNotCapture(F, 2);
2310 } else if (Name == "lchown") {
2311 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2312 return;
2313 setDoesNotThrow(F);
2314 setDoesNotCapture(F, 1);
2315 }
2316 break;
2317 case 'q':
2318 if (Name == "qsort") {
2319 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2320 return;
2321 // May throw; places call through function pointer.
2322 setDoesNotCapture(F, 4);
2323 }
2324 break;
2325 case '_':
2326 if (Name == "__strdup" ||
2327 Name == "__strndup") {
2328 if (FTy->getNumParams() < 1 ||
2329 !FTy->getReturnType()->isPointerTy() ||
2330 !FTy->getParamType(0)->isPointerTy())
2331 return;
2332 setDoesNotThrow(F);
2333 setDoesNotAlias(F, 0);
2334 setDoesNotCapture(F, 1);
2335 } else if (Name == "__strtok_r") {
2336 if (FTy->getNumParams() != 3 ||
2337 !FTy->getParamType(1)->isPointerTy())
2338 return;
2339 setDoesNotThrow(F);
2340 setDoesNotCapture(F, 2);
2341 } else if (Name == "_IO_getc") {
2342 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2343 return;
2344 setDoesNotThrow(F);
2345 setDoesNotCapture(F, 1);
2346 } else if (Name == "_IO_putc") {
2347 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2348 return;
2349 setDoesNotThrow(F);
2350 setDoesNotCapture(F, 2);
2351 }
2352 break;
2353 case 1:
2354 if (Name == "\1__isoc99_scanf") {
2355 if (FTy->getNumParams() < 1 ||
2356 !FTy->getParamType(0)->isPointerTy())
2357 return;
2358 setDoesNotThrow(F);
2359 setDoesNotCapture(F, 1);
2360 } else if (Name == "\1stat64" ||
2361 Name == "\1lstat64" ||
2362 Name == "\1statvfs64" ||
2363 Name == "\1__isoc99_sscanf") {
2364 if (FTy->getNumParams() < 1 ||
2365 !FTy->getParamType(0)->isPointerTy() ||
2366 !FTy->getParamType(1)->isPointerTy())
2367 return;
2368 setDoesNotThrow(F);
2369 setDoesNotCapture(F, 1);
2370 setDoesNotCapture(F, 2);
2371 } else if (Name == "\1fopen64") {
2372 if (FTy->getNumParams() != 2 ||
2373 !FTy->getReturnType()->isPointerTy() ||
2374 !FTy->getParamType(0)->isPointerTy() ||
2375 !FTy->getParamType(1)->isPointerTy())
2376 return;
2377 setDoesNotThrow(F);
2378 setDoesNotAlias(F, 0);
2379 setDoesNotCapture(F, 1);
2380 setDoesNotCapture(F, 2);
2381 } else if (Name == "\1fseeko64" ||
2382 Name == "\1ftello64") {
2383 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2384 return;
2385 setDoesNotThrow(F);
2386 setDoesNotCapture(F, 1);
2387 } else if (Name == "\1tmpfile64") {
2388 if (!FTy->getReturnType()->isPointerTy())
2389 return;
2390 setDoesNotThrow(F);
2391 setDoesNotAlias(F, 0);
2392 } else if (Name == "\1fstat64" ||
2393 Name == "\1fstatvfs64") {
2394 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2395 return;
2396 setDoesNotThrow(F);
2397 setDoesNotCapture(F, 2);
2398 } else if (Name == "\1open64") {
2399 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2400 return;
2401 // May throw; "open" is a valid pthread cancellation point.
2402 setDoesNotCapture(F, 1);
2403 }
2404 break;
2405 }
2406}
2407
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002408/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002409///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002410bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002411 Modified = false;
2412 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2413 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002414 if (F.isDeclaration() && F.hasName())
2415 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002416 }
2417 return Modified;
2418}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002419
2420// TODO:
2421// Additional cases that we need to add to this file:
2422//
2423// cbrt:
2424// * cbrt(expN(X)) -> expN(x/3)
2425// * cbrt(sqrt(x)) -> pow(x,1/6)
2426// * cbrt(sqrt(x)) -> pow(x,1/9)
2427//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002428// exp, expf, expl:
2429// * exp(log(x)) -> x
2430//
2431// log, logf, logl:
2432// * log(exp(x)) -> x
2433// * log(x**y) -> y*log(x)
2434// * log(exp(y)) -> y*log(e)
2435// * log(exp2(y)) -> y*log(2)
2436// * log(exp10(y)) -> y*log(10)
2437// * log(sqrt(x)) -> 0.5*log(x)
2438// * log(pow(x,y)) -> y*log(x)
2439//
2440// lround, lroundf, lroundl:
2441// * lround(cnst) -> cnst'
2442//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002443// pow, powf, powl:
2444// * pow(exp(x),y) -> exp(x*y)
2445// * pow(sqrt(x),y) -> pow(x,y*0.5)
2446// * pow(pow(x,y),z)-> pow(x,y*z)
2447//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002448// round, roundf, roundl:
2449// * round(cnst) -> cnst'
2450//
2451// signbit:
2452// * signbit(cnst) -> cnst'
2453// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2454//
2455// sqrt, sqrtf, sqrtl:
2456// * sqrt(expN(x)) -> expN(x*0.5)
2457// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2458// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2459//
Chris Lattner18c7f802012-02-05 02:29:43 +00002460// strchr:
2461// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002462// tan, tanf, tanl:
2463// * tan(atan(x)) -> x
2464//
2465// trunc, truncf, truncl:
2466// * trunc(cnst) -> cnst'
2467//
2468//