blob: 170e3aa658eea1efd733ce2eeee34ff1ef71693e [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"
20#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000021#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000025#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringMap.h"
29#include "llvm/ADT/Statistic.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000030#include "llvm/ADT/STLExtras.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"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000033#include "llvm/Config/config.h"
34using namespace llvm;
35
36STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000037STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000038
39//===----------------------------------------------------------------------===//
40// Optimizer Base Class
41//===----------------------------------------------------------------------===//
42
43/// This class is the abstract base class for the set of optimizations that
44/// corresponds to one library call.
45namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000046class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000047protected:
48 Function *Caller;
49 const TargetData *TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000050 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000051public:
52 LibCallOptimization() { }
53 virtual ~LibCallOptimization() {}
54
55 /// CallOptimizer - This pure virtual method is implemented by base classes to
56 /// do various optimizations. If this returns null then no transformation was
57 /// performed. If it returns CI, then it transformed the call and CI is to be
58 /// deleted. If it returns something else, replace CI with the new value and
59 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000060 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000061 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000062
Dan Gohmanf14d9192009-08-18 00:48:13 +000063 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000064 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000065 this->TD = TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000066 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000067 Context = &CI->getCalledFunction()->getContext();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000068 return CallOptimizer(CI->getCalledFunction(), CI, B);
69 }
70
71 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000072 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000073
74 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
75 /// specified pointer. Ptr is required to be some pointer type, and the
76 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000077 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +000078
Chris Lattner24604112009-12-16 09:32:05 +000079 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
80 /// specified pointer and character. Ptr is required to be some pointer type,
81 /// and the return value has 'i8*' type.
82 Value *EmitStrChr(Value *Ptr, char C, IRBuilder<> &B);
83
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000084 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
85 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
Eric Christopher37c8b862009-10-07 21:14:25 +000086 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000087 unsigned Align, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +000088
Eric Christopher80bf1d52009-11-21 01:01:30 +000089 /// EmitMemMove - Emit a call to the memmove function to the builder. This
90 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
91 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
92 unsigned Align, IRBuilder<> &B);
93
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000094 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
95 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000096 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +000097
98 /// EmitMemCmp - Emit a call to the memcmp function.
99 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
100
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000101 /// EmitMemSet - Emit a call to the memset function
102 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
103
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000104 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
105 /// 'floor'). This function is known to take a single of type matching 'Op'
106 /// and returns one value with the same type. If 'Op' is a long double, 'l'
107 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
Dan Gohman79cb8402009-09-25 23:10:17 +0000108 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
109 const AttrListPtr &Attrs);
Eric Christopher37c8b862009-10-07 21:14:25 +0000110
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000111 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
112 /// is an integer.
Chris Lattner74965f22009-11-09 04:57:04 +0000113 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000114
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000115 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
116 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000117 void EmitPutS(Value *Str, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000118
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000119 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
120 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000121 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000122
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000123 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
124 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000125 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000126
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000127 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
128 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000129 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000130
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000131};
132} // End anonymous namespace.
133
134/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000135Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Chris Lattnerbf796322009-12-02 06:05:42 +0000136 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000137}
138
139/// EmitStrLen - Emit a call to the strlen function to the builder, for the
140/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000141Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000142 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000143 AttributeWithIndex AWI[2];
144 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
145 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
146 Attribute::NoUnwind);
147
148 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
Owen Anderson1d0be152009-08-13 21:58:54 +0000149 TD->getIntPtrType(*Context),
Eric Christopher37c8b862009-10-07 21:14:25 +0000150 Type::getInt8PtrTy(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000151 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000152 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
153 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
154 CI->setCallingConv(F->getCallingConv());
155
156 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000157}
158
Chris Lattner24604112009-12-16 09:32:05 +0000159/// EmitStrChr - Emit a call to the strchr function to the builder, for the
160/// specified pointer and character. Ptr is required to be some pointer type,
161/// and the return value has 'i8*' type.
162Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
163 Module *M = Caller->getParent();
164 AttributeWithIndex AWI =
165 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
166
167 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
168 const Type *I32Ty = Type::getInt32Ty(*Context);
169 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
170 I8Ptr, I8Ptr, I32Ty, NULL);
171 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
172 ConstantInt::get(I32Ty, C), "strchr");
173 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
174 CI->setCallingConv(F->getCallingConv());
175 return CI;
176}
177
178
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000179/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
180/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
181Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000182 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000183 Module *M = Caller->getParent();
Chris Lattnerbf796322009-12-02 06:05:42 +0000184 const Type *Ty = Len->getType();
185 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
186 Dst = CastToCStr(Dst, B);
187 Src = CastToCStr(Src, B);
188 return B.CreateCall4(MemCpy, Dst, Src, Len,
Owen Anderson1d0be152009-08-13 21:58:54 +0000189 ConstantInt::get(Type::getInt32Ty(*Context), Align));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000190}
191
Chris Lattnerbf796322009-12-02 06:05:42 +0000192/// EmitMemMove - Emit a call to the memmove function to the builder. This
Eric Christopher80bf1d52009-11-21 01:01:30 +0000193/// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
194Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
195 unsigned Align, IRBuilder<> &B) {
196 Module *M = Caller->getParent();
Chris Lattnerbf796322009-12-02 06:05:42 +0000197 const Type *Ty = TD->getIntPtrType(*Context);
198 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
199 Dst = CastToCStr(Dst, B);
200 Src = CastToCStr(Src, B);
Eric Christopher80bf1d52009-11-21 01:01:30 +0000201 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
Chris Lattnerbf796322009-12-02 06:05:42 +0000202 return B.CreateCall4(MemMove, Dst, Src, Len, A);
Eric Christopher80bf1d52009-11-21 01:01:30 +0000203}
204
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000205/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
206/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
207Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000208 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000209 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000210 AttributeWithIndex AWI;
211 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
212
213 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
Eric Christopher37c8b862009-10-07 21:14:25 +0000214 Type::getInt8PtrTy(*Context),
215 Type::getInt8PtrTy(*Context),
216 Type::getInt32Ty(*Context),
217 TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000218 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000219 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
220
221 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
222 CI->setCallingConv(F->getCallingConv());
223
224 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000225}
226
Nick Lewycky13a09e22008-12-21 00:19:21 +0000227/// EmitMemCmp - Emit a call to the memcmp function.
228Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
229 Value *Len, IRBuilder<> &B) {
230 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000231 AttributeWithIndex AWI[3];
232 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
233 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
234 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
235 Attribute::NoUnwind);
236
237 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
Owen Anderson1d0be152009-08-13 21:58:54 +0000238 Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000239 Type::getInt8PtrTy(*Context),
240 Type::getInt8PtrTy(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +0000241 TD->getIntPtrType(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000242 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
243 Len, "memcmp");
244
245 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
246 CI->setCallingConv(F->getCallingConv());
247
248 return CI;
Nick Lewycky13a09e22008-12-21 00:19:21 +0000249}
250
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000251/// EmitMemSet - Emit a call to the memset function
252Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
253 Value *Len, IRBuilder<> &B) {
254 Module *M = Caller->getParent();
255 Intrinsic::ID IID = Intrinsic::memset;
256 const Type *Tys[1];
257 Tys[0] = Len->getType();
258 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
Owen Anderson1d0be152009-08-13 21:58:54 +0000259 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000260 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
261}
262
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000263/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
264/// 'floor'). This function is known to take a single of type matching 'Op' and
265/// returns one value with the same type. If 'Op' is a long double, 'l' is
266/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
267Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Dan Gohman79cb8402009-09-25 23:10:17 +0000268 IRBuilder<> &B,
269 const AttrListPtr &Attrs) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000270 char NameBuffer[20];
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000271 if (!Op->getType()->isDoubleTy()) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000272 // If we need to add a suffix, copy into NameBuffer.
273 unsigned NameLen = strlen(Name);
274 assert(NameLen < sizeof(NameBuffer)-2);
275 memcpy(NameBuffer, Name, NameLen);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000276 if (Op->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000277 NameBuffer[NameLen] = 'f'; // floorf
278 else
279 NameBuffer[NameLen] = 'l'; // floorl
280 NameBuffer[NameLen+1] = 0;
281 Name = NameBuffer;
282 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000283
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000284 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000285 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000286 Op->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000287 CallInst *CI = B.CreateCall(Callee, Op, Name);
Dan Gohman79cb8402009-09-25 23:10:17 +0000288 CI->setAttributes(Attrs);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000289 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
290 CI->setCallingConv(F->getCallingConv());
291
292 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000293}
294
295/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
296/// is an integer.
Chris Lattner74965f22009-11-09 04:57:04 +0000297Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000298 Module *M = Caller->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000299 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
300 Type::getInt32Ty(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000301 CallInst *CI = B.CreateCall(PutChar,
Eric Christopher37c8b862009-10-07 21:14:25 +0000302 B.CreateIntCast(Char,
303 Type::getInt32Ty(*Context),
Duncan Sandsf63c4102009-11-16 12:32:28 +0000304 /*isSigned*/true,
Eric Christopher37c8b862009-10-07 21:14:25 +0000305 "chari"),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000306 "putchar");
307
308 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
309 CI->setCallingConv(F->getCallingConv());
Chris Lattner74965f22009-11-09 04:57:04 +0000310 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000311}
312
313/// EmitPutS - Emit a call to the puts function. This assumes that Str is
314/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000315void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000316 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000317 AttributeWithIndex AWI[2];
318 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
319 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
320
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000321 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
Owen Anderson1d0be152009-08-13 21:58:54 +0000322 Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000323 Type::getInt8PtrTy(*Context),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000324 NULL);
325 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
326 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
327 CI->setCallingConv(F->getCallingConv());
328
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000329}
330
331/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
332/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000333void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000334 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000335 AttributeWithIndex AWI[2];
336 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
337 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
338 Constant *F;
339 if (isa<PointerType>(File->getType()))
Eric Christopher37c8b862009-10-07 21:14:25 +0000340 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
341 Type::getInt32Ty(*Context),
342 Type::getInt32Ty(*Context), File->getType(),
343 NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000344 else
Eric Christopher37c8b862009-10-07 21:14:25 +0000345 F = M->getOrInsertFunction("fputc",
346 Type::getInt32Ty(*Context),
347 Type::getInt32Ty(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000348 File->getType(), NULL);
Duncan Sandsf63c4102009-11-16 12:32:28 +0000349 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
350 "chari");
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000351 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
352
353 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
354 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000355}
356
357/// EmitFPutS - Emit a call to the puts function. Str is required to be a
358/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000359void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000360 Module *M = Caller->getParent();
Nick Lewycky225f7472009-02-15 22:47:25 +0000361 AttributeWithIndex AWI[3];
362 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
363 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
364 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000365 Constant *F;
366 if (isa<PointerType>(File->getType()))
Eric Christopher37c8b862009-10-07 21:14:25 +0000367 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
368 Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000369 Type::getInt8PtrTy(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000370 File->getType(), NULL);
371 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000372 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000373 Type::getInt8PtrTy(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000374 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000375 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
376
377 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
378 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000379}
380
381/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
382/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
383void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000384 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000385 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000386 AttributeWithIndex AWI[3];
387 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
388 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
389 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
390 Constant *F;
391 if (isa<PointerType>(File->getType()))
392 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
Owen Anderson1d0be152009-08-13 21:58:54 +0000393 TD->getIntPtrType(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000394 Type::getInt8PtrTy(*Context),
Eric Christopher37c8b862009-10-07 21:14:25 +0000395 TD->getIntPtrType(*Context),
396 TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000397 File->getType(), NULL);
398 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000399 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000400 Type::getInt8PtrTy(*Context),
Eric Christopher37c8b862009-10-07 21:14:25 +0000401 TD->getIntPtrType(*Context),
402 TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000403 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000404 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Anderson1d0be152009-08-13 21:58:54 +0000405 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000406
407 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
408 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000409}
410
411//===----------------------------------------------------------------------===//
412// Helper Functions
413//===----------------------------------------------------------------------===//
414
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000415/// GetStringLengthH - If we can compute the length of the string pointed to by
416/// the specified pointer, return 'len+1'. If we can't, return 0.
417static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
418 // Look through noop bitcast instructions.
419 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
420 return GetStringLengthH(BCI->getOperand(0), PHIs);
Eric Christopher37c8b862009-10-07 21:14:25 +0000421
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000422 // If this is a PHI node, there are two cases: either we have already seen it
423 // or we haven't.
424 if (PHINode *PN = dyn_cast<PHINode>(V)) {
425 if (!PHIs.insert(PN))
426 return ~0ULL; // already in the set.
Eric Christopher37c8b862009-10-07 21:14:25 +0000427
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000428 // If it was new, see if all the input strings are the same length.
429 uint64_t LenSoFar = ~0ULL;
430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
431 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
432 if (Len == 0) return 0; // Unknown length -> unknown.
Eric Christopher37c8b862009-10-07 21:14:25 +0000433
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000434 if (Len == ~0ULL) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000435
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000436 if (Len != LenSoFar && LenSoFar != ~0ULL)
437 return 0; // Disagree -> unknown.
438 LenSoFar = Len;
439 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000440
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000441 // Success, all agree.
442 return LenSoFar;
443 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000444
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000445 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
446 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
447 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
448 if (Len1 == 0) return 0;
449 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
450 if (Len2 == 0) return 0;
451 if (Len1 == ~0ULL) return Len2;
452 if (Len2 == ~0ULL) return Len1;
453 if (Len1 != Len2) return 0;
454 return Len1;
455 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000456
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000457 // If the value is not a GEP instruction nor a constant expression with a
458 // GEP instruction, then return unknown.
459 User *GEP = 0;
460 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
461 GEP = GEPI;
462 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
463 if (CE->getOpcode() != Instruction::GetElementPtr)
464 return 0;
465 GEP = CE;
466 } else {
467 return 0;
468 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000469
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000470 // Make sure the GEP has exactly three arguments.
471 if (GEP->getNumOperands() != 3)
472 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000473
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000474 // Check to make sure that the first operand of the GEP is an integer and
475 // has value 0 so that we are sure we're indexing into the initializer.
476 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
477 if (!Idx->isZero())
478 return 0;
479 } else
480 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000481
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000482 // If the second index isn't a ConstantInt, then this is a variable index
483 // into the array. If this occurs, we can't say anything meaningful about
484 // the string.
485 uint64_t StartIdx = 0;
486 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
487 StartIdx = CI->getZExtValue();
488 else
489 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000490
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000491 // The GEP instruction, constant or instruction, must reference a global
492 // variable that is a constant and is initialized. The referenced constant
493 // initializer is the array that we'll use for optimization.
494 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman107f41f2009-08-19 00:11:12 +0000495 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
496 GV->mayBeOverridden())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000497 return 0;
498 Constant *GlobalInit = GV->getInitializer();
Eric Christopher37c8b862009-10-07 21:14:25 +0000499
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000500 // Handle the ConstantAggregateZero case, which is a degenerate case. The
501 // initializer is constant zero so the length of the string must be zero.
502 if (isa<ConstantAggregateZero>(GlobalInit))
503 return 1; // Len = 0 offset by 1.
Eric Christopher37c8b862009-10-07 21:14:25 +0000504
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000505 // Must be a Constant Array
506 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Owen Anderson1d0be152009-08-13 21:58:54 +0000507 if (!Array ||
508 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000509 return false;
Eric Christopher37c8b862009-10-07 21:14:25 +0000510
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000511 // Get the number of elements in the array
512 uint64_t NumElts = Array->getType()->getNumElements();
Eric Christopher37c8b862009-10-07 21:14:25 +0000513
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000514 // Traverse the constant array from StartIdx (derived above) which is
515 // the place the GEP refers to in the array.
516 for (unsigned i = StartIdx; i != NumElts; ++i) {
517 Constant *Elt = Array->getOperand(i);
518 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
519 if (!CI) // This array isn't suitable, non-int initializer.
520 return 0;
521 if (CI->isZero())
522 return i-StartIdx+1; // We found end of string, success!
523 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000524
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000525 return 0; // The array isn't null terminated, conservatively return 'unknown'.
526}
527
528/// GetStringLength - If we can compute the length of the string pointed to by
529/// the specified pointer, return 'len+1'. If we can't, return 0.
530static uint64_t GetStringLength(Value *V) {
531 if (!isa<PointerType>(V->getType())) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000532
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000533 SmallPtrSet<PHINode*, 32> PHIs;
534 uint64_t Len = GetStringLengthH(V, PHIs);
535 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
536 // an empty string as a length.
537 return Len == ~0ULL ? 1 : Len;
538}
539
540/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +0000541/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000542static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
543 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
544 UI != E; ++UI) {
545 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
546 if (IC->isEquality())
547 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
548 if (C->isNullValue())
549 continue;
550 // Unknown instruction.
551 return false;
552 }
553 return true;
554}
555
556//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000557// String and Memory LibCall Optimizations
558//===----------------------------------------------------------------------===//
559
560//===---------------------------------------===//
561// 'strcat' Optimizations
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000562namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000563struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000565 // Verify the "strcat" function prototype.
566 const FunctionType *FT = Callee->getFunctionType();
567 if (FT->getNumParams() != 2 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000568 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000569 FT->getParamType(0) != FT->getReturnType() ||
570 FT->getParamType(1) != FT->getReturnType())
571 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000572
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000573 // Extract some information from the instruction
574 Value *Dst = CI->getOperand(1);
575 Value *Src = CI->getOperand(2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000576
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000577 // See if we can get the length of the input string.
578 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000579 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000580 --Len; // Unbias length.
Eric Christopher37c8b862009-10-07 21:14:25 +0000581
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000582 // Handle the simple, do-nothing case: strcat(x, "") -> x
583 if (Len == 0)
584 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000585
586 // These optimizations require TargetData.
587 if (!TD) return 0;
588
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000589 EmitStrLenMemCpy(Src, Dst, Len, B);
590 return Dst;
591 }
592
593 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000594 // We need to find the end of the destination string. That's where the
595 // memory is to be moved to. We just generate a call to strlen.
596 Value *DstLen = EmitStrLen(Dst, B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000597
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000598 // Now that we have the destination's length, we must index into the
599 // destination's pointer to get the actual memcpy destination (end of
600 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000601 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000602
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000603 // We have enough information to now generate the memcpy call to do the
604 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000605 EmitMemCpy(CpyDst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000606 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000607 }
608};
609
610//===---------------------------------------===//
611// 'strncat' Optimizations
612
Chris Lattner3e8b6632009-09-02 06:11:42 +0000613struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000614 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
615 // Verify the "strncat" function prototype.
616 const FunctionType *FT = Callee->getFunctionType();
617 if (FT->getNumParams() != 3 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000618 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000619 FT->getParamType(0) != FT->getReturnType() ||
620 FT->getParamType(1) != FT->getReturnType() ||
621 !isa<IntegerType>(FT->getParamType(2)))
622 return 0;
623
624 // Extract some information from the instruction
625 Value *Dst = CI->getOperand(1);
626 Value *Src = CI->getOperand(2);
627 uint64_t Len;
628
629 // We don't do anything if length is not constant
630 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
631 Len = LengthArg->getZExtValue();
632 else
633 return 0;
634
635 // See if we can get the length of the input string.
636 uint64_t SrcLen = GetStringLength(Src);
637 if (SrcLen == 0) return 0;
638 --SrcLen; // Unbias length.
639
640 // Handle the simple, do-nothing cases:
641 // strncat(x, "", c) -> x
642 // strncat(x, c, 0) -> x
643 if (SrcLen == 0 || Len == 0) return Dst;
644
Dan Gohmanf14d9192009-08-18 00:48:13 +0000645 // These optimizations require TargetData.
646 if (!TD) return 0;
647
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000648 // We don't optimize this case
649 if (Len < SrcLen) return 0;
650
651 // strncat(x, s, c) -> strcat(x, s)
652 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000653 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000654 return Dst;
655 }
656};
657
658//===---------------------------------------===//
659// 'strchr' Optimizations
660
Chris Lattner3e8b6632009-09-02 06:11:42 +0000661struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000662 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000663 // Verify the "strchr" function prototype.
664 const FunctionType *FT = Callee->getFunctionType();
665 if (FT->getNumParams() != 2 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000666 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000667 FT->getParamType(0) != FT->getReturnType())
668 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000669
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000670 Value *SrcStr = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000671
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000672 // If the second operand is non-constant, see if we can compute the length
673 // of the input string and turn this into memchr.
674 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
675 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000676 // These optimizations require TargetData.
677 if (!TD) return 0;
678
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000679 uint64_t Len = GetStringLength(SrcStr);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000680 if (Len == 0 ||
681 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000682 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000683
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000684 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Anderson1d0be152009-08-13 21:58:54 +0000685 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000686 }
687
688 // Otherwise, the character is a constant, see if the first argument is
689 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000690 std::string Str;
691 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000692 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000693
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000694 // strchr can find the nul character.
695 Str += '\0';
696 char CharValue = CharC->getSExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +0000697
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000698 // Compute the offset.
699 uint64_t i = 0;
700 while (1) {
701 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersona7235ea2009-07-31 20:28:14 +0000702 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000703 // Did we find our match?
704 if (Str[i] == CharValue)
705 break;
706 ++i;
707 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000708
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000709 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Anderson1d0be152009-08-13 21:58:54 +0000710 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000711 return B.CreateGEP(SrcStr, Idx, "strchr");
712 }
713};
714
715//===---------------------------------------===//
716// 'strcmp' Optimizations
717
Chris Lattner3e8b6632009-09-02 06:11:42 +0000718struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000719 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000720 // Verify the "strcmp" function prototype.
721 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000722 if (FT->getNumParams() != 2 ||
723 FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000724 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000725 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000726 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000727
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000728 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
729 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000730 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000731
Bill Wendling0582ae92009-03-13 04:39:26 +0000732 std::string Str1, Str2;
733 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
734 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000735
Bill Wendling0582ae92009-03-13 04:39:26 +0000736 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000737 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000738
Bill Wendling0582ae92009-03-13 04:39:26 +0000739 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000740 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000741
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000742 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000743 if (HasStr1 && HasStr2)
Eric Christopher37c8b862009-10-07 21:14:25 +0000744 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000745 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000746
747 // strcmp(P, "x") -> memcmp(P, "x", 2)
748 uint64_t Len1 = GetStringLength(Str1P);
749 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000750 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000751 // These optimizations require TargetData.
752 if (!TD) return 0;
753
Nick Lewycky13a09e22008-12-21 00:19:21 +0000754 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000755 ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattner849832c2009-06-19 04:17:36 +0000756 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000757 }
758
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000759 return 0;
760 }
761};
762
763//===---------------------------------------===//
764// 'strncmp' Optimizations
765
Chris Lattner3e8b6632009-09-02 06:11:42 +0000766struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000767 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000768 // Verify the "strncmp" function prototype.
769 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000770 if (FT->getNumParams() != 3 ||
771 FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000772 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000773 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000774 !isa<IntegerType>(FT->getParamType(2)))
775 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000776
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000777 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
778 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000779 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000780
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000781 // Get the length argument if it is constant.
782 uint64_t Length;
783 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
784 Length = LengthArg->getZExtValue();
785 else
786 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000787
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000788 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000789 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000790
Bill Wendling0582ae92009-03-13 04:39:26 +0000791 std::string Str1, Str2;
792 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
793 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000794
Bill Wendling0582ae92009-03-13 04:39:26 +0000795 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000796 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000797
Bill Wendling0582ae92009-03-13 04:39:26 +0000798 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000799 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000800
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000801 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000802 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000803 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000804 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000805 return 0;
806 }
807};
808
809
810//===---------------------------------------===//
811// 'strcpy' Optimizations
812
Chris Lattner3e8b6632009-09-02 06:11:42 +0000813struct StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000814 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000815 // Verify the "strcpy" function prototype.
816 const FunctionType *FT = Callee->getFunctionType();
817 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
818 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000819 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000820 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000821
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000822 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
823 if (Dst == Src) // strcpy(x,x) -> x
824 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000825
Dan Gohmanf14d9192009-08-18 00:48:13 +0000826 // These optimizations require TargetData.
827 if (!TD) return 0;
828
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000829 // See if we can get the length of the input string.
830 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000831 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000832
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000833 // We have enough information to now generate the memcpy call to do the
834 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000835 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000836 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000837 return Dst;
838 }
839};
840
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000841//===---------------------------------------===//
842// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000843
Chris Lattner3e8b6632009-09-02 06:11:42 +0000844struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000845 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
846 const FunctionType *FT = Callee->getFunctionType();
847 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
848 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000849 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000850 !isa<IntegerType>(FT->getParamType(2)))
851 return 0;
852
853 Value *Dst = CI->getOperand(1);
854 Value *Src = CI->getOperand(2);
855 Value *LenOp = CI->getOperand(3);
856
857 // See if we can get the length of the input string.
858 uint64_t SrcLen = GetStringLength(Src);
859 if (SrcLen == 0) return 0;
860 --SrcLen;
861
862 if (SrcLen == 0) {
863 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Eric Christopher37c8b862009-10-07 21:14:25 +0000864 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
865 B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000866 return Dst;
867 }
868
869 uint64_t Len;
870 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
871 Len = LengthArg->getZExtValue();
872 else
873 return 0;
874
875 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
876
Dan Gohmanf14d9192009-08-18 00:48:13 +0000877 // These optimizations require TargetData.
878 if (!TD) return 0;
879
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000880 // Let strncpy handle the zero padding
881 if (Len > SrcLen+1) return 0;
882
883 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000884 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000885 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000886
887 return Dst;
888 }
889};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000890
891//===---------------------------------------===//
892// 'strlen' Optimizations
893
Chris Lattner3e8b6632009-09-02 06:11:42 +0000894struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000895 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000896 const FunctionType *FT = Callee->getFunctionType();
897 if (FT->getNumParams() != 1 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000898 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000899 !isa<IntegerType>(FT->getReturnType()))
900 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000901
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000902 Value *Src = CI->getOperand(1);
903
904 // Constant folding: strlen("xyz") -> 3
905 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000906 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000907
908 // Handle strlen(p) != 0.
909 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
910
911 // strlen(x) != 0 --> *x != 0
912 // strlen(x) == 0 --> *x == 0
913 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
914 }
915};
916
917//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000918// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000919
Chris Lattner3e8b6632009-09-02 06:11:42 +0000920struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000921 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
922 const FunctionType *FT = Callee->getFunctionType();
923 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
924 !isa<PointerType>(FT->getParamType(0)) ||
925 !isa<PointerType>(FT->getParamType(1)))
926 return 0;
927
928 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000929 if (isa<ConstantPointerNull>(EndPtr)) {
930 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000931 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000932 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000933
934 return 0;
935 }
936};
937
Chris Lattner24604112009-12-16 09:32:05 +0000938//===---------------------------------------===//
939// 'strstr' Optimizations
940
941struct StrStrOpt : public LibCallOptimization {
942 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
943 const FunctionType *FT = Callee->getFunctionType();
944 if (FT->getNumParams() != 2 ||
945 !isa<PointerType>(FT->getParamType(0)) ||
946 !isa<PointerType>(FT->getParamType(1)) ||
947 !isa<PointerType>(FT->getReturnType()))
948 return 0;
949
950 // fold strstr(x, x) -> x.
951 if (CI->getOperand(1) == CI->getOperand(2))
952 return B.CreateBitCast(CI->getOperand(1), CI->getType());
953
954 // See if either input string is a constant string.
955 std::string SearchStr, ToFindStr;
956 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
957 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
958
959 // fold strstr(x, "") -> x.
960 if (HasStr2 && ToFindStr.empty())
961 return B.CreateBitCast(CI->getOperand(1), CI->getType());
962
963 // If both strings are known, constant fold it.
964 if (HasStr1 && HasStr2) {
965 std::string::size_type Offset = SearchStr.find(ToFindStr);
966
967 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
968 return Constant::getNullValue(CI->getType());
969
970 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
971 Value *Result = CastToCStr(CI->getOperand(1), B);
972 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
973 return B.CreateBitCast(Result, CI->getType());
974 }
975
976 // fold strstr(x, "y") -> strchr(x, 'y').
977 if (HasStr2 && ToFindStr.size() == 1)
978 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
979 CI->getType());
980 return 0;
981 }
982};
983
Nick Lewycky4c498412009-02-13 15:31:46 +0000984
985//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000986// 'memcmp' Optimizations
987
Chris Lattner3e8b6632009-09-02 06:11:42 +0000988struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000989 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000990 const FunctionType *FT = Callee->getFunctionType();
991 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
992 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000993 FT->getReturnType() != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000994 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000995
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000996 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000997
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000998 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000999 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001000
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001001 // Make sure we have a constant length.
1002 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001003 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001004 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001005
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001006 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001007 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001008
1009 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1010 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1011 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +00001012 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001013 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001014
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001015 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
1016 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
1017 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Owen Andersondebcb012009-07-29 22:17:13 +00001018 const Type *PTy = PointerType::getUnqual(Len == 2 ?
Owen Anderson1d0be152009-08-13 21:58:54 +00001019 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001020 LHS = B.CreateBitCast(LHS, PTy, "tmp");
1021 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001022 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
1023 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
1024 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
1025 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
1026 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001027
Benjamin Kramer992a6372009-11-05 17:44:22 +00001028 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1029 std::string LHSStr, RHSStr;
1030 if (GetConstantStringInfo(LHS, LHSStr) &&
1031 GetConstantStringInfo(RHS, RHSStr)) {
1032 // Make sure we're not reading out-of-bounds memory.
1033 if (Len > LHSStr.length() || Len > RHSStr.length())
1034 return 0;
1035 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1036 return ConstantInt::get(CI->getType(), Ret);
1037 }
1038
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001039 return 0;
1040 }
1041};
1042
1043//===---------------------------------------===//
1044// 'memcpy' Optimizations
1045
Chris Lattner3e8b6632009-09-02 06:11:42 +00001046struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001047 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001048 // These optimizations require TargetData.
1049 if (!TD) return 0;
1050
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001051 const FunctionType *FT = Callee->getFunctionType();
1052 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1053 !isa<PointerType>(FT->getParamType(0)) ||
1054 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001055 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001056 return 0;
1057
1058 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1059 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1060 return CI->getOperand(1);
1061 }
1062};
1063
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001064//===---------------------------------------===//
1065// 'memmove' Optimizations
1066
Chris Lattner3e8b6632009-09-02 06:11:42 +00001067struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001068 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001069 // These optimizations require TargetData.
1070 if (!TD) return 0;
1071
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001072 const FunctionType *FT = Callee->getFunctionType();
1073 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1074 !isa<PointerType>(FT->getParamType(0)) ||
1075 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001076 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001077 return 0;
1078
1079 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Eric Christopher80bf1d52009-11-21 01:01:30 +00001080 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001081 return CI->getOperand(1);
1082 }
1083};
1084
1085//===---------------------------------------===//
1086// 'memset' Optimizations
1087
Chris Lattner3e8b6632009-09-02 06:11:42 +00001088struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001089 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001090 // These optimizations require TargetData.
1091 if (!TD) return 0;
1092
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001093 const FunctionType *FT = Callee->getFunctionType();
1094 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1095 !isa<PointerType>(FT->getParamType(0)) ||
Eli Friedman62bb4132009-07-18 08:34:51 +00001096 !isa<IntegerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001097 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001098 return 0;
1099
1100 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Eric Christopher37c8b862009-10-07 21:14:25 +00001101 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1102 false);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001103 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001104 return CI->getOperand(1);
1105 }
1106};
1107
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001108//===----------------------------------------------------------------------===//
Eric Christopher80bf1d52009-11-21 01:01:30 +00001109// Object Size Checking Optimizations
1110//===----------------------------------------------------------------------===//
1111
1112//===---------------------------------------===//
1113// 'object size'
1114namespace {
1115struct SizeOpt : public LibCallOptimization {
1116 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1117 // TODO: We can do more with this, but delaying to here should be no change
1118 // in behavior.
1119 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1120
1121 if (!Const) return 0;
1122
1123 const Type *Ty = Callee->getFunctionType()->getReturnType();
1124
1125 if (Const->getZExtValue() < 2)
1126 return Constant::getAllOnesValue(Ty);
1127 else
1128 return ConstantInt::get(Ty, 0);
1129 }
1130};
1131}
1132
1133//===---------------------------------------===//
1134// 'memcpy_chk' Optimizations
1135
1136struct MemCpyChkOpt : public LibCallOptimization {
1137 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1138 // These optimizations require TargetData.
1139 if (!TD) return 0;
1140
1141 const FunctionType *FT = Callee->getFunctionType();
1142 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1143 !isa<PointerType>(FT->getParamType(0)) ||
1144 !isa<PointerType>(FT->getParamType(1)) ||
Eric Christopherf734be22009-12-22 01:23:51 +00001145 !isa<IntegerType>(FT->getParamType(3)) ||
1146 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eric Christopher80bf1d52009-11-21 01:01:30 +00001147 return 0;
1148
1149 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1150 if (!SizeCI)
1151 return 0;
1152 if (SizeCI->isAllOnesValue()) {
1153 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1154 return CI->getOperand(1);
1155 }
1156
1157 return 0;
1158 }
1159};
1160
1161//===---------------------------------------===//
1162// 'memset_chk' Optimizations
1163
1164struct MemSetChkOpt : public LibCallOptimization {
1165 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1166 // These optimizations require TargetData.
1167 if (!TD) return 0;
1168
1169 const FunctionType *FT = Callee->getFunctionType();
1170 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1171 !isa<PointerType>(FT->getParamType(0)) ||
1172 !isa<IntegerType>(FT->getParamType(1)) ||
Eric Christopherf734be22009-12-22 01:23:51 +00001173 !isa<IntegerType>(FT->getParamType(3)) ||
Eric Christopher80bf1d52009-11-21 01:01:30 +00001174 FT->getParamType(2) != TD->getIntPtrType(*Context))
1175 return 0;
1176
1177 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1178 if (!SizeCI)
1179 return 0;
1180 if (SizeCI->isAllOnesValue()) {
1181 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1182 false);
1183 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1184 return CI->getOperand(1);
1185 }
1186
1187 return 0;
1188 }
1189};
1190
1191//===---------------------------------------===//
1192// 'memmove_chk' Optimizations
1193
1194struct MemMoveChkOpt : public LibCallOptimization {
1195 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1196 // These optimizations require TargetData.
1197 if (!TD) return 0;
1198
1199 const FunctionType *FT = Callee->getFunctionType();
1200 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1201 !isa<PointerType>(FT->getParamType(0)) ||
1202 !isa<PointerType>(FT->getParamType(1)) ||
Eric Christopherf734be22009-12-22 01:23:51 +00001203 !isa<IntegerType>(FT->getParamType(3)) ||
Eric Christopher80bf1d52009-11-21 01:01:30 +00001204 FT->getParamType(2) != TD->getIntPtrType(*Context))
1205 return 0;
1206
1207 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1208 if (!SizeCI)
1209 return 0;
1210 if (SizeCI->isAllOnesValue()) {
1211 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1212 1, B);
1213 return CI->getOperand(1);
1214 }
1215
1216 return 0;
1217 }
1218};
1219
1220//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221// Math Library Optimizations
1222//===----------------------------------------------------------------------===//
1223
1224//===---------------------------------------===//
1225// 'pow*' Optimizations
1226
Chris Lattner3e8b6632009-09-02 06:11:42 +00001227struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001228 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001229 const FunctionType *FT = Callee->getFunctionType();
1230 // Just make sure this has 2 arguments of the same FP type, which match the
1231 // result type.
1232 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1233 FT->getParamType(0) != FT->getParamType(1) ||
1234 !FT->getParamType(0)->isFloatingPoint())
1235 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001236
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001237 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1238 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1239 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1240 return Op1C;
1241 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +00001242 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001243 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001244
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001245 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1246 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001247
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001248 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001249 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001250
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001251 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +00001252 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1253 // This is faster than calling pow, and still handles negative zero
1254 // and negative infinite correctly.
1255 // TODO: In fast-math mode, this could be just sqrt(x).
1256 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +00001257 Value *Inf = ConstantFP::getInfinity(CI->getType());
1258 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +00001259 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1260 Callee->getAttributes());
1261 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1262 Callee->getAttributes());
Dan Gohman79cb8402009-09-25 23:10:17 +00001263 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1264 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1265 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001266 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001267
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001268 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1269 return Op1;
1270 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001271 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001272 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001273 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001274 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001275 return 0;
1276 }
1277};
1278
1279//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001280// 'exp2' Optimizations
1281
Chris Lattner3e8b6632009-09-02 06:11:42 +00001282struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001284 const FunctionType *FT = Callee->getFunctionType();
1285 // Just make sure this has 1 argument of FP type, which matches the
1286 // result type.
1287 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1288 !FT->getParamType(0)->isFloatingPoint())
1289 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001290
Chris Lattnere818f772008-05-02 18:43:35 +00001291 Value *Op = CI->getOperand(1);
1292 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1293 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1294 Value *LdExpArg = 0;
1295 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1296 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Eric Christopher37c8b862009-10-07 21:14:25 +00001297 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1298 Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001299 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1300 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Eric Christopher37c8b862009-10-07 21:14:25 +00001301 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1302 Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001303 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001304
Chris Lattnere818f772008-05-02 18:43:35 +00001305 if (LdExpArg) {
1306 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001307 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001308 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001309 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001310 Name = "ldexp";
1311 else
1312 Name = "ldexpl";
1313
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001314 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001315 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001316 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001317
1318 Module *M = Caller->getParent();
1319 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +00001320 Op->getType(),
1321 Type::getInt32Ty(*Context),NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001322 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1323 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1324 CI->setCallingConv(F->getCallingConv());
1325
1326 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001327 }
1328 return 0;
1329 }
1330};
Chris Lattnere818f772008-05-02 18:43:35 +00001331
1332//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001333// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1334
Chris Lattner3e8b6632009-09-02 06:11:42 +00001335struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001336 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001337 const FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001338 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1339 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001340 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001341
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001342 // If this is something like 'floor((double)floatval)', convert to floorf.
1343 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001344 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001345 return 0;
1346
1347 // floor((double)floatval) -> (double)floorf(floatval)
1348 Value *V = Cast->getOperand(0);
Dan Gohman76926b62009-09-26 18:10:13 +00001349 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1350 Callee->getAttributes());
Owen Anderson1d0be152009-08-13 21:58:54 +00001351 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001352 }
1353};
1354
1355//===----------------------------------------------------------------------===//
1356// Integer Optimizations
1357//===----------------------------------------------------------------------===//
1358
1359//===---------------------------------------===//
1360// 'ffs*' Optimizations
1361
Chris Lattner3e8b6632009-09-02 06:11:42 +00001362struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001363 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001364 const FunctionType *FT = Callee->getFunctionType();
1365 // Just make sure this has 2 arguments of the same FP type, which match the
1366 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001367 if (FT->getNumParams() != 1 ||
1368 FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001369 !isa<IntegerType>(FT->getParamType(0)))
1370 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001371
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001372 Value *Op = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001373
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001374 // Constant fold.
1375 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1376 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001377 return Constant::getNullValue(CI->getType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001378 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001379 CI->getValue().countTrailingZeros()+1);
1380 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001381
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001382 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1383 const Type *ArgType = Op->getType();
1384 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1385 Intrinsic::cttz, &ArgType, 1);
1386 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +00001387 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001388 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001389
Owen Andersona7235ea2009-07-31 20:28:14 +00001390 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001391 return B.CreateSelect(Cond, V,
1392 ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001393 }
1394};
1395
1396//===---------------------------------------===//
1397// 'isdigit' Optimizations
1398
Chris Lattner3e8b6632009-09-02 06:11:42 +00001399struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001400 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001401 const FunctionType *FT = Callee->getFunctionType();
1402 // We require integer(i32)
1403 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001404 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001405 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001406
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001407 // isdigit(c) -> (c-'0') <u 10
1408 Value *Op = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001409 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001410 "isdigittmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001411 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001412 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001413 return B.CreateZExt(Op, CI->getType());
1414 }
1415};
1416
1417//===---------------------------------------===//
1418// 'isascii' Optimizations
1419
Chris Lattner3e8b6632009-09-02 06:11:42 +00001420struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001421 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001422 const FunctionType *FT = Callee->getFunctionType();
1423 // We require integer(i32)
1424 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001425 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001426 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001427
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001428 // isascii(c) -> c <u 128
1429 Value *Op = CI->getOperand(1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001430 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001431 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001432 return B.CreateZExt(Op, CI->getType());
1433 }
1434};
Eric Christopher37c8b862009-10-07 21:14:25 +00001435
Chris Lattner313f0e62008-06-09 08:26:51 +00001436//===---------------------------------------===//
1437// 'abs', 'labs', 'llabs' Optimizations
1438
Chris Lattner3e8b6632009-09-02 06:11:42 +00001439struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001440 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001441 const FunctionType *FT = Callee->getFunctionType();
1442 // We require integer(integer) where the types agree.
1443 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1444 FT->getParamType(0) != FT->getReturnType())
1445 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001446
Chris Lattner313f0e62008-06-09 08:26:51 +00001447 // abs(x) -> x >s -1 ? x : -x
1448 Value *Op = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001449 Value *Pos = B.CreateICmpSGT(Op,
Owen Andersona7235ea2009-07-31 20:28:14 +00001450 Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001451 "ispos");
1452 Value *Neg = B.CreateNeg(Op, "neg");
1453 return B.CreateSelect(Pos, Op, Neg);
1454 }
1455};
Eric Christopher37c8b862009-10-07 21:14:25 +00001456
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001457
1458//===---------------------------------------===//
1459// 'toascii' Optimizations
1460
Chris Lattner3e8b6632009-09-02 06:11:42 +00001461struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001462 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001463 const FunctionType *FT = Callee->getFunctionType();
1464 // We require i32(i32)
1465 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001466 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001467 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001468
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001469 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001470 return B.CreateAnd(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001471 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001472 }
1473};
1474
1475//===----------------------------------------------------------------------===//
1476// Formatting and IO Optimizations
1477//===----------------------------------------------------------------------===//
1478
1479//===---------------------------------------===//
1480// 'printf' Optimizations
1481
Chris Lattner3e8b6632009-09-02 06:11:42 +00001482struct PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001483 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001484 // Require one fixed pointer argument and an integer/void result.
1485 const FunctionType *FT = Callee->getFunctionType();
1486 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1487 !(isa<IntegerType>(FT->getReturnType()) ||
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001488 FT->getReturnType()->isVoidTy()))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001489 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001490
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001491 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001492 std::string FormatStr;
1493 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1494 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001495
1496 // Empty format string -> noop.
1497 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001498 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001499 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001500
Chris Lattner74965f22009-11-09 04:57:04 +00001501 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1502 // in case there is an error writing to stdout.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001503 if (FormatStr.size() == 1) {
Chris Lattner74965f22009-11-09 04:57:04 +00001504 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1505 FormatStr[0]), B);
1506 if (CI->use_empty()) return CI;
1507 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001508 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001509
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001510 // printf("foo\n") --> puts("foo")
1511 if (FormatStr[FormatStr.size()-1] == '\n' &&
1512 FormatStr.find('%') == std::string::npos) { // no format characters.
1513 // Create a string literal with no \n on it. We expect the constant merge
1514 // pass to be run after this pass, to merge duplicate strings.
1515 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001516 Constant *C = ConstantArray::get(*Context, FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001517 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1518 GlobalVariable::InternalLinkage, C, "str");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001519 EmitPutS(C, B);
Eric Christopher37c8b862009-10-07 21:14:25 +00001520 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001521 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001522 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001523
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001524 // Optimize specific format strings.
1525 // printf("%c", chr) --> putchar(*(i8*)dst)
1526 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1527 isa<IntegerType>(CI->getOperand(2)->getType())) {
Chris Lattner74965f22009-11-09 04:57:04 +00001528 Value *Res = EmitPutChar(CI->getOperand(2), B);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001529
Chris Lattner74965f22009-11-09 04:57:04 +00001530 if (CI->use_empty()) return CI;
1531 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001532 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001533
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001534 // printf("%s\n", str) --> puts(str)
1535 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1536 isa<PointerType>(CI->getOperand(2)->getType()) &&
1537 CI->use_empty()) {
1538 EmitPutS(CI->getOperand(2), B);
1539 return CI;
1540 }
1541 return 0;
1542 }
1543};
1544
1545//===---------------------------------------===//
1546// 'sprintf' Optimizations
1547
Chris Lattner3e8b6632009-09-02 06:11:42 +00001548struct SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001549 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001550 // Require two fixed pointer arguments and an integer result.
1551 const FunctionType *FT = Callee->getFunctionType();
1552 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1553 !isa<PointerType>(FT->getParamType(1)) ||
1554 !isa<IntegerType>(FT->getReturnType()))
1555 return 0;
1556
1557 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001558 std::string FormatStr;
1559 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1560 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001561
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001562 // If we just have a format string (nothing else crazy) transform it.
1563 if (CI->getNumOperands() == 3) {
1564 // Make sure there's no % in the constant array. We could try to handle
1565 // %% -> % in the future if we cared.
1566 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1567 if (FormatStr[i] == '%')
1568 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001569
1570 // These optimizations require TargetData.
1571 if (!TD) return 0;
1572
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001573 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1574 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Owen Anderson1d0be152009-08-13 21:58:54 +00001575 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001576 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001577 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001578
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001579 // The remaining optimizations require the format string to be "%s" or "%c"
1580 // and have an extra operand.
1581 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1582 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001583
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584 // Decode the second character of the format string.
1585 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001586 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001587 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001588 Value *V = B.CreateTrunc(CI->getOperand(3),
1589 Type::getInt8Ty(*Context), "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001590 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1591 B.CreateStore(V, Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001592 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1593 "nul");
Owen Anderson1d0be152009-08-13 21:58:54 +00001594 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001595
Owen Andersoneed707b2009-07-24 23:12:02 +00001596 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001597 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001598
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001599 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001600 // These optimizations require TargetData.
1601 if (!TD) return 0;
1602
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001603 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1604 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1605
1606 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001607 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001608 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001609 "leninc");
1610 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
Eric Christopher37c8b862009-10-07 21:14:25 +00001611
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001612 // The sprintf result is the unincremented number of bytes in the string.
1613 return B.CreateIntCast(Len, CI->getType(), false);
1614 }
1615 return 0;
1616 }
1617};
1618
1619//===---------------------------------------===//
1620// 'fwrite' Optimizations
1621
Chris Lattner3e8b6632009-09-02 06:11:42 +00001622struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001624 // Require a pointer, an integer, an integer, a pointer, returning integer.
1625 const FunctionType *FT = Callee->getFunctionType();
1626 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1627 !isa<IntegerType>(FT->getParamType(1)) ||
1628 !isa<IntegerType>(FT->getParamType(2)) ||
1629 !isa<PointerType>(FT->getParamType(3)) ||
1630 !isa<IntegerType>(FT->getReturnType()))
1631 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001632
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001633 // Get the element size and count.
1634 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1635 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1636 if (!SizeC || !CountC) return 0;
1637 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001638
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001639 // If this is writing zero records, remove the call (it's a noop).
1640 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001641 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001642
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001643 // If this is writing one byte, turn it into fputc.
1644 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1645 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1646 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001647 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001648 }
1649
1650 return 0;
1651 }
1652};
1653
1654//===---------------------------------------===//
1655// 'fputs' Optimizations
1656
Chris Lattner3e8b6632009-09-02 06:11:42 +00001657struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001658 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001659 // These optimizations require TargetData.
1660 if (!TD) return 0;
1661
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001662 // Require two pointers. Also, we can't optimize if return value is used.
1663 const FunctionType *FT = Callee->getFunctionType();
1664 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1665 !isa<PointerType>(FT->getParamType(1)) ||
1666 !CI->use_empty())
1667 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001668
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001669 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1670 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001671 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001672 EmitFWrite(CI->getOperand(1),
Owen Anderson1d0be152009-08-13 21:58:54 +00001673 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001674 CI->getOperand(2), B);
1675 return CI; // Known to have no uses (see above).
1676 }
1677};
1678
1679//===---------------------------------------===//
1680// 'fprintf' Optimizations
1681
Chris Lattner3e8b6632009-09-02 06:11:42 +00001682struct FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001683 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001684 // Require two fixed paramters as pointers and integer result.
1685 const FunctionType *FT = Callee->getFunctionType();
1686 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1687 !isa<PointerType>(FT->getParamType(1)) ||
1688 !isa<IntegerType>(FT->getReturnType()))
1689 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001690
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001691 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001692 std::string FormatStr;
1693 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1694 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001695
1696 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1697 if (CI->getNumOperands() == 3) {
1698 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1699 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001700 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001701
1702 // These optimizations require TargetData.
1703 if (!TD) return 0;
1704
Owen Anderson1d0be152009-08-13 21:58:54 +00001705 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001706 FormatStr.size()),
1707 CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001708 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001709 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001710
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001711 // The remaining optimizations require the format string to be "%s" or "%c"
1712 // and have an extra operand.
1713 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1714 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001715
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001716 // Decode the second character of the format string.
1717 if (FormatStr[1] == 'c') {
1718 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1719 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1720 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001721 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001722 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001723
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001724 if (FormatStr[1] == 's') {
1725 // fprintf(F, "%s", str) -> fputs(str, F)
1726 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1727 return 0;
1728 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1729 return CI;
1730 }
1731 return 0;
1732 }
1733};
1734
Bill Wendlingac178222008-05-05 21:37:59 +00001735} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001736
1737//===----------------------------------------------------------------------===//
1738// SimplifyLibCalls Pass Implementation
1739//===----------------------------------------------------------------------===//
1740
1741namespace {
1742 /// This pass optimizes well known library functions from libc and libm.
1743 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001744 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001745 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001746 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001747 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1748 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
Chris Lattner24604112009-12-16 09:32:05 +00001749 StrToOpt StrTo; StrStrOpt StrStr;
1750 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001751 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001752 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001753 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001754 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1755 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001756 // Formatting and IO Optimizations
1757 SPrintFOpt SPrintF; PrintFOpt PrintF;
1758 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Eric Christopher80bf1d52009-11-21 01:01:30 +00001759
1760 // Object Size Checking
Eric Christopher7b5e6172009-10-27 00:52:25 +00001761 SizeOpt ObjectSize;
Eric Christopher80bf1d52009-11-21 01:01:30 +00001762 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001763
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001764 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001765 public:
1766 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001767 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001768
1769 void InitOptimizations();
1770 bool runOnFunction(Function &F);
1771
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001772 void setDoesNotAccessMemory(Function &F);
1773 void setOnlyReadsMemory(Function &F);
1774 void setDoesNotThrow(Function &F);
1775 void setDoesNotCapture(Function &F, unsigned n);
1776 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001777 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001778
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001779 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001780 }
1781 };
1782 char SimplifyLibCalls::ID = 0;
1783} // end anonymous namespace.
1784
1785static RegisterPass<SimplifyLibCalls>
1786X("simplify-libcalls", "Simplify well-known library calls");
1787
1788// Public interface to the Simplify LibCalls pass.
1789FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001790 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001791}
1792
1793/// Optimizations - Populate the Optimizations map with all the optimizations
1794/// we know.
1795void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001796 // String and Memory LibCall Optimizations
1797 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001798 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001799 Optimizations["strchr"] = &StrChr;
1800 Optimizations["strcmp"] = &StrCmp;
1801 Optimizations["strncmp"] = &StrNCmp;
1802 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001803 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001804 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001805 Optimizations["strtol"] = &StrTo;
1806 Optimizations["strtod"] = &StrTo;
1807 Optimizations["strtof"] = &StrTo;
1808 Optimizations["strtoul"] = &StrTo;
1809 Optimizations["strtoll"] = &StrTo;
1810 Optimizations["strtold"] = &StrTo;
1811 Optimizations["strtoull"] = &StrTo;
Chris Lattner24604112009-12-16 09:32:05 +00001812 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001813 Optimizations["memcmp"] = &MemCmp;
1814 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001815 Optimizations["memmove"] = &MemMove;
1816 Optimizations["memset"] = &MemSet;
Eric Christopher37c8b862009-10-07 21:14:25 +00001817
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001818 // Math Library Optimizations
1819 Optimizations["powf"] = &Pow;
1820 Optimizations["pow"] = &Pow;
1821 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001822 Optimizations["llvm.pow.f32"] = &Pow;
1823 Optimizations["llvm.pow.f64"] = &Pow;
1824 Optimizations["llvm.pow.f80"] = &Pow;
1825 Optimizations["llvm.pow.f128"] = &Pow;
1826 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001827 Optimizations["exp2l"] = &Exp2;
1828 Optimizations["exp2"] = &Exp2;
1829 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001830 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1831 Optimizations["llvm.exp2.f128"] = &Exp2;
1832 Optimizations["llvm.exp2.f80"] = &Exp2;
1833 Optimizations["llvm.exp2.f64"] = &Exp2;
1834 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001835
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001836#ifdef HAVE_FLOORF
1837 Optimizations["floor"] = &UnaryDoubleFP;
1838#endif
1839#ifdef HAVE_CEILF
1840 Optimizations["ceil"] = &UnaryDoubleFP;
1841#endif
1842#ifdef HAVE_ROUNDF
1843 Optimizations["round"] = &UnaryDoubleFP;
1844#endif
1845#ifdef HAVE_RINTF
1846 Optimizations["rint"] = &UnaryDoubleFP;
1847#endif
1848#ifdef HAVE_NEARBYINTF
1849 Optimizations["nearbyint"] = &UnaryDoubleFP;
1850#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001851
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001852 // Integer Optimizations
1853 Optimizations["ffs"] = &FFS;
1854 Optimizations["ffsl"] = &FFS;
1855 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001856 Optimizations["abs"] = &Abs;
1857 Optimizations["labs"] = &Abs;
1858 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001859 Optimizations["isdigit"] = &IsDigit;
1860 Optimizations["isascii"] = &IsAscii;
1861 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001862
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001863 // Formatting and IO Optimizations
1864 Optimizations["sprintf"] = &SPrintF;
1865 Optimizations["printf"] = &PrintF;
1866 Optimizations["fwrite"] = &FWrite;
1867 Optimizations["fputs"] = &FPuts;
1868 Optimizations["fprintf"] = &FPrintF;
Eric Christopher80bf1d52009-11-21 01:01:30 +00001869
1870 // Object Size Checking
1871 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1872 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1873 Optimizations["__memcpy_chk"] = &MemCpyChk;
1874 Optimizations["__memset_chk"] = &MemSetChk;
1875 Optimizations["__memmove_chk"] = &MemMoveChk;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001876}
1877
1878
1879/// runOnFunction - Top level algorithm.
1880///
1881bool SimplifyLibCalls::runOnFunction(Function &F) {
1882 if (Optimizations.empty())
1883 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001884
Dan Gohmanf14d9192009-08-18 00:48:13 +00001885 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001886
Owen Andersone922c022009-07-22 00:24:57 +00001887 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001888
1889 bool Changed = false;
1890 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1891 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1892 // Ignore non-calls.
1893 CallInst *CI = dyn_cast<CallInst>(I++);
1894 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001895
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001896 // Ignore indirect calls and calls to non-external functions.
1897 Function *Callee = CI->getCalledFunction();
1898 if (Callee == 0 || !Callee->isDeclaration() ||
1899 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1900 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001901
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001902 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001903 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1904 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001905
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001906 // Set the builder to the instruction after the call.
1907 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001908
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001909 // Try to optimize this call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001910 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001911 if (Result == 0) continue;
1912
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001913 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1914 errs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001915
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001916 // Something changed!
1917 Changed = true;
1918 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001919
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001920 // Inspect the instruction after the call (which was potentially just
1921 // added) next.
1922 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001923
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001924 if (CI != Result && !CI->use_empty()) {
1925 CI->replaceAllUsesWith(Result);
1926 if (!Result->hasName())
1927 Result->takeName(CI);
1928 }
1929 CI->eraseFromParent();
1930 }
1931 }
1932 return Changed;
1933}
1934
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001935// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001936
1937void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1938 if (!F.doesNotAccessMemory()) {
1939 F.setDoesNotAccessMemory();
1940 ++NumAnnotated;
1941 Modified = true;
1942 }
1943}
1944void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1945 if (!F.onlyReadsMemory()) {
1946 F.setOnlyReadsMemory();
1947 ++NumAnnotated;
1948 Modified = true;
1949 }
1950}
1951void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1952 if (!F.doesNotThrow()) {
1953 F.setDoesNotThrow();
1954 ++NumAnnotated;
1955 Modified = true;
1956 }
1957}
1958void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1959 if (!F.doesNotCapture(n)) {
1960 F.setDoesNotCapture(n);
1961 ++NumAnnotated;
1962 Modified = true;
1963 }
1964}
1965void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1966 if (!F.doesNotAlias(n)) {
1967 F.setDoesNotAlias(n);
1968 ++NumAnnotated;
1969 Modified = true;
1970 }
1971}
1972
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001973/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001974///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001975bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001976 Modified = false;
1977 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1978 Function &F = *I;
1979 if (!F.isDeclaration())
1980 continue;
1981
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001982 if (!F.hasName())
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001983 continue;
1984
1985 const FunctionType *FTy = F.getFunctionType();
1986
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001987 StringRef Name = F.getName();
1988 switch (Name[0]) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001989 case 's':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001990 if (Name == "strlen") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001991 if (FTy->getNumParams() != 1 ||
1992 !isa<PointerType>(FTy->getParamType(0)))
1993 continue;
1994 setOnlyReadsMemory(F);
1995 setDoesNotThrow(F);
1996 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001997 } else if (Name == "strcpy" ||
1998 Name == "stpcpy" ||
1999 Name == "strcat" ||
2000 Name == "strtol" ||
2001 Name == "strtod" ||
2002 Name == "strtof" ||
2003 Name == "strtoul" ||
2004 Name == "strtoll" ||
2005 Name == "strtold" ||
2006 Name == "strncat" ||
2007 Name == "strncpy" ||
2008 Name == "strtoull") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002009 if (FTy->getNumParams() < 2 ||
2010 !isa<PointerType>(FTy->getParamType(1)))
2011 continue;
2012 setDoesNotThrow(F);
2013 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002014 } else if (Name == "strxfrm") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002015 if (FTy->getNumParams() != 3 ||
2016 !isa<PointerType>(FTy->getParamType(0)) ||
2017 !isa<PointerType>(FTy->getParamType(1)))
2018 continue;
2019 setDoesNotThrow(F);
2020 setDoesNotCapture(F, 1);
2021 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002022 } else if (Name == "strcmp" ||
2023 Name == "strspn" ||
2024 Name == "strncmp" ||
2025 Name ==" strcspn" ||
2026 Name == "strcoll" ||
2027 Name == "strcasecmp" ||
2028 Name == "strncasecmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002029 if (FTy->getNumParams() < 2 ||
2030 !isa<PointerType>(FTy->getParamType(0)) ||
2031 !isa<PointerType>(FTy->getParamType(1)))
2032 continue;
2033 setOnlyReadsMemory(F);
2034 setDoesNotThrow(F);
2035 setDoesNotCapture(F, 1);
2036 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002037 } else if (Name == "strstr" ||
2038 Name == "strpbrk") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002039 if (FTy->getNumParams() != 2 ||
2040 !isa<PointerType>(FTy->getParamType(1)))
2041 continue;
2042 setOnlyReadsMemory(F);
2043 setDoesNotThrow(F);
2044 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002045 } else if (Name == "strtok" ||
2046 Name == "strtok_r") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002047 if (FTy->getNumParams() < 2 ||
2048 !isa<PointerType>(FTy->getParamType(1)))
2049 continue;
2050 setDoesNotThrow(F);
2051 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002052 } else if (Name == "scanf" ||
2053 Name == "setbuf" ||
2054 Name == "setvbuf") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002055 if (FTy->getNumParams() < 1 ||
2056 !isa<PointerType>(FTy->getParamType(0)))
2057 continue;
2058 setDoesNotThrow(F);
2059 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002060 } else if (Name == "strdup" ||
2061 Name == "strndup") {
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002062 if (FTy->getNumParams() < 1 ||
2063 !isa<PointerType>(FTy->getReturnType()) ||
2064 !isa<PointerType>(FTy->getParamType(0)))
2065 continue;
2066 setDoesNotThrow(F);
2067 setDoesNotAlias(F, 0);
2068 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002069 } else if (Name == "stat" ||
2070 Name == "sscanf" ||
2071 Name == "sprintf" ||
2072 Name == "statvfs") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002073 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002074 !isa<PointerType>(FTy->getParamType(0)) ||
2075 !isa<PointerType>(FTy->getParamType(1)))
2076 continue;
2077 setDoesNotThrow(F);
2078 setDoesNotCapture(F, 1);
2079 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002080 } else if (Name == "snprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002081 if (FTy->getNumParams() != 3 ||
2082 !isa<PointerType>(FTy->getParamType(0)) ||
2083 !isa<PointerType>(FTy->getParamType(2)))
2084 continue;
2085 setDoesNotThrow(F);
2086 setDoesNotCapture(F, 1);
2087 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002088 } else if (Name == "setitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002089 if (FTy->getNumParams() != 3 ||
2090 !isa<PointerType>(FTy->getParamType(1)) ||
2091 !isa<PointerType>(FTy->getParamType(2)))
2092 continue;
2093 setDoesNotThrow(F);
2094 setDoesNotCapture(F, 2);
2095 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002096 } else if (Name == "system") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002097 if (FTy->getNumParams() != 1 ||
2098 !isa<PointerType>(FTy->getParamType(0)))
2099 continue;
2100 // May throw; "system" is a valid pthread cancellation point.
2101 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002102 }
2103 break;
2104 case 'm':
Victor Hernandez83d63912009-09-18 22:35:49 +00002105 if (Name == "malloc") {
2106 if (FTy->getNumParams() != 1 ||
2107 !isa<PointerType>(FTy->getReturnType()))
2108 continue;
2109 setDoesNotThrow(F);
2110 setDoesNotAlias(F, 0);
2111 } else if (Name == "memcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002112 if (FTy->getNumParams() != 3 ||
2113 !isa<PointerType>(FTy->getParamType(0)) ||
2114 !isa<PointerType>(FTy->getParamType(1)))
2115 continue;
2116 setOnlyReadsMemory(F);
2117 setDoesNotThrow(F);
2118 setDoesNotCapture(F, 1);
2119 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002120 } else if (Name == "memchr" ||
2121 Name == "memrchr") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002122 if (FTy->getNumParams() != 3)
2123 continue;
2124 setOnlyReadsMemory(F);
2125 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002126 } else if (Name == "modf" ||
2127 Name == "modff" ||
2128 Name == "modfl" ||
2129 Name == "memcpy" ||
2130 Name == "memccpy" ||
2131 Name == "memmove") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002132 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002133 !isa<PointerType>(FTy->getParamType(1)))
2134 continue;
2135 setDoesNotThrow(F);
2136 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002137 } else if (Name == "memalign") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002138 if (!isa<PointerType>(FTy->getReturnType()))
2139 continue;
2140 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002141 } else if (Name == "mkdir" ||
2142 Name == "mktime") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002143 if (FTy->getNumParams() == 0 ||
2144 !isa<PointerType>(FTy->getParamType(0)))
2145 continue;
2146 setDoesNotThrow(F);
2147 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002148 }
2149 break;
2150 case 'r':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002151 if (Name == "realloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002152 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002153 !isa<PointerType>(FTy->getParamType(0)) ||
2154 !isa<PointerType>(FTy->getReturnType()))
2155 continue;
2156 setDoesNotThrow(F);
2157 setDoesNotAlias(F, 0);
2158 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002159 } else if (Name == "read") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002160 if (FTy->getNumParams() != 3 ||
2161 !isa<PointerType>(FTy->getParamType(1)))
2162 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002163 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002164 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002165 } else if (Name == "rmdir" ||
2166 Name == "rewind" ||
2167 Name == "remove" ||
2168 Name == "realpath") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002169 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002170 !isa<PointerType>(FTy->getParamType(0)))
2171 continue;
2172 setDoesNotThrow(F);
2173 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002174 } else if (Name == "rename" ||
2175 Name == "readlink") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002176 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002177 !isa<PointerType>(FTy->getParamType(0)) ||
2178 !isa<PointerType>(FTy->getParamType(1)))
2179 continue;
2180 setDoesNotThrow(F);
2181 setDoesNotCapture(F, 1);
2182 setDoesNotCapture(F, 2);
2183 }
2184 break;
2185 case 'w':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002186 if (Name == "write") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002187 if (FTy->getNumParams() != 3 ||
2188 !isa<PointerType>(FTy->getParamType(1)))
2189 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002190 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002191 setDoesNotCapture(F, 2);
2192 }
2193 break;
2194 case 'b':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002195 if (Name == "bcopy") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002196 if (FTy->getNumParams() != 3 ||
2197 !isa<PointerType>(FTy->getParamType(0)) ||
2198 !isa<PointerType>(FTy->getParamType(1)))
2199 continue;
2200 setDoesNotThrow(F);
2201 setDoesNotCapture(F, 1);
2202 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002203 } else if (Name == "bcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002204 if (FTy->getNumParams() != 3 ||
2205 !isa<PointerType>(FTy->getParamType(0)) ||
2206 !isa<PointerType>(FTy->getParamType(1)))
2207 continue;
2208 setDoesNotThrow(F);
2209 setOnlyReadsMemory(F);
2210 setDoesNotCapture(F, 1);
2211 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002212 } else if (Name == "bzero") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002213 if (FTy->getNumParams() != 2 ||
2214 !isa<PointerType>(FTy->getParamType(0)))
2215 continue;
2216 setDoesNotThrow(F);
2217 setDoesNotCapture(F, 1);
2218 }
2219 break;
2220 case 'c':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002221 if (Name == "calloc") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002222 if (FTy->getNumParams() != 2 ||
2223 !isa<PointerType>(FTy->getReturnType()))
2224 continue;
2225 setDoesNotThrow(F);
2226 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002227 } else if (Name == "chmod" ||
2228 Name == "chown" ||
2229 Name == "ctermid" ||
2230 Name == "clearerr" ||
2231 Name == "closedir") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002232 if (FTy->getNumParams() == 0 ||
2233 !isa<PointerType>(FTy->getParamType(0)))
2234 continue;
2235 setDoesNotThrow(F);
2236 setDoesNotCapture(F, 1);
2237 }
2238 break;
2239 case 'a':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002240 if (Name == "atoi" ||
2241 Name == "atol" ||
2242 Name == "atof" ||
2243 Name == "atoll") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002244 if (FTy->getNumParams() != 1 ||
2245 !isa<PointerType>(FTy->getParamType(0)))
2246 continue;
2247 setDoesNotThrow(F);
2248 setOnlyReadsMemory(F);
2249 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002250 } else if (Name == "access") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002251 if (FTy->getNumParams() != 2 ||
2252 !isa<PointerType>(FTy->getParamType(0)))
2253 continue;
2254 setDoesNotThrow(F);
2255 setDoesNotCapture(F, 1);
2256 }
2257 break;
2258 case 'f':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002259 if (Name == "fopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002260 if (FTy->getNumParams() != 2 ||
2261 !isa<PointerType>(FTy->getReturnType()) ||
2262 !isa<PointerType>(FTy->getParamType(0)) ||
2263 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002264 continue;
2265 setDoesNotThrow(F);
2266 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002267 setDoesNotCapture(F, 1);
2268 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002269 } else if (Name == "fdopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002270 if (FTy->getNumParams() != 2 ||
2271 !isa<PointerType>(FTy->getReturnType()) ||
2272 !isa<PointerType>(FTy->getParamType(1)))
2273 continue;
2274 setDoesNotThrow(F);
2275 setDoesNotAlias(F, 0);
2276 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002277 } else if (Name == "feof" ||
2278 Name == "free" ||
2279 Name == "fseek" ||
2280 Name == "ftell" ||
2281 Name == "fgetc" ||
2282 Name == "fseeko" ||
2283 Name == "ftello" ||
2284 Name == "fileno" ||
2285 Name == "fflush" ||
2286 Name == "fclose" ||
2287 Name == "fsetpos" ||
2288 Name == "flockfile" ||
2289 Name == "funlockfile" ||
2290 Name == "ftrylockfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002291 if (FTy->getNumParams() == 0 ||
2292 !isa<PointerType>(FTy->getParamType(0)))
2293 continue;
2294 setDoesNotThrow(F);
2295 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002296 } else if (Name == "ferror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002297 if (FTy->getNumParams() != 1 ||
2298 !isa<PointerType>(FTy->getParamType(0)))
2299 continue;
2300 setDoesNotThrow(F);
2301 setDoesNotCapture(F, 1);
2302 setOnlyReadsMemory(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002303 } else if (Name == "fputc" ||
2304 Name == "fstat" ||
2305 Name == "frexp" ||
2306 Name == "frexpf" ||
2307 Name == "frexpl" ||
2308 Name == "fstatvfs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002309 if (FTy->getNumParams() != 2 ||
2310 !isa<PointerType>(FTy->getParamType(1)))
2311 continue;
2312 setDoesNotThrow(F);
2313 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002314 } else if (Name == "fgets") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002315 if (FTy->getNumParams() != 3 ||
2316 !isa<PointerType>(FTy->getParamType(0)) ||
2317 !isa<PointerType>(FTy->getParamType(2)))
2318 continue;
2319 setDoesNotThrow(F);
2320 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002321 } else if (Name == "fread" ||
2322 Name == "fwrite") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002323 if (FTy->getNumParams() != 4 ||
2324 !isa<PointerType>(FTy->getParamType(0)) ||
2325 !isa<PointerType>(FTy->getParamType(3)))
2326 continue;
2327 setDoesNotThrow(F);
2328 setDoesNotCapture(F, 1);
2329 setDoesNotCapture(F, 4);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002330 } else if (Name == "fputs" ||
2331 Name == "fscanf" ||
2332 Name == "fprintf" ||
2333 Name == "fgetpos") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002334 if (FTy->getNumParams() < 2 ||
2335 !isa<PointerType>(FTy->getParamType(0)) ||
2336 !isa<PointerType>(FTy->getParamType(1)))
2337 continue;
2338 setDoesNotThrow(F);
2339 setDoesNotCapture(F, 1);
2340 setDoesNotCapture(F, 2);
2341 }
2342 break;
2343 case 'g':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002344 if (Name == "getc" ||
2345 Name == "getlogin_r" ||
2346 Name == "getc_unlocked") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002347 if (FTy->getNumParams() == 0 ||
2348 !isa<PointerType>(FTy->getParamType(0)))
2349 continue;
2350 setDoesNotThrow(F);
2351 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002352 } else if (Name == "getenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002353 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002354 !isa<PointerType>(FTy->getParamType(0)))
2355 continue;
2356 setDoesNotThrow(F);
2357 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002358 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002359 } else if (Name == "gets" ||
2360 Name == "getchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002361 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002362 } else if (Name == "getitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002363 if (FTy->getNumParams() != 2 ||
2364 !isa<PointerType>(FTy->getParamType(1)))
2365 continue;
2366 setDoesNotThrow(F);
2367 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002368 } else if (Name == "getpwnam") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002369 if (FTy->getNumParams() != 1 ||
2370 !isa<PointerType>(FTy->getParamType(0)))
2371 continue;
2372 setDoesNotThrow(F);
2373 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002374 }
2375 break;
2376 case 'u':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002377 if (Name == "ungetc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002378 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002379 !isa<PointerType>(FTy->getParamType(1)))
2380 continue;
2381 setDoesNotThrow(F);
2382 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002383 } else if (Name == "uname" ||
2384 Name == "unlink" ||
2385 Name == "unsetenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002386 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002387 !isa<PointerType>(FTy->getParamType(0)))
2388 continue;
2389 setDoesNotThrow(F);
2390 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002391 } else if (Name == "utime" ||
2392 Name == "utimes") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002393 if (FTy->getNumParams() != 2 ||
2394 !isa<PointerType>(FTy->getParamType(0)) ||
2395 !isa<PointerType>(FTy->getParamType(1)))
2396 continue;
2397 setDoesNotThrow(F);
2398 setDoesNotCapture(F, 1);
2399 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002400 }
2401 break;
2402 case 'p':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002403 if (Name == "putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002404 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002405 !isa<PointerType>(FTy->getParamType(1)))
2406 continue;
2407 setDoesNotThrow(F);
2408 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002409 } else if (Name == "puts" ||
2410 Name == "printf" ||
2411 Name == "perror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002412 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002413 !isa<PointerType>(FTy->getParamType(0)))
2414 continue;
2415 setDoesNotThrow(F);
2416 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002417 } else if (Name == "pread" ||
2418 Name == "pwrite") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002419 if (FTy->getNumParams() != 4 ||
2420 !isa<PointerType>(FTy->getParamType(1)))
2421 continue;
2422 // May throw; these are valid pthread cancellation points.
2423 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002424 } else if (Name == "putchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002425 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002426 } else if (Name == "popen") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002427 if (FTy->getNumParams() != 2 ||
2428 !isa<PointerType>(FTy->getReturnType()) ||
2429 !isa<PointerType>(FTy->getParamType(0)) ||
2430 !isa<PointerType>(FTy->getParamType(1)))
2431 continue;
2432 setDoesNotThrow(F);
2433 setDoesNotAlias(F, 0);
2434 setDoesNotCapture(F, 1);
2435 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002436 } else if (Name == "pclose") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002437 if (FTy->getNumParams() != 1 ||
2438 !isa<PointerType>(FTy->getParamType(0)))
2439 continue;
2440 setDoesNotThrow(F);
2441 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002442 }
2443 break;
2444 case 'v':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002445 if (Name == "vscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002446 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002447 !isa<PointerType>(FTy->getParamType(1)))
2448 continue;
2449 setDoesNotThrow(F);
2450 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002451 } else if (Name == "vsscanf" ||
2452 Name == "vfscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002453 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002454 !isa<PointerType>(FTy->getParamType(1)) ||
2455 !isa<PointerType>(FTy->getParamType(2)))
2456 continue;
2457 setDoesNotThrow(F);
2458 setDoesNotCapture(F, 1);
2459 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002460 } else if (Name == "valloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002461 if (!isa<PointerType>(FTy->getReturnType()))
2462 continue;
2463 setDoesNotThrow(F);
2464 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002465 } else if (Name == "vprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002466 if (FTy->getNumParams() != 2 ||
2467 !isa<PointerType>(FTy->getParamType(0)))
2468 continue;
2469 setDoesNotThrow(F);
2470 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002471 } else if (Name == "vfprintf" ||
2472 Name == "vsprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002473 if (FTy->getNumParams() != 3 ||
2474 !isa<PointerType>(FTy->getParamType(0)) ||
2475 !isa<PointerType>(FTy->getParamType(1)))
2476 continue;
2477 setDoesNotThrow(F);
2478 setDoesNotCapture(F, 1);
2479 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002480 } else if (Name == "vsnprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002481 if (FTy->getNumParams() != 4 ||
2482 !isa<PointerType>(FTy->getParamType(0)) ||
2483 !isa<PointerType>(FTy->getParamType(2)))
2484 continue;
2485 setDoesNotThrow(F);
2486 setDoesNotCapture(F, 1);
2487 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002488 }
2489 break;
2490 case 'o':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002491 if (Name == "open") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002492 if (FTy->getNumParams() < 2 ||
2493 !isa<PointerType>(FTy->getParamType(0)))
2494 continue;
2495 // May throw; "open" is a valid pthread cancellation point.
2496 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002497 } else if (Name == "opendir") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002498 if (FTy->getNumParams() != 1 ||
2499 !isa<PointerType>(FTy->getReturnType()) ||
2500 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002501 continue;
2502 setDoesNotThrow(F);
2503 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002504 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002505 }
2506 break;
2507 case 't':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002508 if (Name == "tmpfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002509 if (!isa<PointerType>(FTy->getReturnType()))
2510 continue;
2511 setDoesNotThrow(F);
2512 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002513 } else if (Name == "times") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002514 if (FTy->getNumParams() != 1 ||
2515 !isa<PointerType>(FTy->getParamType(0)))
2516 continue;
2517 setDoesNotThrow(F);
2518 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002519 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002520 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002521 case 'h':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002522 if (Name == "htonl" ||
2523 Name == "htons") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002524 setDoesNotThrow(F);
2525 setDoesNotAccessMemory(F);
2526 }
2527 break;
2528 case 'n':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002529 if (Name == "ntohl" ||
2530 Name == "ntohs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002531 setDoesNotThrow(F);
2532 setDoesNotAccessMemory(F);
2533 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002534 break;
2535 case 'l':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002536 if (Name == "lstat") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002537 if (FTy->getNumParams() != 2 ||
2538 !isa<PointerType>(FTy->getParamType(0)) ||
2539 !isa<PointerType>(FTy->getParamType(1)))
2540 continue;
2541 setDoesNotThrow(F);
2542 setDoesNotCapture(F, 1);
2543 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002544 } else if (Name == "lchown") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002545 if (FTy->getNumParams() != 3 ||
2546 !isa<PointerType>(FTy->getParamType(0)))
2547 continue;
2548 setDoesNotThrow(F);
2549 setDoesNotCapture(F, 1);
2550 }
2551 break;
2552 case 'q':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002553 if (Name == "qsort") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002554 if (FTy->getNumParams() != 4 ||
2555 !isa<PointerType>(FTy->getParamType(3)))
2556 continue;
2557 // May throw; places call through function pointer.
2558 setDoesNotCapture(F, 4);
2559 }
2560 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002561 case '_':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002562 if (Name == "__strdup" ||
2563 Name == "__strndup") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002564 if (FTy->getNumParams() < 1 ||
2565 !isa<PointerType>(FTy->getReturnType()) ||
2566 !isa<PointerType>(FTy->getParamType(0)))
2567 continue;
2568 setDoesNotThrow(F);
2569 setDoesNotAlias(F, 0);
2570 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002571 } else if (Name == "__strtok_r") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002572 if (FTy->getNumParams() != 3 ||
2573 !isa<PointerType>(FTy->getParamType(1)))
2574 continue;
2575 setDoesNotThrow(F);
2576 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002577 } else if (Name == "_IO_getc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002578 if (FTy->getNumParams() != 1 ||
2579 !isa<PointerType>(FTy->getParamType(0)))
2580 continue;
2581 setDoesNotThrow(F);
2582 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002583 } else if (Name == "_IO_putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002584 if (FTy->getNumParams() != 2 ||
2585 !isa<PointerType>(FTy->getParamType(1)))
2586 continue;
2587 setDoesNotThrow(F);
2588 setDoesNotCapture(F, 2);
2589 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002590 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002591 case 1:
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002592 if (Name == "\1__isoc99_scanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002593 if (FTy->getNumParams() < 1 ||
2594 !isa<PointerType>(FTy->getParamType(0)))
2595 continue;
2596 setDoesNotThrow(F);
2597 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002598 } else if (Name == "\1stat64" ||
2599 Name == "\1lstat64" ||
2600 Name == "\1statvfs64" ||
2601 Name == "\1__isoc99_sscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002602 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002603 !isa<PointerType>(FTy->getParamType(0)) ||
2604 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002605 continue;
2606 setDoesNotThrow(F);
2607 setDoesNotCapture(F, 1);
2608 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002609 } else if (Name == "\1fopen64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002610 if (FTy->getNumParams() != 2 ||
2611 !isa<PointerType>(FTy->getReturnType()) ||
2612 !isa<PointerType>(FTy->getParamType(0)) ||
2613 !isa<PointerType>(FTy->getParamType(1)))
2614 continue;
2615 setDoesNotThrow(F);
2616 setDoesNotAlias(F, 0);
2617 setDoesNotCapture(F, 1);
2618 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002619 } else if (Name == "\1fseeko64" ||
2620 Name == "\1ftello64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002621 if (FTy->getNumParams() == 0 ||
2622 !isa<PointerType>(FTy->getParamType(0)))
2623 continue;
2624 setDoesNotThrow(F);
2625 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002626 } else if (Name == "\1tmpfile64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002627 if (!isa<PointerType>(FTy->getReturnType()))
2628 continue;
2629 setDoesNotThrow(F);
2630 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002631 } else if (Name == "\1fstat64" ||
2632 Name == "\1fstatvfs64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002633 if (FTy->getNumParams() != 2 ||
2634 !isa<PointerType>(FTy->getParamType(1)))
2635 continue;
2636 setDoesNotThrow(F);
2637 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002638 } else if (Name == "\1open64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002639 if (FTy->getNumParams() < 2 ||
2640 !isa<PointerType>(FTy->getParamType(0)))
2641 continue;
2642 // May throw; "open" is a valid pthread cancellation point.
2643 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002644 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002645 break;
2646 }
2647 }
2648 return Modified;
2649}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002650
2651// TODO:
2652// Additional cases that we need to add to this file:
2653//
2654// cbrt:
2655// * cbrt(expN(X)) -> expN(x/3)
2656// * cbrt(sqrt(x)) -> pow(x,1/6)
2657// * cbrt(sqrt(x)) -> pow(x,1/9)
2658//
2659// cos, cosf, cosl:
2660// * cos(-x) -> cos(x)
2661//
2662// exp, expf, expl:
2663// * exp(log(x)) -> x
2664//
2665// log, logf, logl:
2666// * log(exp(x)) -> x
2667// * log(x**y) -> y*log(x)
2668// * log(exp(y)) -> y*log(e)
2669// * log(exp2(y)) -> y*log(2)
2670// * log(exp10(y)) -> y*log(10)
2671// * log(sqrt(x)) -> 0.5*log(x)
2672// * log(pow(x,y)) -> y*log(x)
2673//
2674// lround, lroundf, lroundl:
2675// * lround(cnst) -> cnst'
2676//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002677// pow, powf, powl:
2678// * pow(exp(x),y) -> exp(x*y)
2679// * pow(sqrt(x),y) -> pow(x,y*0.5)
2680// * pow(pow(x,y),z)-> pow(x,y*z)
2681//
2682// puts:
2683// * puts("") -> putchar("\n")
2684//
2685// round, roundf, roundl:
2686// * round(cnst) -> cnst'
2687//
2688// signbit:
2689// * signbit(cnst) -> cnst'
2690// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2691//
2692// sqrt, sqrtf, sqrtl:
2693// * sqrt(expN(x)) -> expN(x*0.5)
2694// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2695// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2696//
2697// stpcpy:
2698// * stpcpy(str, "literal") ->
2699// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2700// strrchr:
2701// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2702// (if c is a constant integer and s is a constant string)
2703// * strrchr(s1,0) -> strchr(s1,0)
2704//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002705// strpbrk:
2706// * strpbrk(s,a) -> offset_in_for(s,a)
2707// (if s and a are both constant strings)
2708// * strpbrk(s,"") -> 0
2709// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2710//
2711// strspn, strcspn:
2712// * strspn(s,a) -> const_int (if both args are constant)
2713// * strspn("",a) -> 0
2714// * strspn(s,"") -> 0
2715// * strcspn(s,a) -> const_int (if both args are constant)
2716// * strcspn("",a) -> 0
2717// * strcspn(s,"") -> strlen(a)
2718//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002719// tan, tanf, tanl:
2720// * tan(atan(x)) -> x
2721//
2722// trunc, truncf, truncl:
2723// * trunc(cnst) -> cnst'
2724//
2725//