blob: 909ac8bde52364ff7487212858fb0f874a430ae5 [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
Eric Christopherb6174e32010-03-05 22:25:30 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000026#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/Analysis/ValueTracking.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000031#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetLibraryInfo.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}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000103
Richard Osborne36498242011-03-03 13:17:51 +0000104static 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
Nuno Lopescd31fc72012-07-26 17:10:46 +0000160 return EmitStrLenMemCpy(Src, Dst, Len, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000161 }
162
Nuno Lopescd31fc72012-07-26 17:10:46 +0000163 Value *EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000164 // We need to find the end of the destination string. That's where the
165 // memory is to be moved to. We just generate a call to strlen.
Nuno Lopes51004df2012-07-25 16:46:31 +0000166 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000167 if (!DstLen)
168 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000169
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000170 // Now that we have the destination's length, we must index into the
171 // destination's pointer to get the actual memcpy destination (end of
172 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000173 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000174
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000175 // We have enough information to now generate the memcpy call to do the
176 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000177 B.CreateMemCpy(CpyDst, Src,
178 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000179 return Dst;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000180 }
181};
182
183//===---------------------------------------===//
184// 'strncat' Optimizations
185
Chris Lattner3e8b6632009-09-02 06:11:42 +0000186struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000187 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
188 // Verify the "strncat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000189 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000190 if (FT->getNumParams() != 3 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000191 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000192 FT->getParamType(0) != FT->getReturnType() ||
193 FT->getParamType(1) != FT->getReturnType() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000194 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000195 return 0;
196
197 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000198 Value *Dst = CI->getArgOperand(0);
199 Value *Src = CI->getArgOperand(1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000200 uint64_t Len;
201
202 // We don't do anything if length is not constant
Gabor Greifaee5dc12010-06-24 10:42:46 +0000203 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000204 Len = LengthArg->getZExtValue();
205 else
206 return 0;
207
208 // See if we can get the length of the input string.
209 uint64_t SrcLen = GetStringLength(Src);
210 if (SrcLen == 0) return 0;
211 --SrcLen; // Unbias length.
212
213 // Handle the simple, do-nothing cases:
214 // strncat(x, "", c) -> x
215 // strncat(x, c, 0) -> x
216 if (SrcLen == 0 || Len == 0) return Dst;
217
Dan Gohmanf14d9192009-08-18 00:48:13 +0000218 // These optimizations require TargetData.
219 if (!TD) return 0;
220
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000221 // We don't optimize this case
222 if (Len < SrcLen) return 0;
223
224 // strncat(x, s, c) -> strcat(x, s)
225 // s is constant so the strcat can be optimized further
Nuno Lopescd31fc72012-07-26 17:10:46 +0000226 return EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000227 }
228};
229
230//===---------------------------------------===//
231// 'strchr' Optimizations
232
Chris Lattner3e8b6632009-09-02 06:11:42 +0000233struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000234 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000235 // Verify the "strchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000236 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000237 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000238 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000239 FT->getParamType(0) != FT->getReturnType() ||
240 !FT->getParamType(1)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000241 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000242
Gabor Greifaee5dc12010-06-24 10:42:46 +0000243 Value *SrcStr = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000244
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000245 // If the second operand is non-constant, see if we can compute the length
246 // of the input string and turn this into memchr.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000247 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000248 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000249 // These optimizations require TargetData.
250 if (!TD) return 0;
251
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000252 uint64_t Len = GetStringLength(SrcStr);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000253 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000254 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000255
Gabor Greifaee5dc12010-06-24 10:42:46 +0000256 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Eric Christopherb6174e32010-03-05 22:25:30 +0000257 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Nuno Lopes51004df2012-07-25 16:46:31 +0000258 B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000259 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000260
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000261 // Otherwise, the character is a constant, see if the first argument is
262 // a string literal. If so, we can constant fold.
Chris Lattner18c7f802012-02-05 02:29:43 +0000263 StringRef Str;
264 if (!getConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000265 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000266
Chris Lattner18c7f802012-02-05 02:29:43 +0000267 // Compute the offset, make sure to handle the case when we're searching for
268 // zero (a weird way to spell strlen).
269 size_t I = CharC->getSExtValue() == 0 ?
270 Str.size() : Str.find(CharC->getSExtValue());
271 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
Benjamin Kramere2609902010-09-29 22:29:12 +0000272 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000273
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000274 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000275 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000276 }
277};
278
279//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000280// 'strrchr' Optimizations
281
282struct StrRChrOpt : public LibCallOptimization {
283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
284 // Verify the "strrchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000285 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000286 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000287 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000288 FT->getParamType(0) != FT->getReturnType() ||
289 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000290 return 0;
291
292 Value *SrcStr = CI->getArgOperand(0);
293 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
294
295 // Cannot fold anything if we're not looking for a constant.
296 if (!CharC)
297 return 0;
298
Chris Lattner18c7f802012-02-05 02:29:43 +0000299 StringRef Str;
300 if (!getConstantStringInfo(SrcStr, Str)) {
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000301 // strrchr(s, 0) -> strchr(s, 0)
302 if (TD && CharC->isZero())
Nuno Lopes51004df2012-07-25 16:46:31 +0000303 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000304 return 0;
305 }
306
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000307 // Compute the offset.
Chris Lattner18c7f802012-02-05 02:29:43 +0000308 size_t I = CharC->getSExtValue() == 0 ?
309 Str.size() : Str.rfind(CharC->getSExtValue());
310 if (I == StringRef::npos) // Didn't find the char. Return null.
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000311 return Constant::getNullValue(CI->getType());
312
313 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000314 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000315 }
316};
317
318//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000319// 'strcmp' Optimizations
320
Chris Lattner3e8b6632009-09-02 06:11:42 +0000321struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000322 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000323 // Verify the "strcmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000324 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000325 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000326 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000327 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000328 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000329 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000330
Gabor Greifaee5dc12010-06-24 10:42:46 +0000331 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000332 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000333 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000334
Chris Lattner18c7f802012-02-05 02:29:43 +0000335 StringRef Str1, Str2;
336 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
337 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000338
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000339 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000340 if (HasStr1 && HasStr2)
Chris Lattner18c7f802012-02-05 02:29:43 +0000341 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
Eli Friedman79286082011-10-05 22:27:16 +0000342
343 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
344 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
345 CI->getType()));
346
347 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
348 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000349
350 // strcmp(P, "x") -> memcmp(P, "x", 2)
351 uint64_t Len1 = GetStringLength(Str1P);
352 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000353 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000354 // These optimizations require TargetData.
355 if (!TD) return 0;
356
Nick Lewycky13a09e22008-12-21 00:19:21 +0000357 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000358 ConstantInt::get(TD->getIntPtrType(*Context),
Nuno Lopes51004df2012-07-25 16:46:31 +0000359 std::min(Len1, Len2)), B, TD, TLI);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000360 }
361
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000362 return 0;
363 }
364};
365
366//===---------------------------------------===//
367// 'strncmp' Optimizations
368
Chris Lattner3e8b6632009-09-02 06:11:42 +0000369struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000370 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000371 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000372 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000373 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000374 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000375 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000376 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000377 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000378 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000379
Gabor Greifaee5dc12010-06-24 10:42:46 +0000380 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000381 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000382 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000383
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000384 // Get the length argument if it is constant.
385 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000386 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000387 Length = LengthArg->getZExtValue();
388 else
389 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000390
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000391 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000392 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000393
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000394 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000395 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000396
Chris Lattner18c7f802012-02-05 02:29:43 +0000397 StringRef Str1, Str2;
398 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
399 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000400
Eli Friedman79286082011-10-05 22:27:16 +0000401 // strncmp(x, y) -> cnst (if both x and y are constant strings)
402 if (HasStr1 && HasStr2) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000403 StringRef SubStr1 = Str1.substr(0, Length);
404 StringRef SubStr2 = Str2.substr(0, Length);
Eli Friedman79286082011-10-05 22:27:16 +0000405 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
406 }
407
408 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
409 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
410 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000411
Bill Wendling0582ae92009-03-13 04:39:26 +0000412 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000413 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000414
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000415 return 0;
416 }
417};
418
419
420//===---------------------------------------===//
421// 'strcpy' Optimizations
422
Chris Lattner3e8b6632009-09-02 06:11:42 +0000423struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000424 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
425
426 StrCpyOpt(bool c) : OptChkCall(c) {}
427
Eric Christopher7a61d702008-08-08 19:39:37 +0000428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000429 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000430 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000431 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000432 if (FT->getNumParams() != NumParams ||
433 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000434 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000435 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000436 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000437
Gabor Greifaee5dc12010-06-24 10:42:46 +0000438 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000439 if (Dst == Src) // strcpy(x,x) -> x
440 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000441
Dan Gohmanf14d9192009-08-18 00:48:13 +0000442 // These optimizations require TargetData.
443 if (!TD) return 0;
444
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000445 // See if we can get the length of the input string.
446 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000447 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000448
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000449 // We have enough information to now generate the memcpy call to do the
450 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Nuno Lopescd31fc72012-07-26 17:10:46 +0000451 if (!OptChkCall ||
452 !EmitMemCpyChk(Dst, Src,
453 ConstantInt::get(TD->getIntPtrType(*Context), Len),
454 CI->getArgOperand(2), B, TD, TLI))
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);
Nuno Lopes51004df2012-07-25 16:46:31 +0000483 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
484 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
485 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
486 }
David Majnemerac782662012-05-15 11:46:21 +0000487
488 // See if we can get the length of the input string.
489 uint64_t Len = GetStringLength(Src);
490 if (Len == 0) return 0;
491
492 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
493 Value *DstEnd = B.CreateGEP(Dst,
494 ConstantInt::get(TD->getIntPtrType(*Context),
495 Len - 1));
496
497 // We have enough information to now generate the memcpy call to do the
498 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Nuno Lopescd31fc72012-07-26 17:10:46 +0000499 if (!OptChkCall || !EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B,
500 TD, TLI))
David Majnemerac782662012-05-15 11:46:21 +0000501 B.CreateMemCpy(Dst, Src, LenV, 1);
502 return DstEnd;
503 }
504};
505
506//===---------------------------------------===//
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000507// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000508
Chris Lattner3e8b6632009-09-02 06:11:42 +0000509struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000510 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000511 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000512 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
513 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000514 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000515 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000516 return 0;
517
Gabor Greifaee5dc12010-06-24 10:42:46 +0000518 Value *Dst = CI->getArgOperand(0);
519 Value *Src = CI->getArgOperand(1);
520 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000521
522 // See if we can get the length of the input string.
523 uint64_t SrcLen = GetStringLength(Src);
524 if (SrcLen == 0) return 0;
525 --SrcLen;
526
527 if (SrcLen == 0) {
528 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000529 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000530 return Dst;
531 }
532
533 uint64_t Len;
534 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
535 Len = LengthArg->getZExtValue();
536 else
537 return 0;
538
539 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
540
Dan Gohmanf14d9192009-08-18 00:48:13 +0000541 // These optimizations require TargetData.
542 if (!TD) return 0;
543
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000544 // Let strncpy handle the zero padding
545 if (Len > SrcLen+1) return 0;
546
547 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000548 B.CreateMemCpy(Dst, Src,
549 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000550
551 return Dst;
552 }
553};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000554
555//===---------------------------------------===//
556// 'strlen' Optimizations
557
Chris Lattner3e8b6632009-09-02 06:11:42 +0000558struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000559 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000560 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000561 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000562 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000563 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000564 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000565
Gabor Greifaee5dc12010-06-24 10:42:46 +0000566 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000567
568 // Constant folding: strlen("xyz") -> 3
569 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000570 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000571
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000572 // strlen(x) != 0 --> *x != 0
573 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000574 if (IsOnlyUsedInZeroEqualityComparison(CI))
575 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
576 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000577 }
578};
579
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000580
581//===---------------------------------------===//
582// 'strpbrk' Optimizations
583
584struct StrPBrkOpt : public LibCallOptimization {
585 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000586 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000587 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000588 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000589 FT->getParamType(1) != FT->getParamType(0) ||
590 FT->getReturnType() != FT->getParamType(0))
591 return 0;
592
Chris Lattner18c7f802012-02-05 02:29:43 +0000593 StringRef S1, S2;
594 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
595 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000596
597 // strpbrk(s, "") -> NULL
598 // strpbrk("", s) -> NULL
599 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
600 return Constant::getNullValue(CI->getType());
601
602 // Constant folding.
603 if (HasS1 && HasS2) {
604 size_t I = S1.find_first_of(S2);
605 if (I == std::string::npos) // No match.
606 return Constant::getNullValue(CI->getType());
607
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000608 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000609 }
610
611 // strpbrk(s, "a") -> strchr(s, 'a')
612 if (TD && HasS2 && S2.size() == 1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000613 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000614
615 return 0;
616 }
617};
618
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000619//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000620// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000621
Chris Lattner3e8b6632009-09-02 06:11:42 +0000622struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000624 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000625 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000626 !FT->getParamType(0)->isPointerTy() ||
627 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000628 return 0;
629
Gabor Greifaee5dc12010-06-24 10:42:46 +0000630 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000631 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000632 // With a null EndPtr, this function won't capture the main argument.
633 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000634 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000635 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000636
637 return 0;
638 }
639};
640
Chris Lattner24604112009-12-16 09:32:05 +0000641//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000642// 'strspn' Optimizations
643
644struct StrSpnOpt : public LibCallOptimization {
645 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000646 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000647 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000648 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000649 FT->getParamType(1) != FT->getParamType(0) ||
650 !FT->getReturnType()->isIntegerTy())
651 return 0;
652
Chris Lattner18c7f802012-02-05 02:29:43 +0000653 StringRef S1, S2;
654 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
655 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000656
657 // strspn(s, "") -> 0
658 // strspn("", s) -> 0
659 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
660 return Constant::getNullValue(CI->getType());
661
662 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000663 if (HasS1 && HasS2) {
664 size_t Pos = S1.find_first_not_of(S2);
665 if (Pos == StringRef::npos) Pos = S1.size();
666 return ConstantInt::get(CI->getType(), Pos);
667 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000668
669 return 0;
670 }
671};
672
673//===---------------------------------------===//
674// 'strcspn' Optimizations
675
676struct StrCSpnOpt : public LibCallOptimization {
677 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000678 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000679 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000680 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000681 FT->getParamType(1) != FT->getParamType(0) ||
682 !FT->getReturnType()->isIntegerTy())
683 return 0;
684
Chris Lattner18c7f802012-02-05 02:29:43 +0000685 StringRef S1, S2;
686 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
687 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000688
689 // strcspn("", s) -> 0
690 if (HasS1 && S1.empty())
691 return Constant::getNullValue(CI->getType());
692
693 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000694 if (HasS1 && HasS2) {
695 size_t Pos = S1.find_first_of(S2);
696 if (Pos == StringRef::npos) Pos = S1.size();
697 return ConstantInt::get(CI->getType(), Pos);
698 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000699
700 // strcspn(s, "") -> strlen(s)
701 if (TD && HasS2 && S2.empty())
Nuno Lopes51004df2012-07-25 16:46:31 +0000702 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000703
704 return 0;
705 }
706};
707
708//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000709// 'strstr' Optimizations
710
711struct StrStrOpt : public LibCallOptimization {
712 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000713 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000714 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000715 !FT->getParamType(0)->isPointerTy() ||
716 !FT->getParamType(1)->isPointerTy() ||
717 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000718 return 0;
719
720 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000721 if (CI->getArgOperand(0) == CI->getArgOperand(1))
722 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000723
Benjamin Kramer386e9182010-06-15 21:34:25 +0000724 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000725 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000726 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
727 if (!StrLen)
728 return 0;
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000729 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Nuno Lopes51004df2012-07-25 16:46:31 +0000730 StrLen, B, TD, TLI);
731 if (!StrNCmp)
732 return 0;
Benjamin Kramer386e9182010-06-15 21:34:25 +0000733 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
734 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000735 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000736 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
737 ConstantInt::getNullValue(StrNCmp->getType()),
738 "cmp");
739 Old->replaceAllUsesWith(Cmp);
740 Old->eraseFromParent();
741 }
742 return CI;
743 }
744
Chris Lattner24604112009-12-16 09:32:05 +0000745 // See if either input string is a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000746 StringRef SearchStr, ToFindStr;
747 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
748 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000749
Chris Lattner24604112009-12-16 09:32:05 +0000750 // fold strstr(x, "") -> x.
751 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000752 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000753
Chris Lattner24604112009-12-16 09:32:05 +0000754 // If both strings are known, constant fold it.
755 if (HasStr1 && HasStr2) {
756 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000757
Chris Lattner18c7f802012-02-05 02:29:43 +0000758 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Chris Lattner24604112009-12-16 09:32:05 +0000759 return Constant::getNullValue(CI->getType());
760
761 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000762 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000763 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
764 return B.CreateBitCast(Result, CI->getType());
765 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000766
Chris Lattner24604112009-12-16 09:32:05 +0000767 // fold strstr(x, "y") -> strchr(x, 'y').
Nuno Lopes51004df2012-07-25 16:46:31 +0000768 if (HasStr2 && ToFindStr.size() == 1) {
769 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
770 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
771 }
Chris Lattner24604112009-12-16 09:32:05 +0000772 return 0;
773 }
774};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000775
Nick Lewycky4c498412009-02-13 15:31:46 +0000776
777//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000778// 'memcmp' Optimizations
779
Chris Lattner3e8b6632009-09-02 06:11:42 +0000780struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000781 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000782 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000783 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000785 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000786 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000787
Gabor Greifaee5dc12010-06-24 10:42:46 +0000788 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000789
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000790 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000791 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000792
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000793 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000794 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000795 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000796 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000797
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000798 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000799 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000800
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000801 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
802 if (Len == 1) {
803 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
804 CI->getType(), "lhsv");
805 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
806 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000807 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000808 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000809
Benjamin Kramer992a6372009-11-05 17:44:22 +0000810 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Chris Lattner18c7f802012-02-05 02:29:43 +0000811 StringRef LHSStr, RHSStr;
812 if (getConstantStringInfo(LHS, LHSStr) &&
813 getConstantStringInfo(RHS, RHSStr)) {
Benjamin Kramer992a6372009-11-05 17:44:22 +0000814 // Make sure we're not reading out-of-bounds memory.
Chris Lattner18c7f802012-02-05 02:29:43 +0000815 if (Len > LHSStr.size() || Len > RHSStr.size())
Benjamin Kramer992a6372009-11-05 17:44:22 +0000816 return 0;
817 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
818 return ConstantInt::get(CI->getType(), Ret);
819 }
820
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000821 return 0;
822 }
823};
824
825//===---------------------------------------===//
826// 'memcpy' Optimizations
827
Chris Lattner3e8b6632009-09-02 06:11:42 +0000828struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000829 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000830 // These optimizations require TargetData.
831 if (!TD) return 0;
832
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000833 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000834 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000835 !FT->getParamType(0)->isPointerTy() ||
836 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000837 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000838 return 0;
839
840 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000841 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
842 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000843 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000844 }
845};
846
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000847//===---------------------------------------===//
848// 'memmove' Optimizations
849
Chris Lattner3e8b6632009-09-02 06:11:42 +0000850struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000851 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000852 // These optimizations require TargetData.
853 if (!TD) return 0;
854
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000855 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000856 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000857 !FT->getParamType(0)->isPointerTy() ||
858 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000859 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000860 return 0;
861
862 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000863 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
864 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000865 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000866 }
867};
868
869//===---------------------------------------===//
870// 'memset' Optimizations
871
Chris Lattner3e8b6632009-09-02 06:11:42 +0000872struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000873 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000874 // These optimizations require TargetData.
875 if (!TD) return 0;
876
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000877 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000878 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000879 !FT->getParamType(0)->isPointerTy() ||
880 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000881 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000882 return 0;
883
884 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000885 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
886 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000887 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000888 }
889};
890
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000891//===----------------------------------------------------------------------===//
892// Math Library Optimizations
893//===----------------------------------------------------------------------===//
894
895//===---------------------------------------===//
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000896// 'cos*' Optimizations
897
898struct CosOpt : public LibCallOptimization {
899 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
900 FunctionType *FT = Callee->getFunctionType();
901 // Just make sure this has 1 argument of FP type, which matches the
902 // result type.
903 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
904 !FT->getParamType(0)->isFloatingPointTy())
905 return 0;
906
907 // cos(-x) -> cos(x)
908 Value *Op1 = CI->getArgOperand(0);
909 if (BinaryOperator::isFNeg(Op1)) {
910 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
911 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
912 }
913 return 0;
914 }
915};
916
917//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000918// 'pow*' Optimizations
919
Chris Lattner3e8b6632009-09-02 06:11:42 +0000920struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000921 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000922 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000923 // Just make sure this has 2 arguments of the same FP type, which match the
924 // result type.
925 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
926 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000927 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000928 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000929
Gabor Greifaee5dc12010-06-24 10:42:46 +0000930 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000931 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
932 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
933 return Op1C;
934 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000935 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000936 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000937
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000938 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
939 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000940
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000941 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000942 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000943
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000944 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000945 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
946 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000947 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +0000948 // TODO: In fast-math mode, this could be just sqrt(x).
949 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000950 Value *Inf = ConstantFP::getInfinity(CI->getType());
951 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000952 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
953 Callee->getAttributes());
954 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
955 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000956 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
957 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000958 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000959 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000960
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000961 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
962 return Op1;
963 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000964 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000965 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000966 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000967 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000968 return 0;
969 }
970};
971
972//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000973// 'exp2' Optimizations
974
Chris Lattner3e8b6632009-09-02 06:11:42 +0000975struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000976 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000977 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000978 // Just make sure this has 1 argument of FP type, which matches the
979 // result type.
980 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000981 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000982 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000983
Gabor Greifaee5dc12010-06-24 10:42:46 +0000984 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000985 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
986 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
987 Value *LdExpArg = 0;
988 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
989 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000990 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000991 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
992 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000993 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000994 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000995
Chris Lattnere818f772008-05-02 18:43:35 +0000996 if (LdExpArg) {
997 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000998 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000999 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001000 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001001 Name = "ldexp";
1002 else
1003 Name = "ldexpl";
1004
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001005 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001006 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001007 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001008
1009 Module *M = Caller->getParent();
1010 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +00001011 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001012 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001013 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1014 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1015 CI->setCallingConv(F->getCallingConv());
1016
1017 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001018 }
1019 return 0;
1020 }
1021};
Chris Lattnere818f772008-05-02 18:43:35 +00001022
1023//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001024// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1025
Chris Lattner3e8b6632009-09-02 06:11:42 +00001026struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001027 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001028 FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001029 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1030 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001031 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001032
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001033 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001034 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001035 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001036 return 0;
1037
1038 // floor((double)floatval) -> (double)floorf(floatval)
1039 Value *V = Cast->getOperand(0);
Benjamin Kramerb5ccb252011-11-15 19:12:09 +00001040 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001041 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001042 }
1043};
1044
1045//===----------------------------------------------------------------------===//
1046// Integer Optimizations
1047//===----------------------------------------------------------------------===//
1048
1049//===---------------------------------------===//
1050// 'ffs*' Optimizations
1051
Chris Lattner3e8b6632009-09-02 06:11:42 +00001052struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001053 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001054 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001055 // Just make sure this has 2 arguments of the same FP type, which match the
1056 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001057 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +00001058 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +00001059 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001060 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001061
Gabor Greifaee5dc12010-06-24 10:42:46 +00001062 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001063
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001064 // Constant fold.
1065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1066 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001067 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001068 // ffs(c) -> cttz(c)+1
1069 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001070 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001071
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001072 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001073 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001074 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001075 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001076 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001077 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1078 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001079
Benjamin Kramera9390a42011-09-27 20:39:19 +00001080 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001081 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001082 }
1083};
1084
1085//===---------------------------------------===//
1086// 'isdigit' Optimizations
1087
Chris Lattner3e8b6632009-09-02 06:11:42 +00001088struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001089 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001090 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001091 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001092 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001093 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001094 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001095
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001096 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001097 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001098 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1099 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001100 return B.CreateZExt(Op, CI->getType());
1101 }
1102};
1103
1104//===---------------------------------------===//
1105// 'isascii' Optimizations
1106
Chris Lattner3e8b6632009-09-02 06:11:42 +00001107struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001108 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001109 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001110 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001111 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001112 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001113 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001114
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001115 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001116 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001117 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001118 return B.CreateZExt(Op, CI->getType());
1119 }
1120};
Eric Christopher37c8b862009-10-07 21:14:25 +00001121
Chris Lattner313f0e62008-06-09 08:26:51 +00001122//===---------------------------------------===//
1123// 'abs', 'labs', 'llabs' Optimizations
1124
Chris Lattner3e8b6632009-09-02 06:11:42 +00001125struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001126 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001127 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001128 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001129 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001130 FT->getParamType(0) != FT->getReturnType())
1131 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001132
Chris Lattner313f0e62008-06-09 08:26:51 +00001133 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001134 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001135 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001136 "ispos");
1137 Value *Neg = B.CreateNeg(Op, "neg");
1138 return B.CreateSelect(Pos, Op, Neg);
1139 }
1140};
Eric Christopher37c8b862009-10-07 21:14:25 +00001141
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001142
1143//===---------------------------------------===//
1144// 'toascii' Optimizations
1145
Chris Lattner3e8b6632009-09-02 06:11:42 +00001146struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001147 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001148 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001149 // We require i32(i32)
1150 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001151 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001152 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001153
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001154 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001155 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001156 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001157 }
1158};
1159
1160//===----------------------------------------------------------------------===//
1161// Formatting and IO Optimizations
1162//===----------------------------------------------------------------------===//
1163
1164//===---------------------------------------===//
1165// 'printf' Optimizations
1166
Chris Lattner3e8b6632009-09-02 06:11:42 +00001167struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001168 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1169 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001170 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001171 StringRef FormatStr;
1172 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001173 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001174
1175 // Empty format string -> noop.
1176 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001177 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001178 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001179
Daniel Dunbard02be242011-02-12 18:19:57 +00001180 // Do not do any of the following transformations if the printf return value
1181 // is used, in general the printf return value is not compatible with either
1182 // putchar() or puts().
1183 if (!CI->use_empty())
1184 return 0;
1185
1186 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001187 if (FormatStr.size() == 1) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001188 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +00001189 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +00001190 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001191 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001192
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001193 // printf("foo\n") --> puts("foo")
1194 if (FormatStr[FormatStr.size()-1] == '\n' &&
1195 FormatStr.find('%') == std::string::npos) { // no format characters.
1196 // Create a string literal with no \n on it. We expect the constant merge
1197 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +00001198 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001199 Value *GV = B.CreateGlobalString(FormatStr, "str");
Nuno Lopes51004df2012-07-25 16:46:31 +00001200 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1201 return (CI->use_empty() || !NewCI) ?
1202 NewCI :
1203 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001204 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001205
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001206 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001207 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001208 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001209 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001210 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001211
Nuno Lopescd31fc72012-07-26 17:10:46 +00001212 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +00001213 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001214 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001215
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001216 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001217 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001218 CI->getArgOperand(1)->getType()->isPointerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001219 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001220 }
1221 return 0;
1222 }
Richard Osborne36498242011-03-03 13:17:51 +00001223
1224 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1225 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001226 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001227 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1228 !(FT->getReturnType()->isIntegerTy() ||
1229 FT->getReturnType()->isVoidTy()))
1230 return 0;
1231
1232 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1233 return V;
1234 }
1235
1236 // printf(format, ...) -> iprintf(format, ...) if no floating point
1237 // arguments.
1238 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1239 Module *M = B.GetInsertBlock()->getParent()->getParent();
1240 Constant *IPrintFFn =
1241 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1242 CallInst *New = cast<CallInst>(CI->clone());
1243 New->setCalledFunction(IPrintFFn);
1244 B.Insert(New);
1245 return New;
1246 }
1247 return 0;
1248 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001249};
1250
1251//===---------------------------------------===//
1252// 'sprintf' Optimizations
1253
Chris Lattner3e8b6632009-09-02 06:11:42 +00001254struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001255 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1256 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001257 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001258 StringRef FormatStr;
1259 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001260 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001261
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001262 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001263 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001264 // Make sure there's no % in the constant array. We could try to handle
1265 // %% -> % in the future if we cared.
1266 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1267 if (FormatStr[i] == '%')
1268 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001269
1270 // These optimizations require TargetData.
1271 if (!TD) return 0;
1272
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001273 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001274 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1275 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1276 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001277 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001278 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001279
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001280 // The remaining optimizations require the format string to be "%s" or "%c"
1281 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001282 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1283 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001284 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001285
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286 // Decode the second character of the format string.
1287 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001288 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001289 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001290 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001291 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001292 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001293 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1294 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001295
Owen Andersoneed707b2009-07-24 23:12:02 +00001296 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001297 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001298
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001299 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001300 // These optimizations require TargetData.
1301 if (!TD) return 0;
1302
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001303 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001304 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001305
Nuno Lopes51004df2012-07-25 16:46:31 +00001306 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1307 if (!Len)
1308 return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001309 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001310 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001311 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001312 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001313
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001314 // The sprintf result is the unincremented number of bytes in the string.
1315 return B.CreateIntCast(Len, CI->getType(), false);
1316 }
1317 return 0;
1318 }
Richard Osborne419454a2011-03-03 14:09:28 +00001319
1320 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1321 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001322 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001323 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1324 !FT->getParamType(1)->isPointerTy() ||
1325 !FT->getReturnType()->isIntegerTy())
1326 return 0;
1327
1328 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1329 return V;
1330 }
1331
Richard Osborneea2578c2011-03-03 14:21:22 +00001332 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001333 // point arguments.
1334 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1335 Module *M = B.GetInsertBlock()->getParent()->getParent();
1336 Constant *SIPrintFFn =
1337 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1338 CallInst *New = cast<CallInst>(CI->clone());
1339 New->setCalledFunction(SIPrintFFn);
1340 B.Insert(New);
1341 return New;
1342 }
1343 return 0;
1344 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001345};
1346
1347//===---------------------------------------===//
1348// 'fwrite' Optimizations
1349
Chris Lattner3e8b6632009-09-02 06:11:42 +00001350struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001351 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001352 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001353 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001354 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1355 !FT->getParamType(1)->isIntegerTy() ||
1356 !FT->getParamType(2)->isIntegerTy() ||
1357 !FT->getParamType(3)->isPointerTy() ||
1358 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001359 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001360
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001361 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001362 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1363 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001364 if (!SizeC || !CountC) return 0;
1365 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001366
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001367 // If this is writing zero records, remove the call (it's a noop).
1368 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001369 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001370
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001371 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001372 // This optimisation is only valid, if the return value is unused.
1373 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001374 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Nuno Lopes51004df2012-07-25 16:46:31 +00001375 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1376 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001377 }
1378
1379 return 0;
1380 }
1381};
1382
1383//===---------------------------------------===//
1384// 'fputs' Optimizations
1385
Chris Lattner3e8b6632009-09-02 06:11:42 +00001386struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001387 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001388 // These optimizations require TargetData.
1389 if (!TD) return 0;
1390
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001391 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001392 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001393 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1394 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001395 !CI->use_empty())
1396 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001397
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001398 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001399 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001400 if (!Len) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001401 // Known to have no uses (see above).
1402 return EmitFWrite(CI->getArgOperand(0),
1403 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1404 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001405 }
1406};
1407
1408//===---------------------------------------===//
1409// 'fprintf' Optimizations
1410
Chris Lattner3e8b6632009-09-02 06:11:42 +00001411struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001412 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1413 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001414 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001415 StringRef FormatStr;
1416 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001417 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001418
1419 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001420 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001421 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1422 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001423 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001424
1425 // These optimizations require TargetData.
1426 if (!TD) return 0;
1427
Nuno Lopes51004df2012-07-25 16:46:31 +00001428 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1429 ConstantInt::get(TD->getIntPtrType(*Context),
1430 FormatStr.size()),
1431 CI->getArgOperand(0), B, TD, TLI);
1432 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001433 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001434
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001435 // The remaining optimizations require the format string to be "%s" or "%c"
1436 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001437 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1438 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001439 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001440
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001441 // Decode the second character of the format string.
1442 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001443 // fprintf(F, "%c", chr) --> fputc(chr, F)
1444 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001445 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1446 TD, TLI);
1447 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001448 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001449
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001450 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001451 // fprintf(F, "%s", str) --> fputs(str, F)
1452 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001453 return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001454 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001455 }
1456 return 0;
1457 }
Richard Osborne022708f2011-03-03 14:20:22 +00001458
1459 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1460 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001461 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001462 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1463 !FT->getParamType(1)->isPointerTy() ||
1464 !FT->getReturnType()->isIntegerTy())
1465 return 0;
1466
1467 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1468 return V;
1469 }
1470
1471 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1472 // floating point arguments.
1473 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1474 Module *M = B.GetInsertBlock()->getParent()->getParent();
1475 Constant *FIPrintFFn =
1476 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1477 CallInst *New = cast<CallInst>(CI->clone());
1478 New->setCalledFunction(FIPrintFFn);
1479 B.Insert(New);
1480 return New;
1481 }
1482 return 0;
1483 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001484};
1485
Anders Carlsson303023d2010-11-30 06:19:18 +00001486//===---------------------------------------===//
1487// 'puts' Optimizations
1488
1489struct PutsOpt : public LibCallOptimization {
1490 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1491 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001492 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001493 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1494 !(FT->getReturnType()->isIntegerTy() ||
1495 FT->getReturnType()->isVoidTy()))
1496 return 0;
1497
1498 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001499 StringRef Str;
1500 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +00001501 return 0;
1502
Daniel Dunbard02be242011-02-12 18:19:57 +00001503 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001504 // puts("") -> putchar('\n')
Nuno Lopes51004df2012-07-25 16:46:31 +00001505 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +00001506 if (CI->use_empty() || !Res) return Res;
Anders Carlsson303023d2010-11-30 06:19:18 +00001507 return B.CreateIntCast(Res, CI->getType(), true);
1508 }
1509
1510 return 0;
1511 }
1512};
1513
Bill Wendlingac178222008-05-05 21:37:59 +00001514} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001515
1516//===----------------------------------------------------------------------===//
1517// SimplifyLibCalls Pass Implementation
1518//===----------------------------------------------------------------------===//
1519
1520namespace {
1521 /// This pass optimizes well known library functions from libc and libm.
1522 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001523 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001524 TargetLibraryInfo *TLI;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001525
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001526 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001527 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001528 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
David Majnemerac782662012-05-15 11:46:21 +00001529 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1530 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1531 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1532 StrNCpyOpt StrNCpy;
1533 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001534 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001535 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001536 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001537 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001538 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001539 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1540 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001541 // Formatting and IO Optimizations
1542 SPrintFOpt SPrintF; PrintFOpt PrintF;
1543 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001544 PutsOpt Puts;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001545
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001546 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001547 public:
1548 static char ID; // Pass identification
David Majnemerac782662012-05-15 11:46:21 +00001549 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1550 StpCpy(false), StpCpyChk(true) {
Owen Anderson081c34b2010-10-19 17:21:58 +00001551 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1552 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001553 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chad Rosierd7e25252012-08-22 16:52:57 +00001554 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1555
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001556 void InitOptimizations();
1557 bool runOnFunction(Function &F);
1558
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001559 void setDoesNotAccessMemory(Function &F);
1560 void setOnlyReadsMemory(Function &F);
1561 void setDoesNotThrow(Function &F);
1562 void setDoesNotCapture(Function &F, unsigned n);
1563 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001564 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001565
Chris Lattnere265ad82011-02-24 07:12:12 +00001566 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001567 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001568 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001569 }
1570 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001571} // end anonymous namespace.
1572
Chris Lattnerafbf4832011-02-24 07:16:14 +00001573char SimplifyLibCalls::ID = 0;
1574
1575INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1576 "Simplify well-known library calls", false, false)
1577INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1578INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1579 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001580
1581// Public interface to the Simplify LibCalls pass.
1582FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001583 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584}
1585
Eli Friedman9d434db2011-11-17 01:27:36 +00001586void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1587 if (TLI->has(F))
1588 Optimizations[TLI->getName(F)] = Opt;
1589}
1590
Chad Rosierd7e25252012-08-22 16:52:57 +00001591void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1592 LibCallOptimization* Opt) {
1593 if (TLI->has(F1) && TLI->has(F2))
1594 Optimizations[TLI->getName(F1)] = Opt;
1595}
1596
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001597/// Optimizations - Populate the Optimizations map with all the optimizations
1598/// we know.
1599void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001600 // String and Memory LibCall Optimizations
1601 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001602 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001603 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001604 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001605 Optimizations["strcmp"] = &StrCmp;
1606 Optimizations["strncmp"] = &StrNCmp;
1607 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001608 Optimizations["strncpy"] = &StrNCpy;
David Majnemerac782662012-05-15 11:46:21 +00001609 Optimizations["stpcpy"] = &StpCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001610 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001611 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001612 Optimizations["strtol"] = &StrTo;
1613 Optimizations["strtod"] = &StrTo;
1614 Optimizations["strtof"] = &StrTo;
1615 Optimizations["strtoul"] = &StrTo;
1616 Optimizations["strtoll"] = &StrTo;
1617 Optimizations["strtold"] = &StrTo;
1618 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001619 Optimizations["strspn"] = &StrSpn;
1620 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001621 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001622 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001623 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001624 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001625 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001626
Evan Cheng0289b412010-03-23 15:48:04 +00001627 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001628 Optimizations["__strcpy_chk"] = &StrCpyChk;
David Majnemerac782662012-05-15 11:46:21 +00001629 Optimizations["__stpcpy_chk"] = &StpCpyChk;
Evan Cheng0289b412010-03-23 15:48:04 +00001630
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001631 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001632 Optimizations["cosf"] = &Cos;
1633 Optimizations["cos"] = &Cos;
1634 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001635 Optimizations["powf"] = &Pow;
1636 Optimizations["pow"] = &Pow;
1637 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001638 Optimizations["llvm.pow.f32"] = &Pow;
1639 Optimizations["llvm.pow.f64"] = &Pow;
1640 Optimizations["llvm.pow.f80"] = &Pow;
1641 Optimizations["llvm.pow.f128"] = &Pow;
1642 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001643 Optimizations["exp2l"] = &Exp2;
1644 Optimizations["exp2"] = &Exp2;
1645 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001646 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1647 Optimizations["llvm.exp2.f128"] = &Exp2;
1648 Optimizations["llvm.exp2.f80"] = &Exp2;
1649 Optimizations["llvm.exp2.f64"] = &Exp2;
1650 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001651
Chad Rosierd7e25252012-08-22 16:52:57 +00001652 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1653 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
1654 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1655 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1656 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1657 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1658 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
Eric Christopher37c8b862009-10-07 21:14:25 +00001659
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001660 // Integer Optimizations
1661 Optimizations["ffs"] = &FFS;
1662 Optimizations["ffsl"] = &FFS;
1663 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001664 Optimizations["abs"] = &Abs;
1665 Optimizations["labs"] = &Abs;
1666 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001667 Optimizations["isdigit"] = &IsDigit;
1668 Optimizations["isascii"] = &IsAscii;
1669 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001670
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001671 // Formatting and IO Optimizations
1672 Optimizations["sprintf"] = &SPrintF;
1673 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001674 AddOpt(LibFunc::fwrite, &FWrite);
1675 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001676 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001677 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001678}
1679
1680
1681/// runOnFunction - Top level algorithm.
1682///
1683bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001684 TLI = &getAnalysis<TargetLibraryInfo>();
1685
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001686 if (Optimizations.empty())
1687 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001688
Dan Gohmanf14d9192009-08-18 00:48:13 +00001689 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001690
Owen Andersone922c022009-07-22 00:24:57 +00001691 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001692
1693 bool Changed = false;
1694 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1695 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1696 // Ignore non-calls.
1697 CallInst *CI = dyn_cast<CallInst>(I++);
1698 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001699
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001700 // Ignore indirect calls and calls to non-external functions.
1701 Function *Callee = CI->getCalledFunction();
1702 if (Callee == 0 || !Callee->isDeclaration() ||
1703 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1704 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001705
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001706 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001707 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1708 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001709
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001710 // Set the builder to the instruction after the call.
1711 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001712
Devang Patela2ab3992011-03-09 21:27:52 +00001713 // Use debug location of CI for all new instructions.
1714 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1715
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001716 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001717 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001718 if (Result == 0) continue;
1719
David Greene6a6b90e2010-01-05 01:27:21 +00001720 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1721 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001722
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001723 // Something changed!
1724 Changed = true;
1725 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001726
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001727 // Inspect the instruction after the call (which was potentially just
1728 // added) next.
1729 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001730
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001731 if (CI != Result && !CI->use_empty()) {
1732 CI->replaceAllUsesWith(Result);
1733 if (!Result->hasName())
1734 Result->takeName(CI);
1735 }
1736 CI->eraseFromParent();
1737 }
1738 }
1739 return Changed;
1740}
1741
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001742// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001743
1744void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1745 if (!F.doesNotAccessMemory()) {
1746 F.setDoesNotAccessMemory();
1747 ++NumAnnotated;
1748 Modified = true;
1749 }
1750}
1751void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1752 if (!F.onlyReadsMemory()) {
1753 F.setOnlyReadsMemory();
1754 ++NumAnnotated;
1755 Modified = true;
1756 }
1757}
1758void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1759 if (!F.doesNotThrow()) {
1760 F.setDoesNotThrow();
1761 ++NumAnnotated;
1762 Modified = true;
1763 }
1764}
1765void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1766 if (!F.doesNotCapture(n)) {
1767 F.setDoesNotCapture(n);
1768 ++NumAnnotated;
1769 Modified = true;
1770 }
1771}
1772void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1773 if (!F.doesNotAlias(n)) {
1774 F.setDoesNotAlias(n);
1775 ++NumAnnotated;
1776 Modified = true;
1777 }
1778}
1779
Chris Lattnere265ad82011-02-24 07:12:12 +00001780
1781void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001782 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001783
Chris Lattnere265ad82011-02-24 07:12:12 +00001784 StringRef Name = F.getName();
1785 switch (Name[0]) {
1786 case 's':
1787 if (Name == "strlen") {
1788 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1789 return;
1790 setOnlyReadsMemory(F);
1791 setDoesNotThrow(F);
1792 setDoesNotCapture(F, 1);
1793 } else if (Name == "strchr" ||
1794 Name == "strrchr") {
1795 if (FTy->getNumParams() != 2 ||
1796 !FTy->getParamType(0)->isPointerTy() ||
1797 !FTy->getParamType(1)->isIntegerTy())
1798 return;
1799 setOnlyReadsMemory(F);
1800 setDoesNotThrow(F);
1801 } else if (Name == "strcpy" ||
1802 Name == "stpcpy" ||
1803 Name == "strcat" ||
1804 Name == "strtol" ||
1805 Name == "strtod" ||
1806 Name == "strtof" ||
1807 Name == "strtoul" ||
1808 Name == "strtoll" ||
1809 Name == "strtold" ||
1810 Name == "strncat" ||
1811 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001812 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001813 Name == "strtoull") {
1814 if (FTy->getNumParams() < 2 ||
1815 !FTy->getParamType(1)->isPointerTy())
1816 return;
1817 setDoesNotThrow(F);
1818 setDoesNotCapture(F, 2);
1819 } else if (Name == "strxfrm") {
1820 if (FTy->getNumParams() != 3 ||
1821 !FTy->getParamType(0)->isPointerTy() ||
1822 !FTy->getParamType(1)->isPointerTy())
1823 return;
1824 setDoesNotThrow(F);
1825 setDoesNotCapture(F, 1);
1826 setDoesNotCapture(F, 2);
1827 } else if (Name == "strcmp" ||
1828 Name == "strspn" ||
1829 Name == "strncmp" ||
1830 Name == "strcspn" ||
1831 Name == "strcoll" ||
1832 Name == "strcasecmp" ||
1833 Name == "strncasecmp") {
1834 if (FTy->getNumParams() < 2 ||
1835 !FTy->getParamType(0)->isPointerTy() ||
1836 !FTy->getParamType(1)->isPointerTy())
1837 return;
1838 setOnlyReadsMemory(F);
1839 setDoesNotThrow(F);
1840 setDoesNotCapture(F, 1);
1841 setDoesNotCapture(F, 2);
1842 } else if (Name == "strstr" ||
1843 Name == "strpbrk") {
1844 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1845 return;
1846 setOnlyReadsMemory(F);
1847 setDoesNotThrow(F);
1848 setDoesNotCapture(F, 2);
1849 } else if (Name == "strtok" ||
1850 Name == "strtok_r") {
1851 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1852 return;
1853 setDoesNotThrow(F);
1854 setDoesNotCapture(F, 2);
1855 } else if (Name == "scanf" ||
1856 Name == "setbuf" ||
1857 Name == "setvbuf") {
1858 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1859 return;
1860 setDoesNotThrow(F);
1861 setDoesNotCapture(F, 1);
1862 } else if (Name == "strdup" ||
1863 Name == "strndup") {
1864 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1865 !FTy->getParamType(0)->isPointerTy())
1866 return;
1867 setDoesNotThrow(F);
1868 setDoesNotAlias(F, 0);
1869 setDoesNotCapture(F, 1);
1870 } else if (Name == "stat" ||
1871 Name == "sscanf" ||
1872 Name == "sprintf" ||
1873 Name == "statvfs") {
1874 if (FTy->getNumParams() < 2 ||
1875 !FTy->getParamType(0)->isPointerTy() ||
1876 !FTy->getParamType(1)->isPointerTy())
1877 return;
1878 setDoesNotThrow(F);
1879 setDoesNotCapture(F, 1);
1880 setDoesNotCapture(F, 2);
1881 } else if (Name == "snprintf") {
1882 if (FTy->getNumParams() != 3 ||
1883 !FTy->getParamType(0)->isPointerTy() ||
1884 !FTy->getParamType(2)->isPointerTy())
1885 return;
1886 setDoesNotThrow(F);
1887 setDoesNotCapture(F, 1);
1888 setDoesNotCapture(F, 3);
1889 } else if (Name == "setitimer") {
1890 if (FTy->getNumParams() != 3 ||
1891 !FTy->getParamType(1)->isPointerTy() ||
1892 !FTy->getParamType(2)->isPointerTy())
1893 return;
1894 setDoesNotThrow(F);
1895 setDoesNotCapture(F, 2);
1896 setDoesNotCapture(F, 3);
1897 } else if (Name == "system") {
1898 if (FTy->getNumParams() != 1 ||
1899 !FTy->getParamType(0)->isPointerTy())
1900 return;
1901 // May throw; "system" is a valid pthread cancellation point.
1902 setDoesNotCapture(F, 1);
1903 }
1904 break;
1905 case 'm':
1906 if (Name == "malloc") {
1907 if (FTy->getNumParams() != 1 ||
1908 !FTy->getReturnType()->isPointerTy())
1909 return;
1910 setDoesNotThrow(F);
1911 setDoesNotAlias(F, 0);
1912 } else if (Name == "memcmp") {
1913 if (FTy->getNumParams() != 3 ||
1914 !FTy->getParamType(0)->isPointerTy() ||
1915 !FTy->getParamType(1)->isPointerTy())
1916 return;
1917 setOnlyReadsMemory(F);
1918 setDoesNotThrow(F);
1919 setDoesNotCapture(F, 1);
1920 setDoesNotCapture(F, 2);
1921 } else if (Name == "memchr" ||
1922 Name == "memrchr") {
1923 if (FTy->getNumParams() != 3)
1924 return;
1925 setOnlyReadsMemory(F);
1926 setDoesNotThrow(F);
1927 } else if (Name == "modf" ||
1928 Name == "modff" ||
1929 Name == "modfl" ||
1930 Name == "memcpy" ||
1931 Name == "memccpy" ||
1932 Name == "memmove") {
1933 if (FTy->getNumParams() < 2 ||
1934 !FTy->getParamType(1)->isPointerTy())
1935 return;
1936 setDoesNotThrow(F);
1937 setDoesNotCapture(F, 2);
1938 } else if (Name == "memalign") {
1939 if (!FTy->getReturnType()->isPointerTy())
1940 return;
1941 setDoesNotAlias(F, 0);
1942 } else if (Name == "mkdir" ||
1943 Name == "mktime") {
1944 if (FTy->getNumParams() == 0 ||
1945 !FTy->getParamType(0)->isPointerTy())
1946 return;
1947 setDoesNotThrow(F);
1948 setDoesNotCapture(F, 1);
1949 }
1950 break;
1951 case 'r':
1952 if (Name == "realloc") {
1953 if (FTy->getNumParams() != 2 ||
1954 !FTy->getParamType(0)->isPointerTy() ||
1955 !FTy->getReturnType()->isPointerTy())
1956 return;
1957 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +00001958 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +00001959 setDoesNotCapture(F, 1);
1960 } else if (Name == "read") {
1961 if (FTy->getNumParams() != 3 ||
1962 !FTy->getParamType(1)->isPointerTy())
1963 return;
1964 // May throw; "read" is a valid pthread cancellation point.
1965 setDoesNotCapture(F, 2);
1966 } else if (Name == "rmdir" ||
1967 Name == "rewind" ||
1968 Name == "remove" ||
1969 Name == "realpath") {
1970 if (FTy->getNumParams() < 1 ||
1971 !FTy->getParamType(0)->isPointerTy())
1972 return;
1973 setDoesNotThrow(F);
1974 setDoesNotCapture(F, 1);
1975 } else if (Name == "rename" ||
1976 Name == "readlink") {
1977 if (FTy->getNumParams() < 2 ||
1978 !FTy->getParamType(0)->isPointerTy() ||
1979 !FTy->getParamType(1)->isPointerTy())
1980 return;
1981 setDoesNotThrow(F);
1982 setDoesNotCapture(F, 1);
1983 setDoesNotCapture(F, 2);
1984 }
1985 break;
1986 case 'w':
1987 if (Name == "write") {
1988 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1989 return;
1990 // May throw; "write" is a valid pthread cancellation point.
1991 setDoesNotCapture(F, 2);
1992 }
1993 break;
1994 case 'b':
1995 if (Name == "bcopy") {
1996 if (FTy->getNumParams() != 3 ||
1997 !FTy->getParamType(0)->isPointerTy() ||
1998 !FTy->getParamType(1)->isPointerTy())
1999 return;
2000 setDoesNotThrow(F);
2001 setDoesNotCapture(F, 1);
2002 setDoesNotCapture(F, 2);
2003 } else if (Name == "bcmp") {
2004 if (FTy->getNumParams() != 3 ||
2005 !FTy->getParamType(0)->isPointerTy() ||
2006 !FTy->getParamType(1)->isPointerTy())
2007 return;
2008 setDoesNotThrow(F);
2009 setOnlyReadsMemory(F);
2010 setDoesNotCapture(F, 1);
2011 setDoesNotCapture(F, 2);
2012 } else if (Name == "bzero") {
2013 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2014 return;
2015 setDoesNotThrow(F);
2016 setDoesNotCapture(F, 1);
2017 }
2018 break;
2019 case 'c':
2020 if (Name == "calloc") {
2021 if (FTy->getNumParams() != 2 ||
2022 !FTy->getReturnType()->isPointerTy())
2023 return;
2024 setDoesNotThrow(F);
2025 setDoesNotAlias(F, 0);
2026 } else if (Name == "chmod" ||
2027 Name == "chown" ||
2028 Name == "ctermid" ||
2029 Name == "clearerr" ||
2030 Name == "closedir") {
2031 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2032 return;
2033 setDoesNotThrow(F);
2034 setDoesNotCapture(F, 1);
2035 }
2036 break;
2037 case 'a':
2038 if (Name == "atoi" ||
2039 Name == "atol" ||
2040 Name == "atof" ||
2041 Name == "atoll") {
2042 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2043 return;
2044 setDoesNotThrow(F);
2045 setOnlyReadsMemory(F);
2046 setDoesNotCapture(F, 1);
2047 } else if (Name == "access") {
2048 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2049 return;
2050 setDoesNotThrow(F);
2051 setDoesNotCapture(F, 1);
2052 }
2053 break;
2054 case 'f':
2055 if (Name == "fopen") {
2056 if (FTy->getNumParams() != 2 ||
2057 !FTy->getReturnType()->isPointerTy() ||
2058 !FTy->getParamType(0)->isPointerTy() ||
2059 !FTy->getParamType(1)->isPointerTy())
2060 return;
2061 setDoesNotThrow(F);
2062 setDoesNotAlias(F, 0);
2063 setDoesNotCapture(F, 1);
2064 setDoesNotCapture(F, 2);
2065 } else if (Name == "fdopen") {
2066 if (FTy->getNumParams() != 2 ||
2067 !FTy->getReturnType()->isPointerTy() ||
2068 !FTy->getParamType(1)->isPointerTy())
2069 return;
2070 setDoesNotThrow(F);
2071 setDoesNotAlias(F, 0);
2072 setDoesNotCapture(F, 2);
2073 } else if (Name == "feof" ||
2074 Name == "free" ||
2075 Name == "fseek" ||
2076 Name == "ftell" ||
2077 Name == "fgetc" ||
2078 Name == "fseeko" ||
2079 Name == "ftello" ||
2080 Name == "fileno" ||
2081 Name == "fflush" ||
2082 Name == "fclose" ||
2083 Name == "fsetpos" ||
2084 Name == "flockfile" ||
2085 Name == "funlockfile" ||
2086 Name == "ftrylockfile") {
2087 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2088 return;
2089 setDoesNotThrow(F);
2090 setDoesNotCapture(F, 1);
2091 } else if (Name == "ferror") {
2092 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2093 return;
2094 setDoesNotThrow(F);
2095 setDoesNotCapture(F, 1);
2096 setOnlyReadsMemory(F);
2097 } else if (Name == "fputc" ||
2098 Name == "fstat" ||
2099 Name == "frexp" ||
2100 Name == "frexpf" ||
2101 Name == "frexpl" ||
2102 Name == "fstatvfs") {
2103 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2104 return;
2105 setDoesNotThrow(F);
2106 setDoesNotCapture(F, 2);
2107 } else if (Name == "fgets") {
2108 if (FTy->getNumParams() != 3 ||
2109 !FTy->getParamType(0)->isPointerTy() ||
2110 !FTy->getParamType(2)->isPointerTy())
2111 return;
2112 setDoesNotThrow(F);
2113 setDoesNotCapture(F, 3);
2114 } else if (Name == "fread" ||
2115 Name == "fwrite") {
2116 if (FTy->getNumParams() != 4 ||
2117 !FTy->getParamType(0)->isPointerTy() ||
2118 !FTy->getParamType(3)->isPointerTy())
2119 return;
2120 setDoesNotThrow(F);
2121 setDoesNotCapture(F, 1);
2122 setDoesNotCapture(F, 4);
2123 } else if (Name == "fputs" ||
2124 Name == "fscanf" ||
2125 Name == "fprintf" ||
2126 Name == "fgetpos") {
2127 if (FTy->getNumParams() < 2 ||
2128 !FTy->getParamType(0)->isPointerTy() ||
2129 !FTy->getParamType(1)->isPointerTy())
2130 return;
2131 setDoesNotThrow(F);
2132 setDoesNotCapture(F, 1);
2133 setDoesNotCapture(F, 2);
2134 }
2135 break;
2136 case 'g':
2137 if (Name == "getc" ||
2138 Name == "getlogin_r" ||
2139 Name == "getc_unlocked") {
2140 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2141 return;
2142 setDoesNotThrow(F);
2143 setDoesNotCapture(F, 1);
2144 } else if (Name == "getenv") {
2145 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2146 return;
2147 setDoesNotThrow(F);
2148 setOnlyReadsMemory(F);
2149 setDoesNotCapture(F, 1);
2150 } else if (Name == "gets" ||
2151 Name == "getchar") {
2152 setDoesNotThrow(F);
2153 } else if (Name == "getitimer") {
2154 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2155 return;
2156 setDoesNotThrow(F);
2157 setDoesNotCapture(F, 2);
2158 } else if (Name == "getpwnam") {
2159 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2160 return;
2161 setDoesNotThrow(F);
2162 setDoesNotCapture(F, 1);
2163 }
2164 break;
2165 case 'u':
2166 if (Name == "ungetc") {
2167 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2168 return;
2169 setDoesNotThrow(F);
2170 setDoesNotCapture(F, 2);
2171 } else if (Name == "uname" ||
2172 Name == "unlink" ||
2173 Name == "unsetenv") {
2174 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2175 return;
2176 setDoesNotThrow(F);
2177 setDoesNotCapture(F, 1);
2178 } else if (Name == "utime" ||
2179 Name == "utimes") {
2180 if (FTy->getNumParams() != 2 ||
2181 !FTy->getParamType(0)->isPointerTy() ||
2182 !FTy->getParamType(1)->isPointerTy())
2183 return;
2184 setDoesNotThrow(F);
2185 setDoesNotCapture(F, 1);
2186 setDoesNotCapture(F, 2);
2187 }
2188 break;
2189 case 'p':
2190 if (Name == "putc") {
2191 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2192 return;
2193 setDoesNotThrow(F);
2194 setDoesNotCapture(F, 2);
2195 } else if (Name == "puts" ||
2196 Name == "printf" ||
2197 Name == "perror") {
2198 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2199 return;
2200 setDoesNotThrow(F);
2201 setDoesNotCapture(F, 1);
2202 } else if (Name == "pread" ||
2203 Name == "pwrite") {
2204 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2205 return;
2206 // May throw; these are valid pthread cancellation points.
2207 setDoesNotCapture(F, 2);
2208 } else if (Name == "putchar") {
2209 setDoesNotThrow(F);
2210 } else if (Name == "popen") {
2211 if (FTy->getNumParams() != 2 ||
2212 !FTy->getReturnType()->isPointerTy() ||
2213 !FTy->getParamType(0)->isPointerTy() ||
2214 !FTy->getParamType(1)->isPointerTy())
2215 return;
2216 setDoesNotThrow(F);
2217 setDoesNotAlias(F, 0);
2218 setDoesNotCapture(F, 1);
2219 setDoesNotCapture(F, 2);
2220 } else if (Name == "pclose") {
2221 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2222 return;
2223 setDoesNotThrow(F);
2224 setDoesNotCapture(F, 1);
2225 }
2226 break;
2227 case 'v':
2228 if (Name == "vscanf") {
2229 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2230 return;
2231 setDoesNotThrow(F);
2232 setDoesNotCapture(F, 1);
2233 } else if (Name == "vsscanf" ||
2234 Name == "vfscanf") {
2235 if (FTy->getNumParams() != 3 ||
2236 !FTy->getParamType(1)->isPointerTy() ||
2237 !FTy->getParamType(2)->isPointerTy())
2238 return;
2239 setDoesNotThrow(F);
2240 setDoesNotCapture(F, 1);
2241 setDoesNotCapture(F, 2);
2242 } else if (Name == "valloc") {
2243 if (!FTy->getReturnType()->isPointerTy())
2244 return;
2245 setDoesNotThrow(F);
2246 setDoesNotAlias(F, 0);
2247 } else if (Name == "vprintf") {
2248 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2249 return;
2250 setDoesNotThrow(F);
2251 setDoesNotCapture(F, 1);
2252 } else if (Name == "vfprintf" ||
2253 Name == "vsprintf") {
2254 if (FTy->getNumParams() != 3 ||
2255 !FTy->getParamType(0)->isPointerTy() ||
2256 !FTy->getParamType(1)->isPointerTy())
2257 return;
2258 setDoesNotThrow(F);
2259 setDoesNotCapture(F, 1);
2260 setDoesNotCapture(F, 2);
2261 } else if (Name == "vsnprintf") {
2262 if (FTy->getNumParams() != 4 ||
2263 !FTy->getParamType(0)->isPointerTy() ||
2264 !FTy->getParamType(2)->isPointerTy())
2265 return;
2266 setDoesNotThrow(F);
2267 setDoesNotCapture(F, 1);
2268 setDoesNotCapture(F, 3);
2269 }
2270 break;
2271 case 'o':
2272 if (Name == "open") {
2273 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2274 return;
2275 // May throw; "open" is a valid pthread cancellation point.
2276 setDoesNotCapture(F, 1);
2277 } else if (Name == "opendir") {
2278 if (FTy->getNumParams() != 1 ||
2279 !FTy->getReturnType()->isPointerTy() ||
2280 !FTy->getParamType(0)->isPointerTy())
2281 return;
2282 setDoesNotThrow(F);
2283 setDoesNotAlias(F, 0);
2284 setDoesNotCapture(F, 1);
2285 }
2286 break;
2287 case 't':
2288 if (Name == "tmpfile") {
2289 if (!FTy->getReturnType()->isPointerTy())
2290 return;
2291 setDoesNotThrow(F);
2292 setDoesNotAlias(F, 0);
2293 } else if (Name == "times") {
2294 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2295 return;
2296 setDoesNotThrow(F);
2297 setDoesNotCapture(F, 1);
2298 }
2299 break;
2300 case 'h':
2301 if (Name == "htonl" ||
2302 Name == "htons") {
2303 setDoesNotThrow(F);
2304 setDoesNotAccessMemory(F);
2305 }
2306 break;
2307 case 'n':
2308 if (Name == "ntohl" ||
2309 Name == "ntohs") {
2310 setDoesNotThrow(F);
2311 setDoesNotAccessMemory(F);
2312 }
2313 break;
2314 case 'l':
2315 if (Name == "lstat") {
2316 if (FTy->getNumParams() != 2 ||
2317 !FTy->getParamType(0)->isPointerTy() ||
2318 !FTy->getParamType(1)->isPointerTy())
2319 return;
2320 setDoesNotThrow(F);
2321 setDoesNotCapture(F, 1);
2322 setDoesNotCapture(F, 2);
2323 } else if (Name == "lchown") {
2324 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2325 return;
2326 setDoesNotThrow(F);
2327 setDoesNotCapture(F, 1);
2328 }
2329 break;
2330 case 'q':
2331 if (Name == "qsort") {
2332 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2333 return;
2334 // May throw; places call through function pointer.
2335 setDoesNotCapture(F, 4);
2336 }
2337 break;
2338 case '_':
2339 if (Name == "__strdup" ||
2340 Name == "__strndup") {
2341 if (FTy->getNumParams() < 1 ||
2342 !FTy->getReturnType()->isPointerTy() ||
2343 !FTy->getParamType(0)->isPointerTy())
2344 return;
2345 setDoesNotThrow(F);
2346 setDoesNotAlias(F, 0);
2347 setDoesNotCapture(F, 1);
2348 } else if (Name == "__strtok_r") {
2349 if (FTy->getNumParams() != 3 ||
2350 !FTy->getParamType(1)->isPointerTy())
2351 return;
2352 setDoesNotThrow(F);
2353 setDoesNotCapture(F, 2);
2354 } else if (Name == "_IO_getc") {
2355 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2356 return;
2357 setDoesNotThrow(F);
2358 setDoesNotCapture(F, 1);
2359 } else if (Name == "_IO_putc") {
2360 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2361 return;
2362 setDoesNotThrow(F);
2363 setDoesNotCapture(F, 2);
2364 }
2365 break;
2366 case 1:
2367 if (Name == "\1__isoc99_scanf") {
2368 if (FTy->getNumParams() < 1 ||
2369 !FTy->getParamType(0)->isPointerTy())
2370 return;
2371 setDoesNotThrow(F);
2372 setDoesNotCapture(F, 1);
2373 } else if (Name == "\1stat64" ||
2374 Name == "\1lstat64" ||
2375 Name == "\1statvfs64" ||
2376 Name == "\1__isoc99_sscanf") {
2377 if (FTy->getNumParams() < 1 ||
2378 !FTy->getParamType(0)->isPointerTy() ||
2379 !FTy->getParamType(1)->isPointerTy())
2380 return;
2381 setDoesNotThrow(F);
2382 setDoesNotCapture(F, 1);
2383 setDoesNotCapture(F, 2);
2384 } else if (Name == "\1fopen64") {
2385 if (FTy->getNumParams() != 2 ||
2386 !FTy->getReturnType()->isPointerTy() ||
2387 !FTy->getParamType(0)->isPointerTy() ||
2388 !FTy->getParamType(1)->isPointerTy())
2389 return;
2390 setDoesNotThrow(F);
2391 setDoesNotAlias(F, 0);
2392 setDoesNotCapture(F, 1);
2393 setDoesNotCapture(F, 2);
2394 } else if (Name == "\1fseeko64" ||
2395 Name == "\1ftello64") {
2396 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2397 return;
2398 setDoesNotThrow(F);
2399 setDoesNotCapture(F, 1);
2400 } else if (Name == "\1tmpfile64") {
2401 if (!FTy->getReturnType()->isPointerTy())
2402 return;
2403 setDoesNotThrow(F);
2404 setDoesNotAlias(F, 0);
2405 } else if (Name == "\1fstat64" ||
2406 Name == "\1fstatvfs64") {
2407 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2408 return;
2409 setDoesNotThrow(F);
2410 setDoesNotCapture(F, 2);
2411 } else if (Name == "\1open64") {
2412 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2413 return;
2414 // May throw; "open" is a valid pthread cancellation point.
2415 setDoesNotCapture(F, 1);
2416 }
2417 break;
2418 }
2419}
2420
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002421/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002422///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002423bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002424 Modified = false;
2425 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2426 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002427 if (F.isDeclaration() && F.hasName())
2428 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002429 }
2430 return Modified;
2431}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002432
2433// TODO:
2434// Additional cases that we need to add to this file:
2435//
2436// cbrt:
2437// * cbrt(expN(X)) -> expN(x/3)
2438// * cbrt(sqrt(x)) -> pow(x,1/6)
2439// * cbrt(sqrt(x)) -> pow(x,1/9)
2440//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002441// exp, expf, expl:
2442// * exp(log(x)) -> x
2443//
2444// log, logf, logl:
2445// * log(exp(x)) -> x
2446// * log(x**y) -> y*log(x)
2447// * log(exp(y)) -> y*log(e)
2448// * log(exp2(y)) -> y*log(2)
2449// * log(exp10(y)) -> y*log(10)
2450// * log(sqrt(x)) -> 0.5*log(x)
2451// * log(pow(x,y)) -> y*log(x)
2452//
2453// lround, lroundf, lroundl:
2454// * lround(cnst) -> cnst'
2455//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002456// pow, powf, powl:
2457// * pow(exp(x),y) -> exp(x*y)
2458// * pow(sqrt(x),y) -> pow(x,y*0.5)
2459// * pow(pow(x,y),z)-> pow(x,y*z)
2460//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002461// round, roundf, roundl:
2462// * round(cnst) -> cnst'
2463//
2464// signbit:
2465// * signbit(cnst) -> cnst'
2466// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2467//
2468// sqrt, sqrtf, sqrtl:
2469// * sqrt(expN(x)) -> expN(x*0.5)
2470// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2471// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2472//
Chris Lattner18c7f802012-02-05 02:29:43 +00002473// strchr:
2474// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002475// tan, tanf, tanl:
2476// * tan(atan(x)) -> x
2477//
2478// trunc, truncf, truncl:
2479// * trunc(cnst) -> cnst'
2480//
2481//