blob: 761c309c2004d803df38e2fa42397f544296ad7a [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
12// library functions). For example, a call to the function "exit(3)" that
13// occurs within the main() function can be transformed into a simple "return 3"
14// instruction. Any optimization that takes this form (replace call to library
15// function with simpler code that provides the same result) belongs in this
16// file.
17//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "simplify-libcalls"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
26#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000027#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/ADT/Statistic.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000032#include "llvm/ADT/STLExtras.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000033#include "llvm/Support/Compiler.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000034#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000036#include "llvm/Config/config.h"
37using namespace llvm;
38
39STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000040STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000041
42//===----------------------------------------------------------------------===//
43// Optimizer Base Class
44//===----------------------------------------------------------------------===//
45
46/// This class is the abstract base class for the set of optimizations that
47/// corresponds to one library call.
48namespace {
49class VISIBILITY_HIDDEN LibCallOptimization {
50protected:
51 Function *Caller;
52 const TargetData *TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000053 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000054public:
55 LibCallOptimization() { }
56 virtual ~LibCallOptimization() {}
57
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
62 /// delete CI.
Eric Christopher7a61d702008-08-08 19:39:37 +000063 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
64 =0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000065
Dan Gohmanf14d9192009-08-18 00:48:13 +000066 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000067 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000068 this->TD = TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000069 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000070 Context = &CI->getCalledFunction()->getContext();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000071 return CallOptimizer(CI->getCalledFunction(), CI, B);
72 }
73
74 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000075 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000076
77 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
78 /// specified pointer. Ptr is required to be some pointer type, and the
79 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000080 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000081
82 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
83 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
84 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000085 unsigned Align, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000086
87 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
88 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000089 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +000090
91 /// EmitMemCmp - Emit a call to the memcmp function.
92 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
93
Chris Lattnerf5b6bc72009-04-12 05:06:39 +000094 /// EmitMemSet - Emit a call to the memset function
95 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
96
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000097 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
98 /// 'floor'). This function is known to take a single of type matching 'Op'
99 /// and returns one value with the same type. If 'Op' is a long double, 'l'
100 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
Eric Christopher7a61d702008-08-08 19:39:37 +0000101 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000102
103 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
104 /// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000105 void EmitPutChar(Value *Char, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000106
107 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
108 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000109 void EmitPutS(Value *Str, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000110
111 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
112 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000113 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000114
115 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
116 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000117 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000118
119 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
120 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000121 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000122
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000123};
124} // End anonymous namespace.
125
126/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000127Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000128 return
Owen Anderson1d0be152009-08-13 21:58:54 +0000129 B.CreateBitCast(V, PointerType::getUnqual(Type::getInt8Ty(*Context)), "cstr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000130}
131
132/// EmitStrLen - Emit a call to the strlen function to the builder, for the
133/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000134Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000135 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000136 AttributeWithIndex AWI[2];
137 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
138 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
139 Attribute::NoUnwind);
140
141 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
Owen Anderson1d0be152009-08-13 21:58:54 +0000142 TD->getIntPtrType(*Context),
143 PointerType::getUnqual(Type::getInt8Ty(*Context)),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000144 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000145 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
146 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
147 CI->setCallingConv(F->getCallingConv());
148
149 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000150}
151
152/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
153/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
154Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000155 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000156 Module *M = Caller->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +0000157 Intrinsic::ID IID = Intrinsic::memcpy;
158 const Type *Tys[1];
159 Tys[0] = Len->getType();
160 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000161 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
Owen Anderson1d0be152009-08-13 21:58:54 +0000162 ConstantInt::get(Type::getInt32Ty(*Context), Align));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000163}
164
165/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
166/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
167Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000168 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000169 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000170 AttributeWithIndex AWI;
171 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
172
173 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
Owen Anderson1d0be152009-08-13 21:58:54 +0000174 PointerType::getUnqual(Type::getInt8Ty(*Context)),
175 PointerType::getUnqual(Type::getInt8Ty(*Context)),
176 Type::getInt32Ty(*Context), TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000177 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000178 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
179
180 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
181 CI->setCallingConv(F->getCallingConv());
182
183 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000184}
185
Nick Lewycky13a09e22008-12-21 00:19:21 +0000186/// EmitMemCmp - Emit a call to the memcmp function.
187Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
188 Value *Len, IRBuilder<> &B) {
189 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000190 AttributeWithIndex AWI[3];
191 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
192 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
193 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
194 Attribute::NoUnwind);
195
196 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
Owen Anderson1d0be152009-08-13 21:58:54 +0000197 Type::getInt32Ty(*Context),
198 PointerType::getUnqual(Type::getInt8Ty(*Context)),
199 PointerType::getUnqual(Type::getInt8Ty(*Context)),
200 TD->getIntPtrType(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000201 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
202 Len, "memcmp");
203
204 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
205 CI->setCallingConv(F->getCallingConv());
206
207 return CI;
Nick Lewycky13a09e22008-12-21 00:19:21 +0000208}
209
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000210/// EmitMemSet - Emit a call to the memset function
211Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
212 Value *Len, IRBuilder<> &B) {
213 Module *M = Caller->getParent();
214 Intrinsic::ID IID = Intrinsic::memset;
215 const Type *Tys[1];
216 Tys[0] = Len->getType();
217 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
Owen Anderson1d0be152009-08-13 21:58:54 +0000218 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000219 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
220}
221
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000222/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
223/// 'floor'). This function is known to take a single of type matching 'Op' and
224/// returns one value with the same type. If 'Op' is a long double, 'l' is
225/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
226Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Eric Christopher7a61d702008-08-08 19:39:37 +0000227 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000228 char NameBuffer[20];
Owen Anderson1d0be152009-08-13 21:58:54 +0000229 if (Op->getType() != Type::getDoubleTy(*Context)) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000230 // If we need to add a suffix, copy into NameBuffer.
231 unsigned NameLen = strlen(Name);
232 assert(NameLen < sizeof(NameBuffer)-2);
233 memcpy(NameBuffer, Name, NameLen);
Owen Anderson1d0be152009-08-13 21:58:54 +0000234 if (Op->getType() == Type::getFloatTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000235 NameBuffer[NameLen] = 'f'; // floorf
236 else
237 NameBuffer[NameLen] = 'l'; // floorl
238 NameBuffer[NameLen+1] = 0;
239 Name = NameBuffer;
240 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000241
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000242 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000243 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000244 Op->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000245 CallInst *CI = B.CreateCall(Callee, Op, Name);
246
247 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
248 CI->setCallingConv(F->getCallingConv());
249
250 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000251}
252
253/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
254/// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000255void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000256 Module *M = Caller->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000257 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
258 Type::getInt32Ty(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000259 CallInst *CI = B.CreateCall(PutChar,
Owen Anderson1d0be152009-08-13 21:58:54 +0000260 B.CreateIntCast(Char, Type::getInt32Ty(*Context), "chari"),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000261 "putchar");
262
263 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
264 CI->setCallingConv(F->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000265}
266
267/// EmitPutS - Emit a call to the puts function. This assumes that Str is
268/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000269void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000270 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000271 AttributeWithIndex AWI[2];
272 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
273 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
274
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000275 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
Owen Anderson1d0be152009-08-13 21:58:54 +0000276 Type::getInt32Ty(*Context),
277 PointerType::getUnqual(Type::getInt8Ty(*Context)),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000278 NULL);
279 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
280 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
281 CI->setCallingConv(F->getCallingConv());
282
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000283}
284
285/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
286/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000287void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000288 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000289 AttributeWithIndex AWI[2];
290 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
291 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
292 Constant *F;
293 if (isa<PointerType>(File->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +0000294 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::getInt32Ty(*Context),
295 Type::getInt32Ty(*Context), File->getType(), NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000296 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000297 F = M->getOrInsertFunction("fputc", Type::getInt32Ty(*Context), Type::getInt32Ty(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000298 File->getType(), NULL);
Owen Anderson1d0be152009-08-13 21:58:54 +0000299 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), "chari");
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000300 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
301
302 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
303 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000304}
305
306/// EmitFPutS - Emit a call to the puts function. Str is required to be a
307/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000308void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000309 Module *M = Caller->getParent();
Nick Lewycky225f7472009-02-15 22:47:25 +0000310 AttributeWithIndex AWI[3];
311 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
312 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
313 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000314 Constant *F;
315 if (isa<PointerType>(File->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +0000316 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::getInt32Ty(*Context),
317 PointerType::getUnqual(Type::getInt8Ty(*Context)),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000318 File->getType(), NULL);
319 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000320 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
321 PointerType::getUnqual(Type::getInt8Ty(*Context)),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000322 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000323 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
324
325 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
326 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000327}
328
329/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
330/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
331void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000332 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000333 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000334 AttributeWithIndex AWI[3];
335 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
336 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
337 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
338 Constant *F;
339 if (isa<PointerType>(File->getType()))
340 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
Owen Anderson1d0be152009-08-13 21:58:54 +0000341 TD->getIntPtrType(*Context),
342 PointerType::getUnqual(Type::getInt8Ty(*Context)),
343 TD->getIntPtrType(*Context), TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000344 File->getType(), NULL);
345 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000346 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
347 PointerType::getUnqual(Type::getInt8Ty(*Context)),
348 TD->getIntPtrType(*Context), TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000349 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000350 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Anderson1d0be152009-08-13 21:58:54 +0000351 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000352
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//===----------------------------------------------------------------------===//
358// Helper Functions
359//===----------------------------------------------------------------------===//
360
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000361/// GetStringLengthH - If we can compute the length of the string pointed to by
362/// the specified pointer, return 'len+1'. If we can't, return 0.
363static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
364 // Look through noop bitcast instructions.
365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
366 return GetStringLengthH(BCI->getOperand(0), PHIs);
367
368 // If this is a PHI node, there are two cases: either we have already seen it
369 // or we haven't.
370 if (PHINode *PN = dyn_cast<PHINode>(V)) {
371 if (!PHIs.insert(PN))
372 return ~0ULL; // already in the set.
373
374 // If it was new, see if all the input strings are the same length.
375 uint64_t LenSoFar = ~0ULL;
376 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
377 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
378 if (Len == 0) return 0; // Unknown length -> unknown.
379
380 if (Len == ~0ULL) continue;
381
382 if (Len != LenSoFar && LenSoFar != ~0ULL)
383 return 0; // Disagree -> unknown.
384 LenSoFar = Len;
385 }
386
387 // Success, all agree.
388 return LenSoFar;
389 }
390
391 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
392 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
393 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
394 if (Len1 == 0) return 0;
395 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
396 if (Len2 == 0) return 0;
397 if (Len1 == ~0ULL) return Len2;
398 if (Len2 == ~0ULL) return Len1;
399 if (Len1 != Len2) return 0;
400 return Len1;
401 }
402
403 // If the value is not a GEP instruction nor a constant expression with a
404 // GEP instruction, then return unknown.
405 User *GEP = 0;
406 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
407 GEP = GEPI;
408 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
409 if (CE->getOpcode() != Instruction::GetElementPtr)
410 return 0;
411 GEP = CE;
412 } else {
413 return 0;
414 }
415
416 // Make sure the GEP has exactly three arguments.
417 if (GEP->getNumOperands() != 3)
418 return 0;
419
420 // Check to make sure that the first operand of the GEP is an integer and
421 // has value 0 so that we are sure we're indexing into the initializer.
422 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
423 if (!Idx->isZero())
424 return 0;
425 } else
426 return 0;
427
428 // If the second index isn't a ConstantInt, then this is a variable index
429 // into the array. If this occurs, we can't say anything meaningful about
430 // the string.
431 uint64_t StartIdx = 0;
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
433 StartIdx = CI->getZExtValue();
434 else
435 return 0;
436
437 // The GEP instruction, constant or instruction, must reference a global
438 // variable that is a constant and is initialized. The referenced constant
439 // initializer is the array that we'll use for optimization.
440 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman107f41f2009-08-19 00:11:12 +0000441 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
442 GV->mayBeOverridden())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000443 return 0;
444 Constant *GlobalInit = GV->getInitializer();
445
446 // Handle the ConstantAggregateZero case, which is a degenerate case. The
447 // initializer is constant zero so the length of the string must be zero.
448 if (isa<ConstantAggregateZero>(GlobalInit))
449 return 1; // Len = 0 offset by 1.
450
451 // Must be a Constant Array
452 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Owen Anderson1d0be152009-08-13 21:58:54 +0000453 if (!Array ||
454 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000455 return false;
456
457 // Get the number of elements in the array
458 uint64_t NumElts = Array->getType()->getNumElements();
459
460 // Traverse the constant array from StartIdx (derived above) which is
461 // the place the GEP refers to in the array.
462 for (unsigned i = StartIdx; i != NumElts; ++i) {
463 Constant *Elt = Array->getOperand(i);
464 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
465 if (!CI) // This array isn't suitable, non-int initializer.
466 return 0;
467 if (CI->isZero())
468 return i-StartIdx+1; // We found end of string, success!
469 }
470
471 return 0; // The array isn't null terminated, conservatively return 'unknown'.
472}
473
474/// GetStringLength - If we can compute the length of the string pointed to by
475/// the specified pointer, return 'len+1'. If we can't, return 0.
476static uint64_t GetStringLength(Value *V) {
477 if (!isa<PointerType>(V->getType())) return 0;
478
479 SmallPtrSet<PHINode*, 32> PHIs;
480 uint64_t Len = GetStringLengthH(V, PHIs);
481 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
482 // an empty string as a length.
483 return Len == ~0ULL ? 1 : Len;
484}
485
486/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
487/// value is equal or not-equal to zero.
488static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
489 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
490 UI != E; ++UI) {
491 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
492 if (IC->isEquality())
493 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
494 if (C->isNullValue())
495 continue;
496 // Unknown instruction.
497 return false;
498 }
499 return true;
500}
501
502//===----------------------------------------------------------------------===//
503// Miscellaneous LibCall Optimizations
504//===----------------------------------------------------------------------===//
505
Bill Wendlingac178222008-05-05 21:37:59 +0000506namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000507//===---------------------------------------===//
508// 'exit' Optimizations
509
510/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
511struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000512 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000513 // Verify we have a reasonable prototype for exit.
514 if (Callee->arg_size() == 0 || !CI->use_empty())
515 return 0;
516
517 // Verify the caller is main, and that the result type of main matches the
518 // argument type of exit.
Daniel Dunbar03d76512009-07-25 23:55:21 +0000519 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000520 Caller->getReturnType() != CI->getOperand(1)->getType())
521 return 0;
522
523 TerminatorInst *OldTI = CI->getParent()->getTerminator();
Daniel Dunbar473955f2009-07-29 22:00:43 +0000524
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000525 // Drop all successor phi node entries.
526 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
527 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
Nick Lewycky0efa9212009-07-29 05:17:50 +0000528
Daniel Dunbar473955f2009-07-29 22:00:43 +0000529 // Remove all instructions after the exit.
530 BasicBlock::iterator Dead = CI, E = OldTI; ++Dead;
531 while (Dead != E) {
532 BasicBlock::iterator Next = next(Dead);
Owen Anderson1d0be152009-08-13 21:58:54 +0000533 if (Dead->getType() != Type::getVoidTy(*Context))
Daniel Dunbar473955f2009-07-29 22:00:43 +0000534 Dead->replaceAllUsesWith(UndefValue::get(Dead->getType()));
535 Dead->eraseFromParent();
536 Dead = Next;
537 }
538
539 // Insert a return instruction.
540 OldTI->eraseFromParent();
541 B.SetInsertPoint(B.GetInsertBlock());
Nick Lewycky0efa9212009-07-29 05:17:50 +0000542 B.CreateRet(CI->getOperand(1));
543
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000544 return CI;
545 }
546};
547
548//===----------------------------------------------------------------------===//
549// String and Memory LibCall Optimizations
550//===----------------------------------------------------------------------===//
551
552//===---------------------------------------===//
553// 'strcat' Optimizations
554
555struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000556 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000557 // Verify the "strcat" function prototype.
558 const FunctionType *FT = Callee->getFunctionType();
559 if (FT->getNumParams() != 2 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 FT->getReturnType() != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000561 FT->getParamType(0) != FT->getReturnType() ||
562 FT->getParamType(1) != FT->getReturnType())
563 return 0;
564
565 // Extract some information from the instruction
566 Value *Dst = CI->getOperand(1);
567 Value *Src = CI->getOperand(2);
568
569 // See if we can get the length of the input string.
570 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000571 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000572 --Len; // Unbias length.
573
574 // Handle the simple, do-nothing case: strcat(x, "") -> x
575 if (Len == 0)
576 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000577
578 // These optimizations require TargetData.
579 if (!TD) return 0;
580
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000581 EmitStrLenMemCpy(Src, Dst, Len, B);
582 return Dst;
583 }
584
585 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000586 // We need to find the end of the destination string. That's where the
587 // memory is to be moved to. We just generate a call to strlen.
588 Value *DstLen = EmitStrLen(Dst, B);
589
590 // Now that we have the destination's length, we must index into the
591 // destination's pointer to get the actual memcpy destination (end of
592 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000593 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000594
595 // We have enough information to now generate the memcpy call to do the
596 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000597 EmitMemCpy(CpyDst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000598 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000599 }
600};
601
602//===---------------------------------------===//
603// 'strncat' Optimizations
604
605struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
606 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
607 // Verify the "strncat" function prototype.
608 const FunctionType *FT = Callee->getFunctionType();
609 if (FT->getNumParams() != 3 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000610 FT->getReturnType() != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000611 FT->getParamType(0) != FT->getReturnType() ||
612 FT->getParamType(1) != FT->getReturnType() ||
613 !isa<IntegerType>(FT->getParamType(2)))
614 return 0;
615
616 // Extract some information from the instruction
617 Value *Dst = CI->getOperand(1);
618 Value *Src = CI->getOperand(2);
619 uint64_t Len;
620
621 // We don't do anything if length is not constant
622 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
623 Len = LengthArg->getZExtValue();
624 else
625 return 0;
626
627 // See if we can get the length of the input string.
628 uint64_t SrcLen = GetStringLength(Src);
629 if (SrcLen == 0) return 0;
630 --SrcLen; // Unbias length.
631
632 // Handle the simple, do-nothing cases:
633 // strncat(x, "", c) -> x
634 // strncat(x, c, 0) -> x
635 if (SrcLen == 0 || Len == 0) return Dst;
636
Dan Gohmanf14d9192009-08-18 00:48:13 +0000637 // These optimizations require TargetData.
638 if (!TD) return 0;
639
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000640 // We don't optimize this case
641 if (Len < SrcLen) return 0;
642
643 // strncat(x, s, c) -> strcat(x, s)
644 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000645 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000646 return Dst;
647 }
648};
649
650//===---------------------------------------===//
651// 'strchr' Optimizations
652
653struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000654 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000655 // Verify the "strchr" function prototype.
656 const FunctionType *FT = Callee->getFunctionType();
657 if (FT->getNumParams() != 2 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000658 FT->getReturnType() != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000659 FT->getParamType(0) != FT->getReturnType())
660 return 0;
661
662 Value *SrcStr = CI->getOperand(1);
663
664 // If the second operand is non-constant, see if we can compute the length
665 // of the input string and turn this into memchr.
666 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
667 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000668 // These optimizations require TargetData.
669 if (!TD) return 0;
670
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000671 uint64_t Len = GetStringLength(SrcStr);
Owen Anderson1d0be152009-08-13 21:58:54 +0000672 if (Len == 0 || FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000673 return 0;
674
675 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Anderson1d0be152009-08-13 21:58:54 +0000676 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000677 }
678
679 // Otherwise, the character is a constant, see if the first argument is
680 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000681 std::string Str;
682 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000683 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000684
685 // strchr can find the nul character.
686 Str += '\0';
687 char CharValue = CharC->getSExtValue();
688
689 // Compute the offset.
690 uint64_t i = 0;
691 while (1) {
692 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersona7235ea2009-07-31 20:28:14 +0000693 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000694 // Did we find our match?
695 if (Str[i] == CharValue)
696 break;
697 ++i;
698 }
699
700 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Anderson1d0be152009-08-13 21:58:54 +0000701 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000702 return B.CreateGEP(SrcStr, Idx, "strchr");
703 }
704};
705
706//===---------------------------------------===//
707// 'strcmp' Optimizations
708
709struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000710 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000711 // Verify the "strcmp" function prototype.
712 const FunctionType *FT = Callee->getFunctionType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000713 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000714 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000715 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000716 return 0;
717
718 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
719 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000720 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000721
Bill Wendling0582ae92009-03-13 04:39:26 +0000722 std::string Str1, Str2;
723 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
724 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
725
726 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000727 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
728
Bill Wendling0582ae92009-03-13 04:39:26 +0000729 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000730 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
731
732 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000733 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000734 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000735 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000736
737 // strcmp(P, "x") -> memcmp(P, "x", 2)
738 uint64_t Len1 = GetStringLength(Str1P);
739 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000740 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000741 // These optimizations require TargetData.
742 if (!TD) return 0;
743
Nick Lewycky13a09e22008-12-21 00:19:21 +0000744 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000745 ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattner849832c2009-06-19 04:17:36 +0000746 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000747 }
748
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000749 return 0;
750 }
751};
752
753//===---------------------------------------===//
754// 'strncmp' Optimizations
755
756struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000757 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000758 // Verify the "strncmp" function prototype.
759 const FunctionType *FT = Callee->getFunctionType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000760 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000761 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000762 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000763 !isa<IntegerType>(FT->getParamType(2)))
764 return 0;
765
766 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
767 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000768 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000769
770 // Get the length argument if it is constant.
771 uint64_t Length;
772 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
773 Length = LengthArg->getZExtValue();
774 else
775 return 0;
776
777 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000778 return ConstantInt::get(CI->getType(), 0);
Bill Wendling0582ae92009-03-13 04:39:26 +0000779
780 std::string Str1, Str2;
781 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
782 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
783
784 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000785 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
786
Bill Wendling0582ae92009-03-13 04:39:26 +0000787 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000788 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
789
790 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000791 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000792 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000793 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000794 return 0;
795 }
796};
797
798
799//===---------------------------------------===//
800// 'strcpy' Optimizations
801
802struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000803 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000804 // Verify the "strcpy" function prototype.
805 const FunctionType *FT = Callee->getFunctionType();
806 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
807 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000808 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000809 return 0;
810
811 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
812 if (Dst == Src) // strcpy(x,x) -> x
813 return Src;
814
Dan Gohmanf14d9192009-08-18 00:48:13 +0000815 // These optimizations require TargetData.
816 if (!TD) return 0;
817
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000818 // See if we can get the length of the input string.
819 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000820 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000821
822 // We have enough information to now generate the memcpy call to do the
823 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000824 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000825 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000826 return Dst;
827 }
828};
829
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000830//===---------------------------------------===//
831// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000832
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000833struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
834 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
835 const FunctionType *FT = Callee->getFunctionType();
836 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
837 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000838 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000839 !isa<IntegerType>(FT->getParamType(2)))
840 return 0;
841
842 Value *Dst = CI->getOperand(1);
843 Value *Src = CI->getOperand(2);
844 Value *LenOp = CI->getOperand(3);
845
846 // See if we can get the length of the input string.
847 uint64_t SrcLen = GetStringLength(Src);
848 if (SrcLen == 0) return 0;
849 --SrcLen;
850
851 if (SrcLen == 0) {
852 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Owen Anderson1d0be152009-08-13 21:58:54 +0000853 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000854 return Dst;
855 }
856
857 uint64_t Len;
858 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
859 Len = LengthArg->getZExtValue();
860 else
861 return 0;
862
863 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
864
Dan Gohmanf14d9192009-08-18 00:48:13 +0000865 // These optimizations require TargetData.
866 if (!TD) return 0;
867
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000868 // Let strncpy handle the zero padding
869 if (Len > SrcLen+1) return 0;
870
871 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000872 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000873 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000874
875 return Dst;
876 }
877};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000878
879//===---------------------------------------===//
880// 'strlen' Optimizations
881
882struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000883 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000884 const FunctionType *FT = Callee->getFunctionType();
885 if (FT->getNumParams() != 1 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000886 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000887 !isa<IntegerType>(FT->getReturnType()))
888 return 0;
889
890 Value *Src = CI->getOperand(1);
891
892 // Constant folding: strlen("xyz") -> 3
893 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000894 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000895
896 // Handle strlen(p) != 0.
897 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
898
899 // strlen(x) != 0 --> *x != 0
900 // strlen(x) == 0 --> *x == 0
901 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
902 }
903};
904
905//===---------------------------------------===//
Nick Lewycky4c498412009-02-13 15:31:46 +0000906// 'strto*' Optimizations
907
908struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
909 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
910 const FunctionType *FT = Callee->getFunctionType();
911 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
912 !isa<PointerType>(FT->getParamType(0)) ||
913 !isa<PointerType>(FT->getParamType(1)))
914 return 0;
915
916 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000917 if (isa<ConstantPointerNull>(EndPtr)) {
918 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000919 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000920 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000921
922 return 0;
923 }
924};
925
926
927//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000928// 'memcmp' Optimizations
929
930struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000931 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000932 const FunctionType *FT = Callee->getFunctionType();
933 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
934 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000935 FT->getReturnType() != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000936 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000937
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000938 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000939
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000940 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000941 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000942
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000943 // Make sure we have a constant length.
944 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000945 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000946 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000947
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000948 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000949 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000950
951 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
952 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
953 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +0000954 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000955 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000956
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000957 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
958 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
959 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Owen Andersondebcb012009-07-29 22:17:13 +0000960 const Type *PTy = PointerType::getUnqual(Len == 2 ?
Owen Anderson1d0be152009-08-13 21:58:54 +0000961 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000962 LHS = B.CreateBitCast(LHS, PTy, "tmp");
963 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000964 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
965 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
966 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
967 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
968 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000969
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000970 return 0;
971 }
972};
973
974//===---------------------------------------===//
975// 'memcpy' Optimizations
976
977struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000978 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000979 // These optimizations require TargetData.
980 if (!TD) return 0;
981
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000982 const FunctionType *FT = Callee->getFunctionType();
983 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
984 !isa<PointerType>(FT->getParamType(0)) ||
985 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000986 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000987 return 0;
988
989 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
990 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
991 return CI->getOperand(1);
992 }
993};
994
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000995//===---------------------------------------===//
996// 'memmove' Optimizations
997
998struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
999 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001000 // These optimizations require TargetData.
1001 if (!TD) return 0;
1002
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001003 const FunctionType *FT = Callee->getFunctionType();
1004 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1005 !isa<PointerType>(FT->getParamType(0)) ||
1006 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001007 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001008 return 0;
1009
1010 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1011 Module *M = Caller->getParent();
1012 Intrinsic::ID IID = Intrinsic::memmove;
1013 const Type *Tys[1];
Owen Anderson1d0be152009-08-13 21:58:54 +00001014 Tys[0] = TD->getIntPtrType(*Context);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001015 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
1016 Value *Dst = CastToCStr(CI->getOperand(1), B);
1017 Value *Src = CastToCStr(CI->getOperand(2), B);
1018 Value *Size = CI->getOperand(3);
Owen Anderson1d0be152009-08-13 21:58:54 +00001019 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001020 B.CreateCall4(MemMove, Dst, Src, Size, Align);
1021 return CI->getOperand(1);
1022 }
1023};
1024
1025//===---------------------------------------===//
1026// 'memset' Optimizations
1027
1028struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
1029 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001030 // These optimizations require TargetData.
1031 if (!TD) return 0;
1032
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001033 const FunctionType *FT = Callee->getFunctionType();
1034 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1035 !isa<PointerType>(FT->getParamType(0)) ||
Eli Friedman62bb4132009-07-18 08:34:51 +00001036 !isa<IntegerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001037 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001038 return 0;
1039
1040 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Owen Anderson1d0be152009-08-13 21:58:54 +00001041 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context), false);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001042 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001043 return CI->getOperand(1);
1044 }
1045};
1046
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001047//===----------------------------------------------------------------------===//
1048// Math Library Optimizations
1049//===----------------------------------------------------------------------===//
1050
1051//===---------------------------------------===//
1052// 'pow*' Optimizations
1053
1054struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001055 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001056 const FunctionType *FT = Callee->getFunctionType();
1057 // Just make sure this has 2 arguments of the same FP type, which match the
1058 // result type.
1059 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1060 FT->getParamType(0) != FT->getParamType(1) ||
1061 !FT->getParamType(0)->isFloatingPoint())
1062 return 0;
1063
1064 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1065 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1066 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1067 return Op1C;
1068 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1069 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1070 }
1071
1072 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1073 if (Op2C == 0) return 0;
1074
1075 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001076 return ConstantFP::get(CI->getType(), 1.0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001077
1078 if (Op2C->isExactlyValue(0.5)) {
1079 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1080 // 'unsafe' math optimizations are allowed.
1081 // x pow(x, 0.5) sqrt(x)
1082 // ---------------------------------------------
1083 // -0.0 +0.0 -0.0
1084 // -inf +inf NaN
1085#if 0
1086 // pow(x, 0.5) -> sqrt(x)
1087 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1088#endif
1089 }
1090
1091 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1092 return Op1;
1093 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001094 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001095 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001096 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001097 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001098 return 0;
1099 }
1100};
1101
1102//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001103// 'exp2' Optimizations
1104
1105struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001106 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001107 const FunctionType *FT = Callee->getFunctionType();
1108 // Just make sure this has 1 argument of FP type, which matches the
1109 // result type.
1110 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1111 !FT->getParamType(0)->isFloatingPoint())
1112 return 0;
1113
1114 Value *Op = CI->getOperand(1);
1115 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1116 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1117 Value *LdExpArg = 0;
1118 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1119 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Owen Anderson1d0be152009-08-13 21:58:54 +00001120 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001121 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1122 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +00001123 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001124 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001125
Chris Lattnere818f772008-05-02 18:43:35 +00001126 if (LdExpArg) {
1127 const char *Name;
Owen Anderson1d0be152009-08-13 21:58:54 +00001128 if (Op->getType() == Type::getFloatTy(*Context))
Chris Lattnere818f772008-05-02 18:43:35 +00001129 Name = "ldexpf";
Owen Anderson1d0be152009-08-13 21:58:54 +00001130 else if (Op->getType() == Type::getDoubleTy(*Context))
Chris Lattnere818f772008-05-02 18:43:35 +00001131 Name = "ldexp";
1132 else
1133 Name = "ldexpl";
1134
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001135 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Owen Anderson1d0be152009-08-13 21:58:54 +00001136 if (Op->getType() != Type::getFloatTy(*Context))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001137 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001138
1139 Module *M = Caller->getParent();
1140 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001141 Op->getType(), Type::getInt32Ty(*Context),NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001142 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1143 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1144 CI->setCallingConv(F->getCallingConv());
1145
1146 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001147 }
1148 return 0;
1149 }
1150};
Chris Lattnere818f772008-05-02 18:43:35 +00001151
1152//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001153// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1154
1155struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001156 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001157 const FunctionType *FT = Callee->getFunctionType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001158 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::getDoubleTy(*Context) ||
1159 FT->getParamType(0) != Type::getDoubleTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001160 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001161
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001162 // If this is something like 'floor((double)floatval)', convert to floorf.
1163 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
Owen Anderson1d0be152009-08-13 21:58:54 +00001164 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::getFloatTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001165 return 0;
1166
1167 // floor((double)floatval) -> (double)floorf(floatval)
1168 Value *V = Cast->getOperand(0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001169 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
Owen Anderson1d0be152009-08-13 21:58:54 +00001170 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001171 }
1172};
1173
1174//===----------------------------------------------------------------------===//
1175// Integer Optimizations
1176//===----------------------------------------------------------------------===//
1177
1178//===---------------------------------------===//
1179// 'ffs*' Optimizations
1180
1181struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001182 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001183 const FunctionType *FT = Callee->getFunctionType();
1184 // Just make sure this has 2 arguments of the same FP type, which match the
1185 // result type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001186 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001187 !isa<IntegerType>(FT->getParamType(0)))
1188 return 0;
1189
1190 Value *Op = CI->getOperand(1);
1191
1192 // Constant fold.
1193 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1194 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001195 return Constant::getNullValue(CI->getType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001196 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001197 CI->getValue().countTrailingZeros()+1);
1198 }
1199
1200 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1201 const Type *ArgType = Op->getType();
1202 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1203 Intrinsic::cttz, &ArgType, 1);
1204 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +00001205 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001206 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001207
Owen Andersona7235ea2009-07-31 20:28:14 +00001208 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001209 return B.CreateSelect(Cond, V, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 }
1211};
1212
1213//===---------------------------------------===//
1214// 'isdigit' Optimizations
1215
1216struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001217 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001218 const FunctionType *FT = Callee->getFunctionType();
1219 // We require integer(i32)
1220 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001221 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001222 return 0;
1223
1224 // isdigit(c) -> (c-'0') <u 10
1225 Value *Op = CI->getOperand(1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001226 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001227 "isdigittmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001228 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001229 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001230 return B.CreateZExt(Op, CI->getType());
1231 }
1232};
1233
1234//===---------------------------------------===//
1235// 'isascii' Optimizations
1236
1237struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001238 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001239 const FunctionType *FT = Callee->getFunctionType();
1240 // We require integer(i32)
1241 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001242 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001243 return 0;
1244
1245 // isascii(c) -> c <u 128
1246 Value *Op = CI->getOperand(1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001247 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001248 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001249 return B.CreateZExt(Op, CI->getType());
1250 }
1251};
Chris Lattner313f0e62008-06-09 08:26:51 +00001252
1253//===---------------------------------------===//
1254// 'abs', 'labs', 'llabs' Optimizations
1255
1256struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001257 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001258 const FunctionType *FT = Callee->getFunctionType();
1259 // We require integer(integer) where the types agree.
1260 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1261 FT->getParamType(0) != FT->getReturnType())
1262 return 0;
1263
1264 // abs(x) -> x >s -1 ? x : -x
1265 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001266 Value *Pos = B.CreateICmpSGT(Op,
Owen Andersona7235ea2009-07-31 20:28:14 +00001267 Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001268 "ispos");
1269 Value *Neg = B.CreateNeg(Op, "neg");
1270 return B.CreateSelect(Pos, Op, Neg);
1271 }
1272};
1273
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001274
1275//===---------------------------------------===//
1276// 'toascii' Optimizations
1277
1278struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001279 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001280 const FunctionType *FT = Callee->getFunctionType();
1281 // We require i32(i32)
1282 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001283 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001284 return 0;
1285
1286 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001287 return B.CreateAnd(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001288 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001289 }
1290};
1291
1292//===----------------------------------------------------------------------===//
1293// Formatting and IO Optimizations
1294//===----------------------------------------------------------------------===//
1295
1296//===---------------------------------------===//
1297// 'printf' Optimizations
1298
1299struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001300 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001301 // Require one fixed pointer argument and an integer/void result.
1302 const FunctionType *FT = Callee->getFunctionType();
1303 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1304 !(isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001305 FT->getReturnType() == Type::getVoidTy(*Context)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001306 return 0;
1307
1308 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001309 std::string FormatStr;
1310 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1311 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001312
1313 // Empty format string -> noop.
1314 if (FormatStr.empty()) // Tolerate printf's declared void.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001315 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001316 ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001317
1318 // printf("x") -> putchar('x'), even for '%'.
1319 if (FormatStr.size() == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001320 EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context), FormatStr[0]), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001321 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001322 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001323 }
1324
1325 // printf("foo\n") --> puts("foo")
1326 if (FormatStr[FormatStr.size()-1] == '\n' &&
1327 FormatStr.find('%') == std::string::npos) { // no format characters.
1328 // Create a string literal with no \n on it. We expect the constant merge
1329 // pass to be run after this pass, to merge duplicate strings.
1330 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001331 Constant *C = ConstantArray::get(*Context, FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001332 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1333 GlobalVariable::InternalLinkage, C, "str");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001334 EmitPutS(C, B);
1335 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001336 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001337 }
1338
1339 // Optimize specific format strings.
1340 // printf("%c", chr) --> putchar(*(i8*)dst)
1341 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1342 isa<IntegerType>(CI->getOperand(2)->getType())) {
1343 EmitPutChar(CI->getOperand(2), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001344 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001345 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001346 }
1347
1348 // printf("%s\n", str) --> puts(str)
1349 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1350 isa<PointerType>(CI->getOperand(2)->getType()) &&
1351 CI->use_empty()) {
1352 EmitPutS(CI->getOperand(2), B);
1353 return CI;
1354 }
1355 return 0;
1356 }
1357};
1358
1359//===---------------------------------------===//
1360// 'sprintf' Optimizations
1361
1362struct VISIBILITY_HIDDEN SPrintFOpt : 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 // Require two fixed pointer arguments and an integer result.
1365 const FunctionType *FT = Callee->getFunctionType();
1366 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1367 !isa<PointerType>(FT->getParamType(1)) ||
1368 !isa<IntegerType>(FT->getReturnType()))
1369 return 0;
1370
1371 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001372 std::string FormatStr;
1373 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1374 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001375
1376 // If we just have a format string (nothing else crazy) transform it.
1377 if (CI->getNumOperands() == 3) {
1378 // Make sure there's no % in the constant array. We could try to handle
1379 // %% -> % in the future if we cared.
1380 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1381 if (FormatStr[i] == '%')
1382 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001383
1384 // These optimizations require TargetData.
1385 if (!TD) return 0;
1386
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001387 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1388 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Owen Anderson1d0be152009-08-13 21:58:54 +00001389 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001390 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001391 }
1392
1393 // The remaining optimizations require the format string to be "%s" or "%c"
1394 // and have an extra operand.
1395 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1396 return 0;
1397
1398 // Decode the second character of the format string.
1399 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001400 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001401 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00001402 Value *V = B.CreateTrunc(CI->getOperand(3), Type::getInt8Ty(*Context), "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001403 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1404 B.CreateStore(V, Ptr);
Owen Anderson1d0be152009-08-13 21:58:54 +00001405 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1), "nul");
1406 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001407
Owen Andersoneed707b2009-07-24 23:12:02 +00001408 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001409 }
1410
1411 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001412 // These optimizations require TargetData.
1413 if (!TD) return 0;
1414
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001415 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1416 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1417
1418 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001419 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001420 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001421 "leninc");
1422 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1423
1424 // The sprintf result is the unincremented number of bytes in the string.
1425 return B.CreateIntCast(Len, CI->getType(), false);
1426 }
1427 return 0;
1428 }
1429};
1430
1431//===---------------------------------------===//
1432// 'fwrite' Optimizations
1433
1434struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001435 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001436 // Require a pointer, an integer, an integer, a pointer, returning integer.
1437 const FunctionType *FT = Callee->getFunctionType();
1438 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1439 !isa<IntegerType>(FT->getParamType(1)) ||
1440 !isa<IntegerType>(FT->getParamType(2)) ||
1441 !isa<PointerType>(FT->getParamType(3)) ||
1442 !isa<IntegerType>(FT->getReturnType()))
1443 return 0;
1444
1445 // Get the element size and count.
1446 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1447 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1448 if (!SizeC || !CountC) return 0;
1449 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1450
1451 // If this is writing zero records, remove the call (it's a noop).
1452 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001453 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001454
1455 // If this is writing one byte, turn it into fputc.
1456 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1457 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1458 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001459 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001460 }
1461
1462 return 0;
1463 }
1464};
1465
1466//===---------------------------------------===//
1467// 'fputs' Optimizations
1468
1469struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001470 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001471 // These optimizations require TargetData.
1472 if (!TD) return 0;
1473
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001474 // Require two pointers. Also, we can't optimize if return value is used.
1475 const FunctionType *FT = Callee->getFunctionType();
1476 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1477 !isa<PointerType>(FT->getParamType(1)) ||
1478 !CI->use_empty())
1479 return 0;
1480
1481 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1482 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001483 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001484 EmitFWrite(CI->getOperand(1),
Owen Anderson1d0be152009-08-13 21:58:54 +00001485 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001486 CI->getOperand(2), B);
1487 return CI; // Known to have no uses (see above).
1488 }
1489};
1490
1491//===---------------------------------------===//
1492// 'fprintf' Optimizations
1493
1494struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001495 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001496 // Require two fixed paramters as pointers and integer result.
1497 const FunctionType *FT = Callee->getFunctionType();
1498 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1499 !isa<PointerType>(FT->getParamType(1)) ||
1500 !isa<IntegerType>(FT->getReturnType()))
1501 return 0;
1502
1503 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001504 std::string FormatStr;
1505 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1506 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001507
1508 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1509 if (CI->getNumOperands() == 3) {
1510 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1511 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001512 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001513
1514 // These optimizations require TargetData.
1515 if (!TD) return 0;
1516
Owen Anderson1d0be152009-08-13 21:58:54 +00001517 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001518 FormatStr.size()),
1519 CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001520 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001521 }
1522
1523 // The remaining optimizations require the format string to be "%s" or "%c"
1524 // and have an extra operand.
1525 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1526 return 0;
1527
1528 // Decode the second character of the format string.
1529 if (FormatStr[1] == 'c') {
1530 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1531 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1532 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001533 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001534 }
1535
1536 if (FormatStr[1] == 's') {
1537 // fprintf(F, "%s", str) -> fputs(str, F)
1538 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1539 return 0;
1540 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1541 return CI;
1542 }
1543 return 0;
1544 }
1545};
1546
Bill Wendlingac178222008-05-05 21:37:59 +00001547} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001548
1549//===----------------------------------------------------------------------===//
1550// SimplifyLibCalls Pass Implementation
1551//===----------------------------------------------------------------------===//
1552
1553namespace {
1554 /// This pass optimizes well known library functions from libc and libm.
1555 ///
1556 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1557 StringMap<LibCallOptimization*> Optimizations;
1558 // Miscellaneous LibCall Optimizations
1559 ExitOpt Exit;
1560 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001561 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1562 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1563 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1564 MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001565 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001566 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001567 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001568 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1569 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001570 // Formatting and IO Optimizations
1571 SPrintFOpt SPrintF; PrintFOpt PrintF;
1572 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001573
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001574 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001575 public:
1576 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001577 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001578
1579 void InitOptimizations();
1580 bool runOnFunction(Function &F);
1581
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001582 void setDoesNotAccessMemory(Function &F);
1583 void setOnlyReadsMemory(Function &F);
1584 void setDoesNotThrow(Function &F);
1585 void setDoesNotCapture(Function &F, unsigned n);
1586 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001587 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001588
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001589 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001590 }
1591 };
1592 char SimplifyLibCalls::ID = 0;
1593} // end anonymous namespace.
1594
1595static RegisterPass<SimplifyLibCalls>
1596X("simplify-libcalls", "Simplify well-known library calls");
1597
1598// Public interface to the Simplify LibCalls pass.
1599FunctionPass *llvm::createSimplifyLibCallsPass() {
1600 return new SimplifyLibCalls();
1601}
1602
1603/// Optimizations - Populate the Optimizations map with all the optimizations
1604/// we know.
1605void SimplifyLibCalls::InitOptimizations() {
1606 // Miscellaneous LibCall Optimizations
1607 Optimizations["exit"] = &Exit;
1608
1609 // String and Memory LibCall Optimizations
1610 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001611 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001612 Optimizations["strchr"] = &StrChr;
1613 Optimizations["strcmp"] = &StrCmp;
1614 Optimizations["strncmp"] = &StrNCmp;
1615 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001616 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001617 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001618 Optimizations["strtol"] = &StrTo;
1619 Optimizations["strtod"] = &StrTo;
1620 Optimizations["strtof"] = &StrTo;
1621 Optimizations["strtoul"] = &StrTo;
1622 Optimizations["strtoll"] = &StrTo;
1623 Optimizations["strtold"] = &StrTo;
1624 Optimizations["strtoull"] = &StrTo;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001625 Optimizations["memcmp"] = &MemCmp;
1626 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001627 Optimizations["memmove"] = &MemMove;
1628 Optimizations["memset"] = &MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001629
1630 // Math Library Optimizations
1631 Optimizations["powf"] = &Pow;
1632 Optimizations["pow"] = &Pow;
1633 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001634 Optimizations["llvm.pow.f32"] = &Pow;
1635 Optimizations["llvm.pow.f64"] = &Pow;
1636 Optimizations["llvm.pow.f80"] = &Pow;
1637 Optimizations["llvm.pow.f128"] = &Pow;
1638 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001639 Optimizations["exp2l"] = &Exp2;
1640 Optimizations["exp2"] = &Exp2;
1641 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001642 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1643 Optimizations["llvm.exp2.f128"] = &Exp2;
1644 Optimizations["llvm.exp2.f80"] = &Exp2;
1645 Optimizations["llvm.exp2.f64"] = &Exp2;
1646 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001647
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001648#ifdef HAVE_FLOORF
1649 Optimizations["floor"] = &UnaryDoubleFP;
1650#endif
1651#ifdef HAVE_CEILF
1652 Optimizations["ceil"] = &UnaryDoubleFP;
1653#endif
1654#ifdef HAVE_ROUNDF
1655 Optimizations["round"] = &UnaryDoubleFP;
1656#endif
1657#ifdef HAVE_RINTF
1658 Optimizations["rint"] = &UnaryDoubleFP;
1659#endif
1660#ifdef HAVE_NEARBYINTF
1661 Optimizations["nearbyint"] = &UnaryDoubleFP;
1662#endif
1663
1664 // Integer Optimizations
1665 Optimizations["ffs"] = &FFS;
1666 Optimizations["ffsl"] = &FFS;
1667 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001668 Optimizations["abs"] = &Abs;
1669 Optimizations["labs"] = &Abs;
1670 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001671 Optimizations["isdigit"] = &IsDigit;
1672 Optimizations["isascii"] = &IsAscii;
1673 Optimizations["toascii"] = &ToAscii;
1674
1675 // Formatting and IO Optimizations
1676 Optimizations["sprintf"] = &SPrintF;
1677 Optimizations["printf"] = &PrintF;
1678 Optimizations["fwrite"] = &FWrite;
1679 Optimizations["fputs"] = &FPuts;
1680 Optimizations["fprintf"] = &FPrintF;
1681}
1682
1683
1684/// runOnFunction - Top level algorithm.
1685///
1686bool SimplifyLibCalls::runOnFunction(Function &F) {
1687 if (Optimizations.empty())
1688 InitOptimizations();
1689
Dan Gohmanf14d9192009-08-18 00:48:13 +00001690 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001691
Owen Andersone922c022009-07-22 00:24:57 +00001692 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001693
1694 bool Changed = false;
1695 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1696 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1697 // Ignore non-calls.
1698 CallInst *CI = dyn_cast<CallInst>(I++);
1699 if (!CI) continue;
1700
1701 // Ignore indirect calls and calls to non-external functions.
1702 Function *Callee = CI->getCalledFunction();
1703 if (Callee == 0 || !Callee->isDeclaration() ||
1704 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1705 continue;
1706
1707 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001708 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1709 if (!LCO) continue;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001710
1711 // Set the builder to the instruction after the call.
1712 Builder.SetInsertPoint(BB, I);
1713
1714 // Try to optimize this call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001715 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001716 if (Result == 0) continue;
1717
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001718 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1719 errs() << " into: " << *Result << "\n");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001720
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001721 // Something changed!
1722 Changed = true;
1723 ++NumSimplified;
1724
1725 // Inspect the instruction after the call (which was potentially just
1726 // added) next.
1727 I = CI; ++I;
1728
1729 if (CI != Result && !CI->use_empty()) {
1730 CI->replaceAllUsesWith(Result);
1731 if (!Result->hasName())
1732 Result->takeName(CI);
1733 }
1734 CI->eraseFromParent();
1735 }
1736 }
1737 return Changed;
1738}
1739
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001740// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001741
1742void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1743 if (!F.doesNotAccessMemory()) {
1744 F.setDoesNotAccessMemory();
1745 ++NumAnnotated;
1746 Modified = true;
1747 }
1748}
1749void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1750 if (!F.onlyReadsMemory()) {
1751 F.setOnlyReadsMemory();
1752 ++NumAnnotated;
1753 Modified = true;
1754 }
1755}
1756void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1757 if (!F.doesNotThrow()) {
1758 F.setDoesNotThrow();
1759 ++NumAnnotated;
1760 Modified = true;
1761 }
1762}
1763void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1764 if (!F.doesNotCapture(n)) {
1765 F.setDoesNotCapture(n);
1766 ++NumAnnotated;
1767 Modified = true;
1768 }
1769}
1770void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1771 if (!F.doesNotAlias(n)) {
1772 F.setDoesNotAlias(n);
1773 ++NumAnnotated;
1774 Modified = true;
1775 }
1776}
1777
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001778/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001779///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001780bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001781 Modified = false;
1782 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1783 Function &F = *I;
1784 if (!F.isDeclaration())
1785 continue;
1786
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001787 if (!F.hasName())
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001788 continue;
1789
1790 const FunctionType *FTy = F.getFunctionType();
1791
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001792 StringRef Name = F.getName();
1793 switch (Name[0]) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001794 case 's':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001795 if (Name == "strlen") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001796 if (FTy->getNumParams() != 1 ||
1797 !isa<PointerType>(FTy->getParamType(0)))
1798 continue;
1799 setOnlyReadsMemory(F);
1800 setDoesNotThrow(F);
1801 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001802 } else if (Name == "strcpy" ||
1803 Name == "stpcpy" ||
1804 Name == "strcat" ||
1805 Name == "strtol" ||
1806 Name == "strtod" ||
1807 Name == "strtof" ||
1808 Name == "strtoul" ||
1809 Name == "strtoll" ||
1810 Name == "strtold" ||
1811 Name == "strncat" ||
1812 Name == "strncpy" ||
1813 Name == "strtoull") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001814 if (FTy->getNumParams() < 2 ||
1815 !isa<PointerType>(FTy->getParamType(1)))
1816 continue;
1817 setDoesNotThrow(F);
1818 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001819 } else if (Name == "strxfrm") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001820 if (FTy->getNumParams() != 3 ||
1821 !isa<PointerType>(FTy->getParamType(0)) ||
1822 !isa<PointerType>(FTy->getParamType(1)))
1823 continue;
1824 setDoesNotThrow(F);
1825 setDoesNotCapture(F, 1);
1826 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001827 } else if (Name == "strcmp" ||
1828 Name == "strspn" ||
1829 Name == "strncmp" ||
1830 Name ==" strcspn" ||
1831 Name == "strcoll" ||
1832 Name == "strcasecmp" ||
1833 Name == "strncasecmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001834 if (FTy->getNumParams() < 2 ||
1835 !isa<PointerType>(FTy->getParamType(0)) ||
1836 !isa<PointerType>(FTy->getParamType(1)))
1837 continue;
1838 setOnlyReadsMemory(F);
1839 setDoesNotThrow(F);
1840 setDoesNotCapture(F, 1);
1841 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001842 } else if (Name == "strstr" ||
1843 Name == "strpbrk") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001844 if (FTy->getNumParams() != 2 ||
1845 !isa<PointerType>(FTy->getParamType(1)))
1846 continue;
1847 setOnlyReadsMemory(F);
1848 setDoesNotThrow(F);
1849 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001850 } else if (Name == "strtok" ||
1851 Name == "strtok_r") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001852 if (FTy->getNumParams() < 2 ||
1853 !isa<PointerType>(FTy->getParamType(1)))
1854 continue;
1855 setDoesNotThrow(F);
1856 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001857 } else if (Name == "scanf" ||
1858 Name == "setbuf" ||
1859 Name == "setvbuf") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001860 if (FTy->getNumParams() < 1 ||
1861 !isa<PointerType>(FTy->getParamType(0)))
1862 continue;
1863 setDoesNotThrow(F);
1864 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001865 } else if (Name == "strdup" ||
1866 Name == "strndup") {
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001867 if (FTy->getNumParams() < 1 ||
1868 !isa<PointerType>(FTy->getReturnType()) ||
1869 !isa<PointerType>(FTy->getParamType(0)))
1870 continue;
1871 setDoesNotThrow(F);
1872 setDoesNotAlias(F, 0);
1873 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001874 } else if (Name == "stat" ||
1875 Name == "sscanf" ||
1876 Name == "sprintf" ||
1877 Name == "statvfs") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001878 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001879 !isa<PointerType>(FTy->getParamType(0)) ||
1880 !isa<PointerType>(FTy->getParamType(1)))
1881 continue;
1882 setDoesNotThrow(F);
1883 setDoesNotCapture(F, 1);
1884 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001885 } else if (Name == "snprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001886 if (FTy->getNumParams() != 3 ||
1887 !isa<PointerType>(FTy->getParamType(0)) ||
1888 !isa<PointerType>(FTy->getParamType(2)))
1889 continue;
1890 setDoesNotThrow(F);
1891 setDoesNotCapture(F, 1);
1892 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001893 } else if (Name == "setitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001894 if (FTy->getNumParams() != 3 ||
1895 !isa<PointerType>(FTy->getParamType(1)) ||
1896 !isa<PointerType>(FTy->getParamType(2)))
1897 continue;
1898 setDoesNotThrow(F);
1899 setDoesNotCapture(F, 2);
1900 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001901 } else if (Name == "system") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001902 if (FTy->getNumParams() != 1 ||
1903 !isa<PointerType>(FTy->getParamType(0)))
1904 continue;
1905 // May throw; "system" is a valid pthread cancellation point.
1906 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001907 }
1908 break;
1909 case 'm':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001910 if (Name == "memcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001911 if (FTy->getNumParams() != 3 ||
1912 !isa<PointerType>(FTy->getParamType(0)) ||
1913 !isa<PointerType>(FTy->getParamType(1)))
1914 continue;
1915 setOnlyReadsMemory(F);
1916 setDoesNotThrow(F);
1917 setDoesNotCapture(F, 1);
1918 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001919 } else if (Name == "memchr" ||
1920 Name == "memrchr") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001921 if (FTy->getNumParams() != 3)
1922 continue;
1923 setOnlyReadsMemory(F);
1924 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001925 } else if (Name == "modf" ||
1926 Name == "modff" ||
1927 Name == "modfl" ||
1928 Name == "memcpy" ||
1929 Name == "memccpy" ||
1930 Name == "memmove") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001931 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001932 !isa<PointerType>(FTy->getParamType(1)))
1933 continue;
1934 setDoesNotThrow(F);
1935 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001936 } else if (Name == "memalign") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001937 if (!isa<PointerType>(FTy->getReturnType()))
1938 continue;
1939 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001940 } else if (Name == "mkdir" ||
1941 Name == "mktime") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001942 if (FTy->getNumParams() == 0 ||
1943 !isa<PointerType>(FTy->getParamType(0)))
1944 continue;
1945 setDoesNotThrow(F);
1946 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001947 }
1948 break;
1949 case 'r':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001950 if (Name == "realloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001951 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001952 !isa<PointerType>(FTy->getParamType(0)) ||
1953 !isa<PointerType>(FTy->getReturnType()))
1954 continue;
1955 setDoesNotThrow(F);
1956 setDoesNotAlias(F, 0);
1957 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001958 } else if (Name == "read") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001959 if (FTy->getNumParams() != 3 ||
1960 !isa<PointerType>(FTy->getParamType(1)))
1961 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001962 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001963 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001964 } else if (Name == "rmdir" ||
1965 Name == "rewind" ||
1966 Name == "remove" ||
1967 Name == "realpath") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001968 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001969 !isa<PointerType>(FTy->getParamType(0)))
1970 continue;
1971 setDoesNotThrow(F);
1972 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001973 } else if (Name == "rename" ||
1974 Name == "readlink") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001975 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001976 !isa<PointerType>(FTy->getParamType(0)) ||
1977 !isa<PointerType>(FTy->getParamType(1)))
1978 continue;
1979 setDoesNotThrow(F);
1980 setDoesNotCapture(F, 1);
1981 setDoesNotCapture(F, 2);
1982 }
1983 break;
1984 case 'w':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001985 if (Name == "write") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001986 if (FTy->getNumParams() != 3 ||
1987 !isa<PointerType>(FTy->getParamType(1)))
1988 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001989 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001990 setDoesNotCapture(F, 2);
1991 }
1992 break;
1993 case 'b':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001994 if (Name == "bcopy") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001995 if (FTy->getNumParams() != 3 ||
1996 !isa<PointerType>(FTy->getParamType(0)) ||
1997 !isa<PointerType>(FTy->getParamType(1)))
1998 continue;
1999 setDoesNotThrow(F);
2000 setDoesNotCapture(F, 1);
2001 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002002 } else if (Name == "bcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002003 if (FTy->getNumParams() != 3 ||
2004 !isa<PointerType>(FTy->getParamType(0)) ||
2005 !isa<PointerType>(FTy->getParamType(1)))
2006 continue;
2007 setDoesNotThrow(F);
2008 setOnlyReadsMemory(F);
2009 setDoesNotCapture(F, 1);
2010 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002011 } else if (Name == "bzero") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002012 if (FTy->getNumParams() != 2 ||
2013 !isa<PointerType>(FTy->getParamType(0)))
2014 continue;
2015 setDoesNotThrow(F);
2016 setDoesNotCapture(F, 1);
2017 }
2018 break;
2019 case 'c':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002020 if (Name == "calloc") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002021 if (FTy->getNumParams() != 2 ||
2022 !isa<PointerType>(FTy->getReturnType()))
2023 continue;
2024 setDoesNotThrow(F);
2025 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002026 } else if (Name == "chmod" ||
2027 Name == "chown" ||
2028 Name == "ctermid" ||
2029 Name == "clearerr" ||
2030 Name == "closedir") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002031 if (FTy->getNumParams() == 0 ||
2032 !isa<PointerType>(FTy->getParamType(0)))
2033 continue;
2034 setDoesNotThrow(F);
2035 setDoesNotCapture(F, 1);
2036 }
2037 break;
2038 case 'a':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002039 if (Name == "atoi" ||
2040 Name == "atol" ||
2041 Name == "atof" ||
2042 Name == "atoll") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002043 if (FTy->getNumParams() != 1 ||
2044 !isa<PointerType>(FTy->getParamType(0)))
2045 continue;
2046 setDoesNotThrow(F);
2047 setOnlyReadsMemory(F);
2048 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002049 } else if (Name == "access") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002050 if (FTy->getNumParams() != 2 ||
2051 !isa<PointerType>(FTy->getParamType(0)))
2052 continue;
2053 setDoesNotThrow(F);
2054 setDoesNotCapture(F, 1);
2055 }
2056 break;
2057 case 'f':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002058 if (Name == "fopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002059 if (FTy->getNumParams() != 2 ||
2060 !isa<PointerType>(FTy->getReturnType()) ||
2061 !isa<PointerType>(FTy->getParamType(0)) ||
2062 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002063 continue;
2064 setDoesNotThrow(F);
2065 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002066 setDoesNotCapture(F, 1);
2067 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002068 } else if (Name == "fdopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002069 if (FTy->getNumParams() != 2 ||
2070 !isa<PointerType>(FTy->getReturnType()) ||
2071 !isa<PointerType>(FTy->getParamType(1)))
2072 continue;
2073 setDoesNotThrow(F);
2074 setDoesNotAlias(F, 0);
2075 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002076 } else if (Name == "feof" ||
2077 Name == "free" ||
2078 Name == "fseek" ||
2079 Name == "ftell" ||
2080 Name == "fgetc" ||
2081 Name == "fseeko" ||
2082 Name == "ftello" ||
2083 Name == "fileno" ||
2084 Name == "fflush" ||
2085 Name == "fclose" ||
2086 Name == "fsetpos" ||
2087 Name == "flockfile" ||
2088 Name == "funlockfile" ||
2089 Name == "ftrylockfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002090 if (FTy->getNumParams() == 0 ||
2091 !isa<PointerType>(FTy->getParamType(0)))
2092 continue;
2093 setDoesNotThrow(F);
2094 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002095 } else if (Name == "ferror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002096 if (FTy->getNumParams() != 1 ||
2097 !isa<PointerType>(FTy->getParamType(0)))
2098 continue;
2099 setDoesNotThrow(F);
2100 setDoesNotCapture(F, 1);
2101 setOnlyReadsMemory(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002102 } else if (Name == "fputc" ||
2103 Name == "fstat" ||
2104 Name == "frexp" ||
2105 Name == "frexpf" ||
2106 Name == "frexpl" ||
2107 Name == "fstatvfs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002108 if (FTy->getNumParams() != 2 ||
2109 !isa<PointerType>(FTy->getParamType(1)))
2110 continue;
2111 setDoesNotThrow(F);
2112 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002113 } else if (Name == "fgets") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002114 if (FTy->getNumParams() != 3 ||
2115 !isa<PointerType>(FTy->getParamType(0)) ||
2116 !isa<PointerType>(FTy->getParamType(2)))
2117 continue;
2118 setDoesNotThrow(F);
2119 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002120 } else if (Name == "fread" ||
2121 Name == "fwrite") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002122 if (FTy->getNumParams() != 4 ||
2123 !isa<PointerType>(FTy->getParamType(0)) ||
2124 !isa<PointerType>(FTy->getParamType(3)))
2125 continue;
2126 setDoesNotThrow(F);
2127 setDoesNotCapture(F, 1);
2128 setDoesNotCapture(F, 4);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002129 } else if (Name == "fputs" ||
2130 Name == "fscanf" ||
2131 Name == "fprintf" ||
2132 Name == "fgetpos") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002133 if (FTy->getNumParams() < 2 ||
2134 !isa<PointerType>(FTy->getParamType(0)) ||
2135 !isa<PointerType>(FTy->getParamType(1)))
2136 continue;
2137 setDoesNotThrow(F);
2138 setDoesNotCapture(F, 1);
2139 setDoesNotCapture(F, 2);
2140 }
2141 break;
2142 case 'g':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002143 if (Name == "getc" ||
2144 Name == "getlogin_r" ||
2145 Name == "getc_unlocked") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002146 if (FTy->getNumParams() == 0 ||
2147 !isa<PointerType>(FTy->getParamType(0)))
2148 continue;
2149 setDoesNotThrow(F);
2150 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002151 } else if (Name == "getenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002152 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002153 !isa<PointerType>(FTy->getParamType(0)))
2154 continue;
2155 setDoesNotThrow(F);
2156 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002157 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002158 } else if (Name == "gets" ||
2159 Name == "getchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002160 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002161 } else if (Name == "getitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002162 if (FTy->getNumParams() != 2 ||
2163 !isa<PointerType>(FTy->getParamType(1)))
2164 continue;
2165 setDoesNotThrow(F);
2166 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002167 } else if (Name == "getpwnam") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002168 if (FTy->getNumParams() != 1 ||
2169 !isa<PointerType>(FTy->getParamType(0)))
2170 continue;
2171 setDoesNotThrow(F);
2172 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002173 }
2174 break;
2175 case 'u':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002176 if (Name == "ungetc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002177 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002178 !isa<PointerType>(FTy->getParamType(1)))
2179 continue;
2180 setDoesNotThrow(F);
2181 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002182 } else if (Name == "uname" ||
2183 Name == "unlink" ||
2184 Name == "unsetenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002185 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002186 !isa<PointerType>(FTy->getParamType(0)))
2187 continue;
2188 setDoesNotThrow(F);
2189 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002190 } else if (Name == "utime" ||
2191 Name == "utimes") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002192 if (FTy->getNumParams() != 2 ||
2193 !isa<PointerType>(FTy->getParamType(0)) ||
2194 !isa<PointerType>(FTy->getParamType(1)))
2195 continue;
2196 setDoesNotThrow(F);
2197 setDoesNotCapture(F, 1);
2198 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002199 }
2200 break;
2201 case 'p':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002202 if (Name == "putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002203 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002204 !isa<PointerType>(FTy->getParamType(1)))
2205 continue;
2206 setDoesNotThrow(F);
2207 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002208 } else if (Name == "puts" ||
2209 Name == "printf" ||
2210 Name == "perror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002211 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002212 !isa<PointerType>(FTy->getParamType(0)))
2213 continue;
2214 setDoesNotThrow(F);
2215 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002216 } else if (Name == "pread" ||
2217 Name == "pwrite") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002218 if (FTy->getNumParams() != 4 ||
2219 !isa<PointerType>(FTy->getParamType(1)))
2220 continue;
2221 // May throw; these are valid pthread cancellation points.
2222 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002223 } else if (Name == "putchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002224 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002225 } else if (Name == "popen") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002226 if (FTy->getNumParams() != 2 ||
2227 !isa<PointerType>(FTy->getReturnType()) ||
2228 !isa<PointerType>(FTy->getParamType(0)) ||
2229 !isa<PointerType>(FTy->getParamType(1)))
2230 continue;
2231 setDoesNotThrow(F);
2232 setDoesNotAlias(F, 0);
2233 setDoesNotCapture(F, 1);
2234 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002235 } else if (Name == "pclose") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002236 if (FTy->getNumParams() != 1 ||
2237 !isa<PointerType>(FTy->getParamType(0)))
2238 continue;
2239 setDoesNotThrow(F);
2240 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002241 }
2242 break;
2243 case 'v':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002244 if (Name == "vscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002245 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002246 !isa<PointerType>(FTy->getParamType(1)))
2247 continue;
2248 setDoesNotThrow(F);
2249 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002250 } else if (Name == "vsscanf" ||
2251 Name == "vfscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002252 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002253 !isa<PointerType>(FTy->getParamType(1)) ||
2254 !isa<PointerType>(FTy->getParamType(2)))
2255 continue;
2256 setDoesNotThrow(F);
2257 setDoesNotCapture(F, 1);
2258 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002259 } else if (Name == "valloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002260 if (!isa<PointerType>(FTy->getReturnType()))
2261 continue;
2262 setDoesNotThrow(F);
2263 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002264 } else if (Name == "vprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002265 if (FTy->getNumParams() != 2 ||
2266 !isa<PointerType>(FTy->getParamType(0)))
2267 continue;
2268 setDoesNotThrow(F);
2269 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002270 } else if (Name == "vfprintf" ||
2271 Name == "vsprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002272 if (FTy->getNumParams() != 3 ||
2273 !isa<PointerType>(FTy->getParamType(0)) ||
2274 !isa<PointerType>(FTy->getParamType(1)))
2275 continue;
2276 setDoesNotThrow(F);
2277 setDoesNotCapture(F, 1);
2278 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002279 } else if (Name == "vsnprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002280 if (FTy->getNumParams() != 4 ||
2281 !isa<PointerType>(FTy->getParamType(0)) ||
2282 !isa<PointerType>(FTy->getParamType(2)))
2283 continue;
2284 setDoesNotThrow(F);
2285 setDoesNotCapture(F, 1);
2286 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002287 }
2288 break;
2289 case 'o':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002290 if (Name == "open") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002291 if (FTy->getNumParams() < 2 ||
2292 !isa<PointerType>(FTy->getParamType(0)))
2293 continue;
2294 // May throw; "open" is a valid pthread cancellation point.
2295 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002296 } else if (Name == "opendir") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002297 if (FTy->getNumParams() != 1 ||
2298 !isa<PointerType>(FTy->getReturnType()) ||
2299 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002300 continue;
2301 setDoesNotThrow(F);
2302 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002303 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002304 }
2305 break;
2306 case 't':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002307 if (Name == "tmpfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002308 if (!isa<PointerType>(FTy->getReturnType()))
2309 continue;
2310 setDoesNotThrow(F);
2311 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002312 } else if (Name == "times") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002313 if (FTy->getNumParams() != 1 ||
2314 !isa<PointerType>(FTy->getParamType(0)))
2315 continue;
2316 setDoesNotThrow(F);
2317 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002318 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002319 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002320 case 'h':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002321 if (Name == "htonl" ||
2322 Name == "htons") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002323 setDoesNotThrow(F);
2324 setDoesNotAccessMemory(F);
2325 }
2326 break;
2327 case 'n':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002328 if (Name == "ntohl" ||
2329 Name == "ntohs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002330 setDoesNotThrow(F);
2331 setDoesNotAccessMemory(F);
2332 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002333 break;
2334 case 'l':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002335 if (Name == "lstat") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002336 if (FTy->getNumParams() != 2 ||
2337 !isa<PointerType>(FTy->getParamType(0)) ||
2338 !isa<PointerType>(FTy->getParamType(1)))
2339 continue;
2340 setDoesNotThrow(F);
2341 setDoesNotCapture(F, 1);
2342 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002343 } else if (Name == "lchown") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002344 if (FTy->getNumParams() != 3 ||
2345 !isa<PointerType>(FTy->getParamType(0)))
2346 continue;
2347 setDoesNotThrow(F);
2348 setDoesNotCapture(F, 1);
2349 }
2350 break;
2351 case 'q':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002352 if (Name == "qsort") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002353 if (FTy->getNumParams() != 4 ||
2354 !isa<PointerType>(FTy->getParamType(3)))
2355 continue;
2356 // May throw; places call through function pointer.
2357 setDoesNotCapture(F, 4);
2358 }
2359 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002360 case '_':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002361 if (Name == "__strdup" ||
2362 Name == "__strndup") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002363 if (FTy->getNumParams() < 1 ||
2364 !isa<PointerType>(FTy->getReturnType()) ||
2365 !isa<PointerType>(FTy->getParamType(0)))
2366 continue;
2367 setDoesNotThrow(F);
2368 setDoesNotAlias(F, 0);
2369 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002370 } else if (Name == "__strtok_r") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002371 if (FTy->getNumParams() != 3 ||
2372 !isa<PointerType>(FTy->getParamType(1)))
2373 continue;
2374 setDoesNotThrow(F);
2375 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002376 } else if (Name == "_IO_getc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002377 if (FTy->getNumParams() != 1 ||
2378 !isa<PointerType>(FTy->getParamType(0)))
2379 continue;
2380 setDoesNotThrow(F);
2381 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002382 } else if (Name == "_IO_putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002383 if (FTy->getNumParams() != 2 ||
2384 !isa<PointerType>(FTy->getParamType(1)))
2385 continue;
2386 setDoesNotThrow(F);
2387 setDoesNotCapture(F, 2);
2388 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002389 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002390 case 1:
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002391 if (Name == "\1__isoc99_scanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002392 if (FTy->getNumParams() < 1 ||
2393 !isa<PointerType>(FTy->getParamType(0)))
2394 continue;
2395 setDoesNotThrow(F);
2396 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002397 } else if (Name == "\1stat64" ||
2398 Name == "\1lstat64" ||
2399 Name == "\1statvfs64" ||
2400 Name == "\1__isoc99_sscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002401 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002402 !isa<PointerType>(FTy->getParamType(0)) ||
2403 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002404 continue;
2405 setDoesNotThrow(F);
2406 setDoesNotCapture(F, 1);
2407 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002408 } else if (Name == "\1fopen64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002409 if (FTy->getNumParams() != 2 ||
2410 !isa<PointerType>(FTy->getReturnType()) ||
2411 !isa<PointerType>(FTy->getParamType(0)) ||
2412 !isa<PointerType>(FTy->getParamType(1)))
2413 continue;
2414 setDoesNotThrow(F);
2415 setDoesNotAlias(F, 0);
2416 setDoesNotCapture(F, 1);
2417 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002418 } else if (Name == "\1fseeko64" ||
2419 Name == "\1ftello64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002420 if (FTy->getNumParams() == 0 ||
2421 !isa<PointerType>(FTy->getParamType(0)))
2422 continue;
2423 setDoesNotThrow(F);
2424 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002425 } else if (Name == "\1tmpfile64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002426 if (!isa<PointerType>(FTy->getReturnType()))
2427 continue;
2428 setDoesNotThrow(F);
2429 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002430 } else if (Name == "\1fstat64" ||
2431 Name == "\1fstatvfs64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002432 if (FTy->getNumParams() != 2 ||
2433 !isa<PointerType>(FTy->getParamType(1)))
2434 continue;
2435 setDoesNotThrow(F);
2436 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002437 } else if (Name == "\1open64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002438 if (FTy->getNumParams() < 2 ||
2439 !isa<PointerType>(FTy->getParamType(0)))
2440 continue;
2441 // May throw; "open" is a valid pthread cancellation point.
2442 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002443 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002444 break;
2445 }
2446 }
2447 return Modified;
2448}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002449
2450// TODO:
2451// Additional cases that we need to add to this file:
2452//
2453// cbrt:
2454// * cbrt(expN(X)) -> expN(x/3)
2455// * cbrt(sqrt(x)) -> pow(x,1/6)
2456// * cbrt(sqrt(x)) -> pow(x,1/9)
2457//
2458// cos, cosf, cosl:
2459// * cos(-x) -> cos(x)
2460//
2461// exp, expf, expl:
2462// * exp(log(x)) -> x
2463//
2464// log, logf, logl:
2465// * log(exp(x)) -> x
2466// * log(x**y) -> y*log(x)
2467// * log(exp(y)) -> y*log(e)
2468// * log(exp2(y)) -> y*log(2)
2469// * log(exp10(y)) -> y*log(10)
2470// * log(sqrt(x)) -> 0.5*log(x)
2471// * log(pow(x,y)) -> y*log(x)
2472//
2473// lround, lroundf, lroundl:
2474// * lround(cnst) -> cnst'
2475//
2476// memcmp:
2477// * memcmp(x,y,l) -> cnst
2478// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2479//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002480// pow, powf, powl:
2481// * pow(exp(x),y) -> exp(x*y)
2482// * pow(sqrt(x),y) -> pow(x,y*0.5)
2483// * pow(pow(x,y),z)-> pow(x,y*z)
2484//
2485// puts:
2486// * puts("") -> putchar("\n")
2487//
2488// round, roundf, roundl:
2489// * round(cnst) -> cnst'
2490//
2491// signbit:
2492// * signbit(cnst) -> cnst'
2493// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2494//
2495// sqrt, sqrtf, sqrtl:
2496// * sqrt(expN(x)) -> expN(x*0.5)
2497// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2498// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2499//
2500// stpcpy:
2501// * stpcpy(str, "literal") ->
2502// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2503// strrchr:
2504// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2505// (if c is a constant integer and s is a constant string)
2506// * strrchr(s1,0) -> strchr(s1,0)
2507//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002508// strpbrk:
2509// * strpbrk(s,a) -> offset_in_for(s,a)
2510// (if s and a are both constant strings)
2511// * strpbrk(s,"") -> 0
2512// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2513//
2514// strspn, strcspn:
2515// * strspn(s,a) -> const_int (if both args are constant)
2516// * strspn("",a) -> 0
2517// * strspn(s,"") -> 0
2518// * strcspn(s,a) -> const_int (if both args are constant)
2519// * strcspn("",a) -> 0
2520// * strcspn(s,"") -> strlen(a)
2521//
2522// strstr:
2523// * strstr(x,x) -> x
2524// * strstr(s1,s2) -> offset_of_s2_in(s1)
2525// (if s1 and s2 are constant strings)
2526//
2527// tan, tanf, tanl:
2528// * tan(atan(x)) -> x
2529//
2530// trunc, truncf, truncl:
2531// * trunc(cnst) -> cnst'
2532//
2533//