blob: f110320c1bf9943afd7d63e6dce526643b10cb50 [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);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001554 void InitOptimizations();
1555 bool runOnFunction(Function &F);
1556
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001557 void setDoesNotAccessMemory(Function &F);
1558 void setOnlyReadsMemory(Function &F);
1559 void setDoesNotThrow(Function &F);
1560 void setDoesNotCapture(Function &F, unsigned n);
1561 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001562 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001563
Chris Lattnere265ad82011-02-24 07:12:12 +00001564 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001565 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001566 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001567 }
1568 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001569} // end anonymous namespace.
1570
Chris Lattnerafbf4832011-02-24 07:16:14 +00001571char SimplifyLibCalls::ID = 0;
1572
1573INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1574 "Simplify well-known library calls", false, false)
1575INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1576INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1577 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001578
1579// Public interface to the Simplify LibCalls pass.
1580FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001581 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001582}
1583
Eli Friedman9d434db2011-11-17 01:27:36 +00001584void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1585 if (TLI->has(F))
1586 Optimizations[TLI->getName(F)] = Opt;
1587}
1588
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001589/// Optimizations - Populate the Optimizations map with all the optimizations
1590/// we know.
1591void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001592 // String and Memory LibCall Optimizations
1593 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001594 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001595 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001596 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001597 Optimizations["strcmp"] = &StrCmp;
1598 Optimizations["strncmp"] = &StrNCmp;
1599 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001600 Optimizations["strncpy"] = &StrNCpy;
David Majnemerac782662012-05-15 11:46:21 +00001601 Optimizations["stpcpy"] = &StpCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001602 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001603 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001604 Optimizations["strtol"] = &StrTo;
1605 Optimizations["strtod"] = &StrTo;
1606 Optimizations["strtof"] = &StrTo;
1607 Optimizations["strtoul"] = &StrTo;
1608 Optimizations["strtoll"] = &StrTo;
1609 Optimizations["strtold"] = &StrTo;
1610 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001611 Optimizations["strspn"] = &StrSpn;
1612 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001613 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001614 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001615 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001616 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001617 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001618
Evan Cheng0289b412010-03-23 15:48:04 +00001619 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001620 Optimizations["__strcpy_chk"] = &StrCpyChk;
David Majnemerac782662012-05-15 11:46:21 +00001621 Optimizations["__stpcpy_chk"] = &StpCpyChk;
Evan Cheng0289b412010-03-23 15:48:04 +00001622
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001623 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001624 Optimizations["cosf"] = &Cos;
1625 Optimizations["cos"] = &Cos;
1626 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001627 Optimizations["powf"] = &Pow;
1628 Optimizations["pow"] = &Pow;
1629 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001630 Optimizations["llvm.pow.f32"] = &Pow;
1631 Optimizations["llvm.pow.f64"] = &Pow;
1632 Optimizations["llvm.pow.f80"] = &Pow;
1633 Optimizations["llvm.pow.f128"] = &Pow;
1634 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001635 Optimizations["exp2l"] = &Exp2;
1636 Optimizations["exp2"] = &Exp2;
1637 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001638 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1639 Optimizations["llvm.exp2.f128"] = &Exp2;
1640 Optimizations["llvm.exp2.f80"] = &Exp2;
1641 Optimizations["llvm.exp2.f64"] = &Exp2;
1642 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001643
Joe Groffd5bda5e2012-04-17 23:05:54 +00001644 if (TLI->has(LibFunc::floor) && TLI->has(LibFunc::floorf))
1645 Optimizations["floor"] = &UnaryDoubleFP;
1646 if (TLI->has(LibFunc::ceil) && TLI->has(LibFunc::ceilf))
1647 Optimizations["ceil"] = &UnaryDoubleFP;
1648 if (TLI->has(LibFunc::round) && TLI->has(LibFunc::roundf))
1649 Optimizations["round"] = &UnaryDoubleFP;
1650 if (TLI->has(LibFunc::rint) && TLI->has(LibFunc::rintf))
1651 Optimizations["rint"] = &UnaryDoubleFP;
1652 if (TLI->has(LibFunc::nearbyint) && TLI->has(LibFunc::nearbyintf))
1653 Optimizations["nearbyint"] = &UnaryDoubleFP;
Eric Christopher37c8b862009-10-07 21:14:25 +00001654
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001655 // Integer Optimizations
1656 Optimizations["ffs"] = &FFS;
1657 Optimizations["ffsl"] = &FFS;
1658 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001659 Optimizations["abs"] = &Abs;
1660 Optimizations["labs"] = &Abs;
1661 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001662 Optimizations["isdigit"] = &IsDigit;
1663 Optimizations["isascii"] = &IsAscii;
1664 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001665
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001666 // Formatting and IO Optimizations
1667 Optimizations["sprintf"] = &SPrintF;
1668 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001669 AddOpt(LibFunc::fwrite, &FWrite);
1670 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001671 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001672 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001673}
1674
1675
1676/// runOnFunction - Top level algorithm.
1677///
1678bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001679 TLI = &getAnalysis<TargetLibraryInfo>();
1680
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001681 if (Optimizations.empty())
1682 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001683
Dan Gohmanf14d9192009-08-18 00:48:13 +00001684 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001685
Owen Andersone922c022009-07-22 00:24:57 +00001686 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001687
1688 bool Changed = false;
1689 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1690 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1691 // Ignore non-calls.
1692 CallInst *CI = dyn_cast<CallInst>(I++);
1693 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001694
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001695 // Ignore indirect calls and calls to non-external functions.
1696 Function *Callee = CI->getCalledFunction();
1697 if (Callee == 0 || !Callee->isDeclaration() ||
1698 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1699 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001700
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001701 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001702 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1703 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001704
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001705 // Set the builder to the instruction after the call.
1706 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001707
Devang Patela2ab3992011-03-09 21:27:52 +00001708 // Use debug location of CI for all new instructions.
1709 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1710
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001711 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001712 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001713 if (Result == 0) continue;
1714
David Greene6a6b90e2010-01-05 01:27:21 +00001715 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1716 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001717
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001718 // Something changed!
1719 Changed = true;
1720 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001721
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001722 // Inspect the instruction after the call (which was potentially just
1723 // added) next.
1724 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001725
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001726 if (CI != Result && !CI->use_empty()) {
1727 CI->replaceAllUsesWith(Result);
1728 if (!Result->hasName())
1729 Result->takeName(CI);
1730 }
1731 CI->eraseFromParent();
1732 }
1733 }
1734 return Changed;
1735}
1736
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001737// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001738
1739void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1740 if (!F.doesNotAccessMemory()) {
1741 F.setDoesNotAccessMemory();
1742 ++NumAnnotated;
1743 Modified = true;
1744 }
1745}
1746void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1747 if (!F.onlyReadsMemory()) {
1748 F.setOnlyReadsMemory();
1749 ++NumAnnotated;
1750 Modified = true;
1751 }
1752}
1753void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1754 if (!F.doesNotThrow()) {
1755 F.setDoesNotThrow();
1756 ++NumAnnotated;
1757 Modified = true;
1758 }
1759}
1760void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1761 if (!F.doesNotCapture(n)) {
1762 F.setDoesNotCapture(n);
1763 ++NumAnnotated;
1764 Modified = true;
1765 }
1766}
1767void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1768 if (!F.doesNotAlias(n)) {
1769 F.setDoesNotAlias(n);
1770 ++NumAnnotated;
1771 Modified = true;
1772 }
1773}
1774
Chris Lattnere265ad82011-02-24 07:12:12 +00001775
1776void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001777 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001778
Chris Lattnere265ad82011-02-24 07:12:12 +00001779 StringRef Name = F.getName();
1780 switch (Name[0]) {
1781 case 's':
1782 if (Name == "strlen") {
1783 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1784 return;
1785 setOnlyReadsMemory(F);
1786 setDoesNotThrow(F);
1787 setDoesNotCapture(F, 1);
1788 } else if (Name == "strchr" ||
1789 Name == "strrchr") {
1790 if (FTy->getNumParams() != 2 ||
1791 !FTy->getParamType(0)->isPointerTy() ||
1792 !FTy->getParamType(1)->isIntegerTy())
1793 return;
1794 setOnlyReadsMemory(F);
1795 setDoesNotThrow(F);
1796 } else if (Name == "strcpy" ||
1797 Name == "stpcpy" ||
1798 Name == "strcat" ||
1799 Name == "strtol" ||
1800 Name == "strtod" ||
1801 Name == "strtof" ||
1802 Name == "strtoul" ||
1803 Name == "strtoll" ||
1804 Name == "strtold" ||
1805 Name == "strncat" ||
1806 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001807 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001808 Name == "strtoull") {
1809 if (FTy->getNumParams() < 2 ||
1810 !FTy->getParamType(1)->isPointerTy())
1811 return;
1812 setDoesNotThrow(F);
1813 setDoesNotCapture(F, 2);
1814 } else if (Name == "strxfrm") {
1815 if (FTy->getNumParams() != 3 ||
1816 !FTy->getParamType(0)->isPointerTy() ||
1817 !FTy->getParamType(1)->isPointerTy())
1818 return;
1819 setDoesNotThrow(F);
1820 setDoesNotCapture(F, 1);
1821 setDoesNotCapture(F, 2);
1822 } else if (Name == "strcmp" ||
1823 Name == "strspn" ||
1824 Name == "strncmp" ||
1825 Name == "strcspn" ||
1826 Name == "strcoll" ||
1827 Name == "strcasecmp" ||
1828 Name == "strncasecmp") {
1829 if (FTy->getNumParams() < 2 ||
1830 !FTy->getParamType(0)->isPointerTy() ||
1831 !FTy->getParamType(1)->isPointerTy())
1832 return;
1833 setOnlyReadsMemory(F);
1834 setDoesNotThrow(F);
1835 setDoesNotCapture(F, 1);
1836 setDoesNotCapture(F, 2);
1837 } else if (Name == "strstr" ||
1838 Name == "strpbrk") {
1839 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1840 return;
1841 setOnlyReadsMemory(F);
1842 setDoesNotThrow(F);
1843 setDoesNotCapture(F, 2);
1844 } else if (Name == "strtok" ||
1845 Name == "strtok_r") {
1846 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1847 return;
1848 setDoesNotThrow(F);
1849 setDoesNotCapture(F, 2);
1850 } else if (Name == "scanf" ||
1851 Name == "setbuf" ||
1852 Name == "setvbuf") {
1853 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1854 return;
1855 setDoesNotThrow(F);
1856 setDoesNotCapture(F, 1);
1857 } else if (Name == "strdup" ||
1858 Name == "strndup") {
1859 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1860 !FTy->getParamType(0)->isPointerTy())
1861 return;
1862 setDoesNotThrow(F);
1863 setDoesNotAlias(F, 0);
1864 setDoesNotCapture(F, 1);
1865 } else if (Name == "stat" ||
1866 Name == "sscanf" ||
1867 Name == "sprintf" ||
1868 Name == "statvfs") {
1869 if (FTy->getNumParams() < 2 ||
1870 !FTy->getParamType(0)->isPointerTy() ||
1871 !FTy->getParamType(1)->isPointerTy())
1872 return;
1873 setDoesNotThrow(F);
1874 setDoesNotCapture(F, 1);
1875 setDoesNotCapture(F, 2);
1876 } else if (Name == "snprintf") {
1877 if (FTy->getNumParams() != 3 ||
1878 !FTy->getParamType(0)->isPointerTy() ||
1879 !FTy->getParamType(2)->isPointerTy())
1880 return;
1881 setDoesNotThrow(F);
1882 setDoesNotCapture(F, 1);
1883 setDoesNotCapture(F, 3);
1884 } else if (Name == "setitimer") {
1885 if (FTy->getNumParams() != 3 ||
1886 !FTy->getParamType(1)->isPointerTy() ||
1887 !FTy->getParamType(2)->isPointerTy())
1888 return;
1889 setDoesNotThrow(F);
1890 setDoesNotCapture(F, 2);
1891 setDoesNotCapture(F, 3);
1892 } else if (Name == "system") {
1893 if (FTy->getNumParams() != 1 ||
1894 !FTy->getParamType(0)->isPointerTy())
1895 return;
1896 // May throw; "system" is a valid pthread cancellation point.
1897 setDoesNotCapture(F, 1);
1898 }
1899 break;
1900 case 'm':
1901 if (Name == "malloc") {
1902 if (FTy->getNumParams() != 1 ||
1903 !FTy->getReturnType()->isPointerTy())
1904 return;
1905 setDoesNotThrow(F);
1906 setDoesNotAlias(F, 0);
1907 } else if (Name == "memcmp") {
1908 if (FTy->getNumParams() != 3 ||
1909 !FTy->getParamType(0)->isPointerTy() ||
1910 !FTy->getParamType(1)->isPointerTy())
1911 return;
1912 setOnlyReadsMemory(F);
1913 setDoesNotThrow(F);
1914 setDoesNotCapture(F, 1);
1915 setDoesNotCapture(F, 2);
1916 } else if (Name == "memchr" ||
1917 Name == "memrchr") {
1918 if (FTy->getNumParams() != 3)
1919 return;
1920 setOnlyReadsMemory(F);
1921 setDoesNotThrow(F);
1922 } else if (Name == "modf" ||
1923 Name == "modff" ||
1924 Name == "modfl" ||
1925 Name == "memcpy" ||
1926 Name == "memccpy" ||
1927 Name == "memmove") {
1928 if (FTy->getNumParams() < 2 ||
1929 !FTy->getParamType(1)->isPointerTy())
1930 return;
1931 setDoesNotThrow(F);
1932 setDoesNotCapture(F, 2);
1933 } else if (Name == "memalign") {
1934 if (!FTy->getReturnType()->isPointerTy())
1935 return;
1936 setDoesNotAlias(F, 0);
1937 } else if (Name == "mkdir" ||
1938 Name == "mktime") {
1939 if (FTy->getNumParams() == 0 ||
1940 !FTy->getParamType(0)->isPointerTy())
1941 return;
1942 setDoesNotThrow(F);
1943 setDoesNotCapture(F, 1);
1944 }
1945 break;
1946 case 'r':
1947 if (Name == "realloc") {
1948 if (FTy->getNumParams() != 2 ||
1949 !FTy->getParamType(0)->isPointerTy() ||
1950 !FTy->getReturnType()->isPointerTy())
1951 return;
1952 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +00001953 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +00001954 setDoesNotCapture(F, 1);
1955 } else if (Name == "read") {
1956 if (FTy->getNumParams() != 3 ||
1957 !FTy->getParamType(1)->isPointerTy())
1958 return;
1959 // May throw; "read" is a valid pthread cancellation point.
1960 setDoesNotCapture(F, 2);
1961 } else if (Name == "rmdir" ||
1962 Name == "rewind" ||
1963 Name == "remove" ||
1964 Name == "realpath") {
1965 if (FTy->getNumParams() < 1 ||
1966 !FTy->getParamType(0)->isPointerTy())
1967 return;
1968 setDoesNotThrow(F);
1969 setDoesNotCapture(F, 1);
1970 } else if (Name == "rename" ||
1971 Name == "readlink") {
1972 if (FTy->getNumParams() < 2 ||
1973 !FTy->getParamType(0)->isPointerTy() ||
1974 !FTy->getParamType(1)->isPointerTy())
1975 return;
1976 setDoesNotThrow(F);
1977 setDoesNotCapture(F, 1);
1978 setDoesNotCapture(F, 2);
1979 }
1980 break;
1981 case 'w':
1982 if (Name == "write") {
1983 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1984 return;
1985 // May throw; "write" is a valid pthread cancellation point.
1986 setDoesNotCapture(F, 2);
1987 }
1988 break;
1989 case 'b':
1990 if (Name == "bcopy") {
1991 if (FTy->getNumParams() != 3 ||
1992 !FTy->getParamType(0)->isPointerTy() ||
1993 !FTy->getParamType(1)->isPointerTy())
1994 return;
1995 setDoesNotThrow(F);
1996 setDoesNotCapture(F, 1);
1997 setDoesNotCapture(F, 2);
1998 } else if (Name == "bcmp") {
1999 if (FTy->getNumParams() != 3 ||
2000 !FTy->getParamType(0)->isPointerTy() ||
2001 !FTy->getParamType(1)->isPointerTy())
2002 return;
2003 setDoesNotThrow(F);
2004 setOnlyReadsMemory(F);
2005 setDoesNotCapture(F, 1);
2006 setDoesNotCapture(F, 2);
2007 } else if (Name == "bzero") {
2008 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2009 return;
2010 setDoesNotThrow(F);
2011 setDoesNotCapture(F, 1);
2012 }
2013 break;
2014 case 'c':
2015 if (Name == "calloc") {
2016 if (FTy->getNumParams() != 2 ||
2017 !FTy->getReturnType()->isPointerTy())
2018 return;
2019 setDoesNotThrow(F);
2020 setDoesNotAlias(F, 0);
2021 } else if (Name == "chmod" ||
2022 Name == "chown" ||
2023 Name == "ctermid" ||
2024 Name == "clearerr" ||
2025 Name == "closedir") {
2026 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2027 return;
2028 setDoesNotThrow(F);
2029 setDoesNotCapture(F, 1);
2030 }
2031 break;
2032 case 'a':
2033 if (Name == "atoi" ||
2034 Name == "atol" ||
2035 Name == "atof" ||
2036 Name == "atoll") {
2037 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2038 return;
2039 setDoesNotThrow(F);
2040 setOnlyReadsMemory(F);
2041 setDoesNotCapture(F, 1);
2042 } else if (Name == "access") {
2043 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2044 return;
2045 setDoesNotThrow(F);
2046 setDoesNotCapture(F, 1);
2047 }
2048 break;
2049 case 'f':
2050 if (Name == "fopen") {
2051 if (FTy->getNumParams() != 2 ||
2052 !FTy->getReturnType()->isPointerTy() ||
2053 !FTy->getParamType(0)->isPointerTy() ||
2054 !FTy->getParamType(1)->isPointerTy())
2055 return;
2056 setDoesNotThrow(F);
2057 setDoesNotAlias(F, 0);
2058 setDoesNotCapture(F, 1);
2059 setDoesNotCapture(F, 2);
2060 } else if (Name == "fdopen") {
2061 if (FTy->getNumParams() != 2 ||
2062 !FTy->getReturnType()->isPointerTy() ||
2063 !FTy->getParamType(1)->isPointerTy())
2064 return;
2065 setDoesNotThrow(F);
2066 setDoesNotAlias(F, 0);
2067 setDoesNotCapture(F, 2);
2068 } else if (Name == "feof" ||
2069 Name == "free" ||
2070 Name == "fseek" ||
2071 Name == "ftell" ||
2072 Name == "fgetc" ||
2073 Name == "fseeko" ||
2074 Name == "ftello" ||
2075 Name == "fileno" ||
2076 Name == "fflush" ||
2077 Name == "fclose" ||
2078 Name == "fsetpos" ||
2079 Name == "flockfile" ||
2080 Name == "funlockfile" ||
2081 Name == "ftrylockfile") {
2082 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2083 return;
2084 setDoesNotThrow(F);
2085 setDoesNotCapture(F, 1);
2086 } else if (Name == "ferror") {
2087 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2088 return;
2089 setDoesNotThrow(F);
2090 setDoesNotCapture(F, 1);
2091 setOnlyReadsMemory(F);
2092 } else if (Name == "fputc" ||
2093 Name == "fstat" ||
2094 Name == "frexp" ||
2095 Name == "frexpf" ||
2096 Name == "frexpl" ||
2097 Name == "fstatvfs") {
2098 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2099 return;
2100 setDoesNotThrow(F);
2101 setDoesNotCapture(F, 2);
2102 } else if (Name == "fgets") {
2103 if (FTy->getNumParams() != 3 ||
2104 !FTy->getParamType(0)->isPointerTy() ||
2105 !FTy->getParamType(2)->isPointerTy())
2106 return;
2107 setDoesNotThrow(F);
2108 setDoesNotCapture(F, 3);
2109 } else if (Name == "fread" ||
2110 Name == "fwrite") {
2111 if (FTy->getNumParams() != 4 ||
2112 !FTy->getParamType(0)->isPointerTy() ||
2113 !FTy->getParamType(3)->isPointerTy())
2114 return;
2115 setDoesNotThrow(F);
2116 setDoesNotCapture(F, 1);
2117 setDoesNotCapture(F, 4);
2118 } else if (Name == "fputs" ||
2119 Name == "fscanf" ||
2120 Name == "fprintf" ||
2121 Name == "fgetpos") {
2122 if (FTy->getNumParams() < 2 ||
2123 !FTy->getParamType(0)->isPointerTy() ||
2124 !FTy->getParamType(1)->isPointerTy())
2125 return;
2126 setDoesNotThrow(F);
2127 setDoesNotCapture(F, 1);
2128 setDoesNotCapture(F, 2);
2129 }
2130 break;
2131 case 'g':
2132 if (Name == "getc" ||
2133 Name == "getlogin_r" ||
2134 Name == "getc_unlocked") {
2135 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2136 return;
2137 setDoesNotThrow(F);
2138 setDoesNotCapture(F, 1);
2139 } else if (Name == "getenv") {
2140 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2141 return;
2142 setDoesNotThrow(F);
2143 setOnlyReadsMemory(F);
2144 setDoesNotCapture(F, 1);
2145 } else if (Name == "gets" ||
2146 Name == "getchar") {
2147 setDoesNotThrow(F);
2148 } else if (Name == "getitimer") {
2149 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2150 return;
2151 setDoesNotThrow(F);
2152 setDoesNotCapture(F, 2);
2153 } else if (Name == "getpwnam") {
2154 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2155 return;
2156 setDoesNotThrow(F);
2157 setDoesNotCapture(F, 1);
2158 }
2159 break;
2160 case 'u':
2161 if (Name == "ungetc") {
2162 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2163 return;
2164 setDoesNotThrow(F);
2165 setDoesNotCapture(F, 2);
2166 } else if (Name == "uname" ||
2167 Name == "unlink" ||
2168 Name == "unsetenv") {
2169 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2170 return;
2171 setDoesNotThrow(F);
2172 setDoesNotCapture(F, 1);
2173 } else if (Name == "utime" ||
2174 Name == "utimes") {
2175 if (FTy->getNumParams() != 2 ||
2176 !FTy->getParamType(0)->isPointerTy() ||
2177 !FTy->getParamType(1)->isPointerTy())
2178 return;
2179 setDoesNotThrow(F);
2180 setDoesNotCapture(F, 1);
2181 setDoesNotCapture(F, 2);
2182 }
2183 break;
2184 case 'p':
2185 if (Name == "putc") {
2186 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2187 return;
2188 setDoesNotThrow(F);
2189 setDoesNotCapture(F, 2);
2190 } else if (Name == "puts" ||
2191 Name == "printf" ||
2192 Name == "perror") {
2193 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2194 return;
2195 setDoesNotThrow(F);
2196 setDoesNotCapture(F, 1);
2197 } else if (Name == "pread" ||
2198 Name == "pwrite") {
2199 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2200 return;
2201 // May throw; these are valid pthread cancellation points.
2202 setDoesNotCapture(F, 2);
2203 } else if (Name == "putchar") {
2204 setDoesNotThrow(F);
2205 } else if (Name == "popen") {
2206 if (FTy->getNumParams() != 2 ||
2207 !FTy->getReturnType()->isPointerTy() ||
2208 !FTy->getParamType(0)->isPointerTy() ||
2209 !FTy->getParamType(1)->isPointerTy())
2210 return;
2211 setDoesNotThrow(F);
2212 setDoesNotAlias(F, 0);
2213 setDoesNotCapture(F, 1);
2214 setDoesNotCapture(F, 2);
2215 } else if (Name == "pclose") {
2216 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2217 return;
2218 setDoesNotThrow(F);
2219 setDoesNotCapture(F, 1);
2220 }
2221 break;
2222 case 'v':
2223 if (Name == "vscanf") {
2224 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2225 return;
2226 setDoesNotThrow(F);
2227 setDoesNotCapture(F, 1);
2228 } else if (Name == "vsscanf" ||
2229 Name == "vfscanf") {
2230 if (FTy->getNumParams() != 3 ||
2231 !FTy->getParamType(1)->isPointerTy() ||
2232 !FTy->getParamType(2)->isPointerTy())
2233 return;
2234 setDoesNotThrow(F);
2235 setDoesNotCapture(F, 1);
2236 setDoesNotCapture(F, 2);
2237 } else if (Name == "valloc") {
2238 if (!FTy->getReturnType()->isPointerTy())
2239 return;
2240 setDoesNotThrow(F);
2241 setDoesNotAlias(F, 0);
2242 } else if (Name == "vprintf") {
2243 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2244 return;
2245 setDoesNotThrow(F);
2246 setDoesNotCapture(F, 1);
2247 } else if (Name == "vfprintf" ||
2248 Name == "vsprintf") {
2249 if (FTy->getNumParams() != 3 ||
2250 !FTy->getParamType(0)->isPointerTy() ||
2251 !FTy->getParamType(1)->isPointerTy())
2252 return;
2253 setDoesNotThrow(F);
2254 setDoesNotCapture(F, 1);
2255 setDoesNotCapture(F, 2);
2256 } else if (Name == "vsnprintf") {
2257 if (FTy->getNumParams() != 4 ||
2258 !FTy->getParamType(0)->isPointerTy() ||
2259 !FTy->getParamType(2)->isPointerTy())
2260 return;
2261 setDoesNotThrow(F);
2262 setDoesNotCapture(F, 1);
2263 setDoesNotCapture(F, 3);
2264 }
2265 break;
2266 case 'o':
2267 if (Name == "open") {
2268 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2269 return;
2270 // May throw; "open" is a valid pthread cancellation point.
2271 setDoesNotCapture(F, 1);
2272 } else if (Name == "opendir") {
2273 if (FTy->getNumParams() != 1 ||
2274 !FTy->getReturnType()->isPointerTy() ||
2275 !FTy->getParamType(0)->isPointerTy())
2276 return;
2277 setDoesNotThrow(F);
2278 setDoesNotAlias(F, 0);
2279 setDoesNotCapture(F, 1);
2280 }
2281 break;
2282 case 't':
2283 if (Name == "tmpfile") {
2284 if (!FTy->getReturnType()->isPointerTy())
2285 return;
2286 setDoesNotThrow(F);
2287 setDoesNotAlias(F, 0);
2288 } else if (Name == "times") {
2289 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2290 return;
2291 setDoesNotThrow(F);
2292 setDoesNotCapture(F, 1);
2293 }
2294 break;
2295 case 'h':
2296 if (Name == "htonl" ||
2297 Name == "htons") {
2298 setDoesNotThrow(F);
2299 setDoesNotAccessMemory(F);
2300 }
2301 break;
2302 case 'n':
2303 if (Name == "ntohl" ||
2304 Name == "ntohs") {
2305 setDoesNotThrow(F);
2306 setDoesNotAccessMemory(F);
2307 }
2308 break;
2309 case 'l':
2310 if (Name == "lstat") {
2311 if (FTy->getNumParams() != 2 ||
2312 !FTy->getParamType(0)->isPointerTy() ||
2313 !FTy->getParamType(1)->isPointerTy())
2314 return;
2315 setDoesNotThrow(F);
2316 setDoesNotCapture(F, 1);
2317 setDoesNotCapture(F, 2);
2318 } else if (Name == "lchown") {
2319 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2320 return;
2321 setDoesNotThrow(F);
2322 setDoesNotCapture(F, 1);
2323 }
2324 break;
2325 case 'q':
2326 if (Name == "qsort") {
2327 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2328 return;
2329 // May throw; places call through function pointer.
2330 setDoesNotCapture(F, 4);
2331 }
2332 break;
2333 case '_':
2334 if (Name == "__strdup" ||
2335 Name == "__strndup") {
2336 if (FTy->getNumParams() < 1 ||
2337 !FTy->getReturnType()->isPointerTy() ||
2338 !FTy->getParamType(0)->isPointerTy())
2339 return;
2340 setDoesNotThrow(F);
2341 setDoesNotAlias(F, 0);
2342 setDoesNotCapture(F, 1);
2343 } else if (Name == "__strtok_r") {
2344 if (FTy->getNumParams() != 3 ||
2345 !FTy->getParamType(1)->isPointerTy())
2346 return;
2347 setDoesNotThrow(F);
2348 setDoesNotCapture(F, 2);
2349 } else if (Name == "_IO_getc") {
2350 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2351 return;
2352 setDoesNotThrow(F);
2353 setDoesNotCapture(F, 1);
2354 } else if (Name == "_IO_putc") {
2355 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2356 return;
2357 setDoesNotThrow(F);
2358 setDoesNotCapture(F, 2);
2359 }
2360 break;
2361 case 1:
2362 if (Name == "\1__isoc99_scanf") {
2363 if (FTy->getNumParams() < 1 ||
2364 !FTy->getParamType(0)->isPointerTy())
2365 return;
2366 setDoesNotThrow(F);
2367 setDoesNotCapture(F, 1);
2368 } else if (Name == "\1stat64" ||
2369 Name == "\1lstat64" ||
2370 Name == "\1statvfs64" ||
2371 Name == "\1__isoc99_sscanf") {
2372 if (FTy->getNumParams() < 1 ||
2373 !FTy->getParamType(0)->isPointerTy() ||
2374 !FTy->getParamType(1)->isPointerTy())
2375 return;
2376 setDoesNotThrow(F);
2377 setDoesNotCapture(F, 1);
2378 setDoesNotCapture(F, 2);
2379 } else if (Name == "\1fopen64") {
2380 if (FTy->getNumParams() != 2 ||
2381 !FTy->getReturnType()->isPointerTy() ||
2382 !FTy->getParamType(0)->isPointerTy() ||
2383 !FTy->getParamType(1)->isPointerTy())
2384 return;
2385 setDoesNotThrow(F);
2386 setDoesNotAlias(F, 0);
2387 setDoesNotCapture(F, 1);
2388 setDoesNotCapture(F, 2);
2389 } else if (Name == "\1fseeko64" ||
2390 Name == "\1ftello64") {
2391 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2392 return;
2393 setDoesNotThrow(F);
2394 setDoesNotCapture(F, 1);
2395 } else if (Name == "\1tmpfile64") {
2396 if (!FTy->getReturnType()->isPointerTy())
2397 return;
2398 setDoesNotThrow(F);
2399 setDoesNotAlias(F, 0);
2400 } else if (Name == "\1fstat64" ||
2401 Name == "\1fstatvfs64") {
2402 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2403 return;
2404 setDoesNotThrow(F);
2405 setDoesNotCapture(F, 2);
2406 } else if (Name == "\1open64") {
2407 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2408 return;
2409 // May throw; "open" is a valid pthread cancellation point.
2410 setDoesNotCapture(F, 1);
2411 }
2412 break;
2413 }
2414}
2415
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002416/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002417///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002418bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002419 Modified = false;
2420 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2421 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002422 if (F.isDeclaration() && F.hasName())
2423 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002424 }
2425 return Modified;
2426}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002427
2428// TODO:
2429// Additional cases that we need to add to this file:
2430//
2431// cbrt:
2432// * cbrt(expN(X)) -> expN(x/3)
2433// * cbrt(sqrt(x)) -> pow(x,1/6)
2434// * cbrt(sqrt(x)) -> pow(x,1/9)
2435//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002436// exp, expf, expl:
2437// * exp(log(x)) -> x
2438//
2439// log, logf, logl:
2440// * log(exp(x)) -> x
2441// * log(x**y) -> y*log(x)
2442// * log(exp(y)) -> y*log(e)
2443// * log(exp2(y)) -> y*log(2)
2444// * log(exp10(y)) -> y*log(10)
2445// * log(sqrt(x)) -> 0.5*log(x)
2446// * log(pow(x,y)) -> y*log(x)
2447//
2448// lround, lroundf, lroundl:
2449// * lround(cnst) -> cnst'
2450//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002451// pow, powf, powl:
2452// * pow(exp(x),y) -> exp(x*y)
2453// * pow(sqrt(x),y) -> pow(x,y*0.5)
2454// * pow(pow(x,y),z)-> pow(x,y*z)
2455//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002456// round, roundf, roundl:
2457// * round(cnst) -> cnst'
2458//
2459// signbit:
2460// * signbit(cnst) -> cnst'
2461// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2462//
2463// sqrt, sqrtf, sqrtl:
2464// * sqrt(expN(x)) -> expN(x*0.5)
2465// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2466// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2467//
Chris Lattner18c7f802012-02-05 02:29:43 +00002468// strchr:
2469// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002470// tan, tanf, tanl:
2471// * tan(atan(x)) -> x
2472//
2473// trunc, truncf, truncl:
2474// * trunc(cnst) -> cnst'
2475//
2476//