blob: 2ac980fbe6e8fde5fc47cbfe3e9b06bab39e82d6 [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
Eric Christopher7a61d702008-08-08 19:39:37 +000066 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000067 Caller = CI->getParent()->getParent();
68 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 Andersondebcb012009-07-29 22:17:13 +0000129 B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "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),
142 TD->getIntPtrType(),
Owen Andersondebcb012009-07-29 22:17:13 +0000143 PointerType::getUnqual(Type::Int8Ty),
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 Andersoneed707b2009-07-24 23:12:02 +0000162 ConstantInt::get(Type::Int32Ty, 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 Andersondebcb012009-07-29 22:17:13 +0000174 PointerType::getUnqual(Type::Int8Ty),
175 PointerType::getUnqual(Type::Int8Ty),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000176 Type::Int32Ty, TD->getIntPtrType(),
177 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),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000197 Type::Int32Ty,
Owen Andersondebcb012009-07-29 22:17:13 +0000198 PointerType::getUnqual(Type::Int8Ty),
199 PointerType::getUnqual(Type::Int8Ty),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000200 TD->getIntPtrType(), 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 Andersoneed707b2009-07-24 23:12:02 +0000218 Value *Align = ConstantInt::get(Type::Int32Ty, 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];
229 if (Op->getType() != Type::DoubleTy) {
230 // 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);
234 if (Op->getType() == Type::FloatTy)
235 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();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000257 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
258 Type::Int32Ty, NULL);
259 CallInst *CI = B.CreateCall(PutChar,
260 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
261 "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),
276 Type::Int32Ty,
Owen Andersondebcb012009-07-29 22:17:13 +0000277 PointerType::getUnqual(Type::Int8Ty),
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()))
294 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
295 Type::Int32Ty, File->getType(), NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000296 else
297 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
298 File->getType(), NULL);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000299 Char = B.CreateIntCast(Char, Type::Int32Ty, "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()))
Nick Lewycky225f7472009-02-15 22:47:25 +0000316 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
Owen Andersondebcb012009-07-29 22:17:13 +0000317 PointerType::getUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000318 File->getType(), NULL);
319 else
320 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
Owen Andersondebcb012009-07-29 22:17:13 +0000321 PointerType::getUnqual(Type::Int8Ty),
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),
341 TD->getIntPtrType(),
Owen Andersondebcb012009-07-29 22:17:13 +0000342 PointerType::getUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000343 TD->getIntPtrType(), TD->getIntPtrType(),
344 File->getType(), NULL);
345 else
346 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
Owen Andersondebcb012009-07-29 22:17:13 +0000347 PointerType::getUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000348 TD->getIntPtrType(), TD->getIntPtrType(),
349 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000350 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Andersoneed707b2009-07-24 23:12:02 +0000351 ConstantInt::get(TD->getIntPtrType(), 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));
441 if (!GV || !GV->isConstant() || !GV->hasInitializer())
442 return 0;
443 Constant *GlobalInit = GV->getInitializer();
444
445 // Handle the ConstantAggregateZero case, which is a degenerate case. The
446 // initializer is constant zero so the length of the string must be zero.
447 if (isa<ConstantAggregateZero>(GlobalInit))
448 return 1; // Len = 0 offset by 1.
449
450 // Must be a Constant Array
451 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
452 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
453 return false;
454
455 // Get the number of elements in the array
456 uint64_t NumElts = Array->getType()->getNumElements();
457
458 // Traverse the constant array from StartIdx (derived above) which is
459 // the place the GEP refers to in the array.
460 for (unsigned i = StartIdx; i != NumElts; ++i) {
461 Constant *Elt = Array->getOperand(i);
462 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
463 if (!CI) // This array isn't suitable, non-int initializer.
464 return 0;
465 if (CI->isZero())
466 return i-StartIdx+1; // We found end of string, success!
467 }
468
469 return 0; // The array isn't null terminated, conservatively return 'unknown'.
470}
471
472/// GetStringLength - If we can compute the length of the string pointed to by
473/// the specified pointer, return 'len+1'. If we can't, return 0.
474static uint64_t GetStringLength(Value *V) {
475 if (!isa<PointerType>(V->getType())) return 0;
476
477 SmallPtrSet<PHINode*, 32> PHIs;
478 uint64_t Len = GetStringLengthH(V, PHIs);
479 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
480 // an empty string as a length.
481 return Len == ~0ULL ? 1 : Len;
482}
483
484/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
485/// value is equal or not-equal to zero.
486static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
487 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
488 UI != E; ++UI) {
489 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
490 if (IC->isEquality())
491 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
492 if (C->isNullValue())
493 continue;
494 // Unknown instruction.
495 return false;
496 }
497 return true;
498}
499
500//===----------------------------------------------------------------------===//
501// Miscellaneous LibCall Optimizations
502//===----------------------------------------------------------------------===//
503
Bill Wendlingac178222008-05-05 21:37:59 +0000504namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000505//===---------------------------------------===//
506// 'exit' Optimizations
507
508/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
509struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000510 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000511 // Verify we have a reasonable prototype for exit.
512 if (Callee->arg_size() == 0 || !CI->use_empty())
513 return 0;
514
515 // Verify the caller is main, and that the result type of main matches the
516 // argument type of exit.
Daniel Dunbar03d76512009-07-25 23:55:21 +0000517 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000518 Caller->getReturnType() != CI->getOperand(1)->getType())
519 return 0;
520
521 TerminatorInst *OldTI = CI->getParent()->getTerminator();
Daniel Dunbar473955f2009-07-29 22:00:43 +0000522
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000523 // Drop all successor phi node entries.
524 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
525 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
Nick Lewycky0efa9212009-07-29 05:17:50 +0000526
Daniel Dunbar473955f2009-07-29 22:00:43 +0000527 // Remove all instructions after the exit.
528 BasicBlock::iterator Dead = CI, E = OldTI; ++Dead;
529 while (Dead != E) {
530 BasicBlock::iterator Next = next(Dead);
531 if (Dead->getType() != Type::VoidTy)
532 Dead->replaceAllUsesWith(UndefValue::get(Dead->getType()));
533 Dead->eraseFromParent();
534 Dead = Next;
535 }
536
537 // Insert a return instruction.
538 OldTI->eraseFromParent();
539 B.SetInsertPoint(B.GetInsertBlock());
Nick Lewycky0efa9212009-07-29 05:17:50 +0000540 B.CreateRet(CI->getOperand(1));
541
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000542 return CI;
543 }
544};
545
546//===----------------------------------------------------------------------===//
547// String and Memory LibCall Optimizations
548//===----------------------------------------------------------------------===//
549
550//===---------------------------------------===//
551// 'strcat' Optimizations
552
553struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000554 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000555 // Verify the "strcat" function prototype.
556 const FunctionType *FT = Callee->getFunctionType();
557 if (FT->getNumParams() != 2 ||
Owen Andersondebcb012009-07-29 22:17:13 +0000558 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000559 FT->getParamType(0) != FT->getReturnType() ||
560 FT->getParamType(1) != FT->getReturnType())
561 return 0;
562
563 // Extract some information from the instruction
564 Value *Dst = CI->getOperand(1);
565 Value *Src = CI->getOperand(2);
566
567 // See if we can get the length of the input string.
568 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000569 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000570 --Len; // Unbias length.
571
572 // Handle the simple, do-nothing case: strcat(x, "") -> x
573 if (Len == 0)
574 return Dst;
575
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000576 EmitStrLenMemCpy(Src, Dst, Len, B);
577 return Dst;
578 }
579
580 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000581 // We need to find the end of the destination string. That's where the
582 // memory is to be moved to. We just generate a call to strlen.
583 Value *DstLen = EmitStrLen(Dst, B);
584
585 // Now that we have the destination's length, we must index into the
586 // destination's pointer to get the actual memcpy destination (end of
587 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000588 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000589
590 // We have enough information to now generate the memcpy call to do the
591 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000592 EmitMemCpy(CpyDst, Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000593 ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000594 }
595};
596
597//===---------------------------------------===//
598// 'strncat' Optimizations
599
600struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
601 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
602 // Verify the "strncat" function prototype.
603 const FunctionType *FT = Callee->getFunctionType();
604 if (FT->getNumParams() != 3 ||
Owen Andersondebcb012009-07-29 22:17:13 +0000605 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000606 FT->getParamType(0) != FT->getReturnType() ||
607 FT->getParamType(1) != FT->getReturnType() ||
608 !isa<IntegerType>(FT->getParamType(2)))
609 return 0;
610
611 // Extract some information from the instruction
612 Value *Dst = CI->getOperand(1);
613 Value *Src = CI->getOperand(2);
614 uint64_t Len;
615
616 // We don't do anything if length is not constant
617 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
618 Len = LengthArg->getZExtValue();
619 else
620 return 0;
621
622 // See if we can get the length of the input string.
623 uint64_t SrcLen = GetStringLength(Src);
624 if (SrcLen == 0) return 0;
625 --SrcLen; // Unbias length.
626
627 // Handle the simple, do-nothing cases:
628 // strncat(x, "", c) -> x
629 // strncat(x, c, 0) -> x
630 if (SrcLen == 0 || Len == 0) return Dst;
631
632 // We don't optimize this case
633 if (Len < SrcLen) return 0;
634
635 // strncat(x, s, c) -> strcat(x, s)
636 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000637 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000638 return Dst;
639 }
640};
641
642//===---------------------------------------===//
643// 'strchr' Optimizations
644
645struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000646 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000647 // Verify the "strchr" function prototype.
648 const FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 ||
Owen Andersondebcb012009-07-29 22:17:13 +0000650 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000651 FT->getParamType(0) != FT->getReturnType())
652 return 0;
653
654 Value *SrcStr = CI->getOperand(1);
655
656 // If the second operand is non-constant, see if we can compute the length
657 // of the input string and turn this into memchr.
658 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
659 if (CharC == 0) {
660 uint64_t Len = GetStringLength(SrcStr);
661 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
662 return 0;
663
664 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Andersoneed707b2009-07-24 23:12:02 +0000665 ConstantInt::get(TD->getIntPtrType(), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000666 }
667
668 // Otherwise, the character is a constant, see if the first argument is
669 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000670 std::string Str;
671 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000672 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000673
674 // strchr can find the nul character.
675 Str += '\0';
676 char CharValue = CharC->getSExtValue();
677
678 // Compute the offset.
679 uint64_t i = 0;
680 while (1) {
681 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersona7235ea2009-07-31 20:28:14 +0000682 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000683 // Did we find our match?
684 if (Str[i] == CharValue)
685 break;
686 ++i;
687 }
688
689 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Andersoneed707b2009-07-24 23:12:02 +0000690 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000691 return B.CreateGEP(SrcStr, Idx, "strchr");
692 }
693};
694
695//===---------------------------------------===//
696// 'strcmp' Optimizations
697
698struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000699 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000700 // Verify the "strcmp" function prototype.
701 const FunctionType *FT = Callee->getFunctionType();
702 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
703 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersondebcb012009-07-29 22:17:13 +0000704 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000705 return 0;
706
707 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
708 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000709 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000710
Bill Wendling0582ae92009-03-13 04:39:26 +0000711 std::string Str1, Str2;
712 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
713 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
714
715 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000716 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
717
Bill Wendling0582ae92009-03-13 04:39:26 +0000718 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000719 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
720
721 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000722 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000723 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000724 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000725
726 // strcmp(P, "x") -> memcmp(P, "x", 2)
727 uint64_t Len1 = GetStringLength(Str1P);
728 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000729 if (Len1 && Len2) {
Nick Lewycky13a09e22008-12-21 00:19:21 +0000730 return EmitMemCmp(Str1P, Str2P,
Owen Andersoneed707b2009-07-24 23:12:02 +0000731 ConstantInt::get(TD->getIntPtrType(),
Chris Lattner849832c2009-06-19 04:17:36 +0000732 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000733 }
734
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000735 return 0;
736 }
737};
738
739//===---------------------------------------===//
740// 'strncmp' Optimizations
741
742struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000743 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000744 // Verify the "strncmp" function prototype.
745 const FunctionType *FT = Callee->getFunctionType();
746 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
747 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersondebcb012009-07-29 22:17:13 +0000748 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000749 !isa<IntegerType>(FT->getParamType(2)))
750 return 0;
751
752 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
753 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000754 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000755
756 // Get the length argument if it is constant.
757 uint64_t Length;
758 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
759 Length = LengthArg->getZExtValue();
760 else
761 return 0;
762
763 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000764 return ConstantInt::get(CI->getType(), 0);
Bill Wendling0582ae92009-03-13 04:39:26 +0000765
766 std::string Str1, Str2;
767 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
768 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
769
770 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000771 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
772
Bill Wendling0582ae92009-03-13 04:39:26 +0000773 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000774 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
775
776 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000777 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000778 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000779 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000780 return 0;
781 }
782};
783
784
785//===---------------------------------------===//
786// 'strcpy' Optimizations
787
788struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000789 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000790 // Verify the "strcpy" function prototype.
791 const FunctionType *FT = Callee->getFunctionType();
792 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
793 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersondebcb012009-07-29 22:17:13 +0000794 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000795 return 0;
796
797 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
798 if (Dst == Src) // strcpy(x,x) -> x
799 return Src;
800
801 // See if we can get the length of the input string.
802 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000803 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000804
805 // We have enough information to now generate the memcpy call to do the
806 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000807 EmitMemCpy(Dst, Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000808 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000809 return Dst;
810 }
811};
812
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000813//===---------------------------------------===//
814// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000815
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000816struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
817 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
818 const FunctionType *FT = Callee->getFunctionType();
819 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
820 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersondebcb012009-07-29 22:17:13 +0000821 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000822 !isa<IntegerType>(FT->getParamType(2)))
823 return 0;
824
825 Value *Dst = CI->getOperand(1);
826 Value *Src = CI->getOperand(2);
827 Value *LenOp = CI->getOperand(3);
828
829 // See if we can get the length of the input string.
830 uint64_t SrcLen = GetStringLength(Src);
831 if (SrcLen == 0) return 0;
832 --SrcLen;
833
834 if (SrcLen == 0) {
835 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000836 EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000837 return Dst;
838 }
839
840 uint64_t Len;
841 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
842 Len = LengthArg->getZExtValue();
843 else
844 return 0;
845
846 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
847
848 // Let strncpy handle the zero padding
849 if (Len > SrcLen+1) return 0;
850
851 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000852 EmitMemCpy(Dst, Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000853 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000854
855 return Dst;
856 }
857};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000858
859//===---------------------------------------===//
860// 'strlen' Optimizations
861
862struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000863 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000864 const FunctionType *FT = Callee->getFunctionType();
865 if (FT->getNumParams() != 1 ||
Owen Andersondebcb012009-07-29 22:17:13 +0000866 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000867 !isa<IntegerType>(FT->getReturnType()))
868 return 0;
869
870 Value *Src = CI->getOperand(1);
871
872 // Constant folding: strlen("xyz") -> 3
873 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000874 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000875
876 // Handle strlen(p) != 0.
877 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
878
879 // strlen(x) != 0 --> *x != 0
880 // strlen(x) == 0 --> *x == 0
881 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
882 }
883};
884
885//===---------------------------------------===//
Nick Lewycky4c498412009-02-13 15:31:46 +0000886// 'strto*' Optimizations
887
888struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
889 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
890 const FunctionType *FT = Callee->getFunctionType();
891 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
892 !isa<PointerType>(FT->getParamType(0)) ||
893 !isa<PointerType>(FT->getParamType(1)))
894 return 0;
895
896 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000897 if (isa<ConstantPointerNull>(EndPtr)) {
898 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000899 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000900 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000901
902 return 0;
903 }
904};
905
906
907//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000908// 'memcmp' Optimizations
909
910struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000911 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000912 const FunctionType *FT = Callee->getFunctionType();
913 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
914 !isa<PointerType>(FT->getParamType(1)) ||
915 FT->getReturnType() != Type::Int32Ty)
916 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000917
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000918 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000919
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000920 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000921 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000922
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000923 // Make sure we have a constant length.
924 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000925 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000926 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000927
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000928 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000929 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000930
931 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
932 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
933 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +0000934 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000935 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000936
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000937 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
938 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
939 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Owen Andersondebcb012009-07-29 22:17:13 +0000940 const Type *PTy = PointerType::getUnqual(Len == 2 ?
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000941 Type::Int16Ty : Type::Int32Ty);
942 LHS = B.CreateBitCast(LHS, PTy, "tmp");
943 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000944 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
945 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
946 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
947 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
948 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000949
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000950 return 0;
951 }
952};
953
954//===---------------------------------------===//
955// 'memcpy' Optimizations
956
957struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000958 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000959 const FunctionType *FT = Callee->getFunctionType();
960 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
961 !isa<PointerType>(FT->getParamType(0)) ||
962 !isa<PointerType>(FT->getParamType(1)) ||
963 FT->getParamType(2) != TD->getIntPtrType())
964 return 0;
965
966 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
967 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
968 return CI->getOperand(1);
969 }
970};
971
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000972//===---------------------------------------===//
973// 'memmove' Optimizations
974
975struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
976 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
977 const FunctionType *FT = Callee->getFunctionType();
978 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
979 !isa<PointerType>(FT->getParamType(0)) ||
980 !isa<PointerType>(FT->getParamType(1)) ||
981 FT->getParamType(2) != TD->getIntPtrType())
982 return 0;
983
984 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
985 Module *M = Caller->getParent();
986 Intrinsic::ID IID = Intrinsic::memmove;
987 const Type *Tys[1];
988 Tys[0] = TD->getIntPtrType();
989 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
990 Value *Dst = CastToCStr(CI->getOperand(1), B);
991 Value *Src = CastToCStr(CI->getOperand(2), B);
992 Value *Size = CI->getOperand(3);
Owen Andersoneed707b2009-07-24 23:12:02 +0000993 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000994 B.CreateCall4(MemMove, Dst, Src, Size, Align);
995 return CI->getOperand(1);
996 }
997};
998
999//===---------------------------------------===//
1000// 'memset' Optimizations
1001
1002struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
1003 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1004 const FunctionType *FT = Callee->getFunctionType();
1005 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1006 !isa<PointerType>(FT->getParamType(0)) ||
Eli Friedman62bb4132009-07-18 08:34:51 +00001007 !isa<IntegerType>(FT->getParamType(1)) ||
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001008 FT->getParamType(2) != TD->getIntPtrType())
1009 return 0;
1010
1011 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Eli Friedman62bb4132009-07-18 08:34:51 +00001012 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::Int8Ty, false);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001013 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001014 return CI->getOperand(1);
1015 }
1016};
1017
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001018//===----------------------------------------------------------------------===//
1019// Math Library Optimizations
1020//===----------------------------------------------------------------------===//
1021
1022//===---------------------------------------===//
1023// 'pow*' Optimizations
1024
1025struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001026 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001027 const FunctionType *FT = Callee->getFunctionType();
1028 // Just make sure this has 2 arguments of the same FP type, which match the
1029 // result type.
1030 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1031 FT->getParamType(0) != FT->getParamType(1) ||
1032 !FT->getParamType(0)->isFloatingPoint())
1033 return 0;
1034
1035 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1036 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1037 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1038 return Op1C;
1039 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1040 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1041 }
1042
1043 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1044 if (Op2C == 0) return 0;
1045
1046 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001047 return ConstantFP::get(CI->getType(), 1.0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001048
1049 if (Op2C->isExactlyValue(0.5)) {
1050 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1051 // 'unsafe' math optimizations are allowed.
1052 // x pow(x, 0.5) sqrt(x)
1053 // ---------------------------------------------
1054 // -0.0 +0.0 -0.0
1055 // -inf +inf NaN
1056#if 0
1057 // pow(x, 0.5) -> sqrt(x)
1058 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1059#endif
1060 }
1061
1062 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1063 return Op1;
1064 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001065 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001066 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001067 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001068 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001069 return 0;
1070 }
1071};
1072
1073//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001074// 'exp2' Optimizations
1075
1076struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001077 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001078 const FunctionType *FT = Callee->getFunctionType();
1079 // Just make sure this has 1 argument of FP type, which matches the
1080 // result type.
1081 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1082 !FT->getParamType(0)->isFloatingPoint())
1083 return 0;
1084
1085 Value *Op = CI->getOperand(1);
1086 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1087 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1088 Value *LdExpArg = 0;
1089 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1090 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1091 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1092 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1093 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1094 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1095 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001096
Chris Lattnere818f772008-05-02 18:43:35 +00001097 if (LdExpArg) {
1098 const char *Name;
1099 if (Op->getType() == Type::FloatTy)
1100 Name = "ldexpf";
1101 else if (Op->getType() == Type::DoubleTy)
1102 Name = "ldexp";
1103 else
1104 Name = "ldexpl";
1105
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001106 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnere818f772008-05-02 18:43:35 +00001107 if (Op->getType() != Type::FloatTy)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001108 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001109
1110 Module *M = Caller->getParent();
1111 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1112 Op->getType(), Type::Int32Ty,NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001113 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1114 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1115 CI->setCallingConv(F->getCallingConv());
1116
1117 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001118 }
1119 return 0;
1120 }
1121};
Chris Lattnere818f772008-05-02 18:43:35 +00001122
1123//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001124// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1125
1126struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001127 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001128 const FunctionType *FT = Callee->getFunctionType();
1129 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1130 FT->getParamType(0) != Type::DoubleTy)
1131 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001132
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001133 // If this is something like 'floor((double)floatval)', convert to floorf.
1134 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1135 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1136 return 0;
1137
1138 // floor((double)floatval) -> (double)floorf(floatval)
1139 Value *V = Cast->getOperand(0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001140 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001141 return B.CreateFPExt(V, Type::DoubleTy);
1142 }
1143};
1144
1145//===----------------------------------------------------------------------===//
1146// Integer Optimizations
1147//===----------------------------------------------------------------------===//
1148
1149//===---------------------------------------===//
1150// 'ffs*' Optimizations
1151
1152struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001153 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001154 const FunctionType *FT = Callee->getFunctionType();
1155 // Just make sure this has 2 arguments of the same FP type, which match the
1156 // result type.
1157 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1158 !isa<IntegerType>(FT->getParamType(0)))
1159 return 0;
1160
1161 Value *Op = CI->getOperand(1);
1162
1163 // Constant fold.
1164 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1165 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001166 return Constant::getNullValue(CI->getType());
Owen Andersoneed707b2009-07-24 23:12:02 +00001167 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001168 CI->getValue().countTrailingZeros()+1);
1169 }
1170
1171 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1172 const Type *ArgType = Op->getType();
1173 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1174 Intrinsic::cttz, &ArgType, 1);
1175 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +00001176 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001177 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1178
Owen Andersona7235ea2009-07-31 20:28:14 +00001179 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Owen Andersoneed707b2009-07-24 23:12:02 +00001180 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001181 }
1182};
1183
1184//===---------------------------------------===//
1185// 'isdigit' Optimizations
1186
1187struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001188 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001189 const FunctionType *FT = Callee->getFunctionType();
1190 // We require integer(i32)
1191 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1192 FT->getParamType(0) != Type::Int32Ty)
1193 return 0;
1194
1195 // isdigit(c) -> (c-'0') <u 10
1196 Value *Op = CI->getOperand(1);
Owen Andersoneed707b2009-07-24 23:12:02 +00001197 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001198 "isdigittmp");
Owen Andersoneed707b2009-07-24 23:12:02 +00001199 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001200 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001201 return B.CreateZExt(Op, CI->getType());
1202 }
1203};
1204
1205//===---------------------------------------===//
1206// 'isascii' Optimizations
1207
1208struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001209 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 const FunctionType *FT = Callee->getFunctionType();
1211 // We require integer(i32)
1212 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1213 FT->getParamType(0) != Type::Int32Ty)
1214 return 0;
1215
1216 // isascii(c) -> c <u 128
1217 Value *Op = CI->getOperand(1);
Owen Andersoneed707b2009-07-24 23:12:02 +00001218 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001219 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001220 return B.CreateZExt(Op, CI->getType());
1221 }
1222};
Chris Lattner313f0e62008-06-09 08:26:51 +00001223
1224//===---------------------------------------===//
1225// 'abs', 'labs', 'llabs' Optimizations
1226
1227struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001228 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001229 const FunctionType *FT = Callee->getFunctionType();
1230 // We require integer(integer) where the types agree.
1231 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1232 FT->getParamType(0) != FT->getReturnType())
1233 return 0;
1234
1235 // abs(x) -> x >s -1 ? x : -x
1236 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001237 Value *Pos = B.CreateICmpSGT(Op,
Owen Andersona7235ea2009-07-31 20:28:14 +00001238 Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001239 "ispos");
1240 Value *Neg = B.CreateNeg(Op, "neg");
1241 return B.CreateSelect(Pos, Op, Neg);
1242 }
1243};
1244
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001245
1246//===---------------------------------------===//
1247// 'toascii' Optimizations
1248
1249struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001250 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001251 const FunctionType *FT = Callee->getFunctionType();
1252 // We require i32(i32)
1253 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1254 FT->getParamType(0) != Type::Int32Ty)
1255 return 0;
1256
1257 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001258 return B.CreateAnd(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001259 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001260 }
1261};
1262
1263//===----------------------------------------------------------------------===//
1264// Formatting and IO Optimizations
1265//===----------------------------------------------------------------------===//
1266
1267//===---------------------------------------===//
1268// 'printf' Optimizations
1269
1270struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001271 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001272 // Require one fixed pointer argument and an integer/void result.
1273 const FunctionType *FT = Callee->getFunctionType();
1274 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1275 !(isa<IntegerType>(FT->getReturnType()) ||
1276 FT->getReturnType() == Type::VoidTy))
1277 return 0;
1278
1279 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001280 std::string FormatStr;
1281 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1282 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001283
1284 // Empty format string -> noop.
1285 if (FormatStr.empty()) // Tolerate printf's declared void.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001286 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001287 ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001288
1289 // printf("x") -> putchar('x'), even for '%'.
1290 if (FormatStr.size() == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001291 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001292 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001293 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001294 }
1295
1296 // printf("foo\n") --> puts("foo")
1297 if (FormatStr[FormatStr.size()-1] == '\n' &&
1298 FormatStr.find('%') == std::string::npos) { // no format characters.
1299 // Create a string literal with no \n on it. We expect the constant merge
1300 // pass to be run after this pass, to merge duplicate strings.
1301 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1fd70962009-07-28 18:32:17 +00001302 Constant *C = ConstantArray::get(FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001303 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1304 GlobalVariable::InternalLinkage, C, "str");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001305 EmitPutS(C, B);
1306 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001307 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001308 }
1309
1310 // Optimize specific format strings.
1311 // printf("%c", chr) --> putchar(*(i8*)dst)
1312 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1313 isa<IntegerType>(CI->getOperand(2)->getType())) {
1314 EmitPutChar(CI->getOperand(2), B);
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(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001317 }
1318
1319 // printf("%s\n", str) --> puts(str)
1320 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1321 isa<PointerType>(CI->getOperand(2)->getType()) &&
1322 CI->use_empty()) {
1323 EmitPutS(CI->getOperand(2), B);
1324 return CI;
1325 }
1326 return 0;
1327 }
1328};
1329
1330//===---------------------------------------===//
1331// 'sprintf' Optimizations
1332
1333struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001334 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001335 // Require two fixed pointer arguments and an integer result.
1336 const FunctionType *FT = Callee->getFunctionType();
1337 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1338 !isa<PointerType>(FT->getParamType(1)) ||
1339 !isa<IntegerType>(FT->getReturnType()))
1340 return 0;
1341
1342 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001343 std::string FormatStr;
1344 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1345 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001346
1347 // If we just have a format string (nothing else crazy) transform it.
1348 if (CI->getNumOperands() == 3) {
1349 // Make sure there's no % in the constant array. We could try to handle
1350 // %% -> % in the future if we cared.
1351 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1352 if (FormatStr[i] == '%')
1353 return 0; // we found a format specifier, bail out.
1354
1355 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1356 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001357 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1358 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001359 }
1360
1361 // The remaining optimizations require the format string to be "%s" or "%c"
1362 // and have an extra operand.
1363 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1364 return 0;
1365
1366 // Decode the second character of the format string.
1367 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001368 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001369 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1370 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001371 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1372 B.CreateStore(V, Ptr);
Owen Andersoneed707b2009-07-24 23:12:02 +00001373 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
Owen Andersona7235ea2009-07-31 20:28:14 +00001374 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001375
Owen Andersoneed707b2009-07-24 23:12:02 +00001376 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001377 }
1378
1379 if (FormatStr[1] == 's') {
1380 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1381 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1382
1383 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001384 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001385 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001386 "leninc");
1387 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1388
1389 // The sprintf result is the unincremented number of bytes in the string.
1390 return B.CreateIntCast(Len, CI->getType(), false);
1391 }
1392 return 0;
1393 }
1394};
1395
1396//===---------------------------------------===//
1397// 'fwrite' Optimizations
1398
1399struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001400 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001401 // Require a pointer, an integer, an integer, a pointer, returning integer.
1402 const FunctionType *FT = Callee->getFunctionType();
1403 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1404 !isa<IntegerType>(FT->getParamType(1)) ||
1405 !isa<IntegerType>(FT->getParamType(2)) ||
1406 !isa<PointerType>(FT->getParamType(3)) ||
1407 !isa<IntegerType>(FT->getReturnType()))
1408 return 0;
1409
1410 // Get the element size and count.
1411 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1412 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1413 if (!SizeC || !CountC) return 0;
1414 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1415
1416 // If this is writing zero records, remove the call (it's a noop).
1417 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001418 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001419
1420 // If this is writing one byte, turn it into fputc.
1421 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1422 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1423 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001424 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001425 }
1426
1427 return 0;
1428 }
1429};
1430
1431//===---------------------------------------===//
1432// 'fputs' Optimizations
1433
1434struct VISIBILITY_HIDDEN FPutsOpt : 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 two pointers. Also, we can't optimize if return value is used.
1437 const FunctionType *FT = Callee->getFunctionType();
1438 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1439 !isa<PointerType>(FT->getParamType(1)) ||
1440 !CI->use_empty())
1441 return 0;
1442
1443 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1444 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001445 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001446 EmitFWrite(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001447 ConstantInt::get(TD->getIntPtrType(), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001448 CI->getOperand(2), B);
1449 return CI; // Known to have no uses (see above).
1450 }
1451};
1452
1453//===---------------------------------------===//
1454// 'fprintf' Optimizations
1455
1456struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001457 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001458 // Require two fixed paramters as pointers and integer result.
1459 const FunctionType *FT = Callee->getFunctionType();
1460 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1461 !isa<PointerType>(FT->getParamType(1)) ||
1462 !isa<IntegerType>(FT->getReturnType()))
1463 return 0;
1464
1465 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001466 std::string FormatStr;
1467 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1468 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001469
1470 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1471 if (CI->getNumOperands() == 3) {
1472 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1473 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001474 return 0; // We found a format specifier.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001475
Owen Andersoneed707b2009-07-24 23:12:02 +00001476 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001477 FormatStr.size()),
1478 CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001479 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001480 }
1481
1482 // The remaining optimizations require the format string to be "%s" or "%c"
1483 // and have an extra operand.
1484 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1485 return 0;
1486
1487 // Decode the second character of the format string.
1488 if (FormatStr[1] == 'c') {
1489 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1490 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1491 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001492 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001493 }
1494
1495 if (FormatStr[1] == 's') {
1496 // fprintf(F, "%s", str) -> fputs(str, F)
1497 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1498 return 0;
1499 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1500 return CI;
1501 }
1502 return 0;
1503 }
1504};
1505
Bill Wendlingac178222008-05-05 21:37:59 +00001506} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001507
1508//===----------------------------------------------------------------------===//
1509// SimplifyLibCalls Pass Implementation
1510//===----------------------------------------------------------------------===//
1511
1512namespace {
1513 /// This pass optimizes well known library functions from libc and libm.
1514 ///
1515 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1516 StringMap<LibCallOptimization*> Optimizations;
1517 // Miscellaneous LibCall Optimizations
1518 ExitOpt Exit;
1519 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001520 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1521 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1522 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1523 MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001524 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001525 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001526 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001527 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1528 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001529 // Formatting and IO Optimizations
1530 SPrintFOpt SPrintF; PrintFOpt PrintF;
1531 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001532
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001533 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001534 public:
1535 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001536 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001537
1538 void InitOptimizations();
1539 bool runOnFunction(Function &F);
1540
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001541 void setDoesNotAccessMemory(Function &F);
1542 void setOnlyReadsMemory(Function &F);
1543 void setDoesNotThrow(Function &F);
1544 void setDoesNotCapture(Function &F, unsigned n);
1545 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001546 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001547
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001548 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1549 AU.addRequired<TargetData>();
1550 }
1551 };
1552 char SimplifyLibCalls::ID = 0;
1553} // end anonymous namespace.
1554
1555static RegisterPass<SimplifyLibCalls>
1556X("simplify-libcalls", "Simplify well-known library calls");
1557
1558// Public interface to the Simplify LibCalls pass.
1559FunctionPass *llvm::createSimplifyLibCallsPass() {
1560 return new SimplifyLibCalls();
1561}
1562
1563/// Optimizations - Populate the Optimizations map with all the optimizations
1564/// we know.
1565void SimplifyLibCalls::InitOptimizations() {
1566 // Miscellaneous LibCall Optimizations
1567 Optimizations["exit"] = &Exit;
1568
1569 // String and Memory LibCall Optimizations
1570 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001571 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001572 Optimizations["strchr"] = &StrChr;
1573 Optimizations["strcmp"] = &StrCmp;
1574 Optimizations["strncmp"] = &StrNCmp;
1575 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001576 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001577 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001578 Optimizations["strtol"] = &StrTo;
1579 Optimizations["strtod"] = &StrTo;
1580 Optimizations["strtof"] = &StrTo;
1581 Optimizations["strtoul"] = &StrTo;
1582 Optimizations["strtoll"] = &StrTo;
1583 Optimizations["strtold"] = &StrTo;
1584 Optimizations["strtoull"] = &StrTo;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001585 Optimizations["memcmp"] = &MemCmp;
1586 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001587 Optimizations["memmove"] = &MemMove;
1588 Optimizations["memset"] = &MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001589
1590 // Math Library Optimizations
1591 Optimizations["powf"] = &Pow;
1592 Optimizations["pow"] = &Pow;
1593 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001594 Optimizations["llvm.pow.f32"] = &Pow;
1595 Optimizations["llvm.pow.f64"] = &Pow;
1596 Optimizations["llvm.pow.f80"] = &Pow;
1597 Optimizations["llvm.pow.f128"] = &Pow;
1598 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001599 Optimizations["exp2l"] = &Exp2;
1600 Optimizations["exp2"] = &Exp2;
1601 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001602 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1603 Optimizations["llvm.exp2.f128"] = &Exp2;
1604 Optimizations["llvm.exp2.f80"] = &Exp2;
1605 Optimizations["llvm.exp2.f64"] = &Exp2;
1606 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001607
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001608#ifdef HAVE_FLOORF
1609 Optimizations["floor"] = &UnaryDoubleFP;
1610#endif
1611#ifdef HAVE_CEILF
1612 Optimizations["ceil"] = &UnaryDoubleFP;
1613#endif
1614#ifdef HAVE_ROUNDF
1615 Optimizations["round"] = &UnaryDoubleFP;
1616#endif
1617#ifdef HAVE_RINTF
1618 Optimizations["rint"] = &UnaryDoubleFP;
1619#endif
1620#ifdef HAVE_NEARBYINTF
1621 Optimizations["nearbyint"] = &UnaryDoubleFP;
1622#endif
1623
1624 // Integer Optimizations
1625 Optimizations["ffs"] = &FFS;
1626 Optimizations["ffsl"] = &FFS;
1627 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001628 Optimizations["abs"] = &Abs;
1629 Optimizations["labs"] = &Abs;
1630 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001631 Optimizations["isdigit"] = &IsDigit;
1632 Optimizations["isascii"] = &IsAscii;
1633 Optimizations["toascii"] = &ToAscii;
1634
1635 // Formatting and IO Optimizations
1636 Optimizations["sprintf"] = &SPrintF;
1637 Optimizations["printf"] = &PrintF;
1638 Optimizations["fwrite"] = &FWrite;
1639 Optimizations["fputs"] = &FPuts;
1640 Optimizations["fprintf"] = &FPrintF;
1641}
1642
1643
1644/// runOnFunction - Top level algorithm.
1645///
1646bool SimplifyLibCalls::runOnFunction(Function &F) {
1647 if (Optimizations.empty())
1648 InitOptimizations();
1649
1650 const TargetData &TD = getAnalysis<TargetData>();
1651
Owen Andersone922c022009-07-22 00:24:57 +00001652 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001653
1654 bool Changed = false;
1655 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1656 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1657 // Ignore non-calls.
1658 CallInst *CI = dyn_cast<CallInst>(I++);
1659 if (!CI) continue;
1660
1661 // Ignore indirect calls and calls to non-external functions.
1662 Function *Callee = CI->getCalledFunction();
1663 if (Callee == 0 || !Callee->isDeclaration() ||
1664 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1665 continue;
1666
1667 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001668 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1669 if (!LCO) continue;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001670
1671 // Set the builder to the instruction after the call.
1672 Builder.SetInsertPoint(BB, I);
1673
1674 // Try to optimize this call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001675 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001676 if (Result == 0) continue;
1677
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001678 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1679 errs() << " into: " << *Result << "\n");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001680
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001681 // Something changed!
1682 Changed = true;
1683 ++NumSimplified;
1684
1685 // Inspect the instruction after the call (which was potentially just
1686 // added) next.
1687 I = CI; ++I;
1688
1689 if (CI != Result && !CI->use_empty()) {
1690 CI->replaceAllUsesWith(Result);
1691 if (!Result->hasName())
1692 Result->takeName(CI);
1693 }
1694 CI->eraseFromParent();
1695 }
1696 }
1697 return Changed;
1698}
1699
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001700// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001701
1702void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1703 if (!F.doesNotAccessMemory()) {
1704 F.setDoesNotAccessMemory();
1705 ++NumAnnotated;
1706 Modified = true;
1707 }
1708}
1709void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1710 if (!F.onlyReadsMemory()) {
1711 F.setOnlyReadsMemory();
1712 ++NumAnnotated;
1713 Modified = true;
1714 }
1715}
1716void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1717 if (!F.doesNotThrow()) {
1718 F.setDoesNotThrow();
1719 ++NumAnnotated;
1720 Modified = true;
1721 }
1722}
1723void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1724 if (!F.doesNotCapture(n)) {
1725 F.setDoesNotCapture(n);
1726 ++NumAnnotated;
1727 Modified = true;
1728 }
1729}
1730void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1731 if (!F.doesNotAlias(n)) {
1732 F.setDoesNotAlias(n);
1733 ++NumAnnotated;
1734 Modified = true;
1735 }
1736}
1737
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001738/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001739///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001740bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001741 Modified = false;
1742 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1743 Function &F = *I;
1744 if (!F.isDeclaration())
1745 continue;
1746
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001747 if (!F.hasName())
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001748 continue;
1749
1750 const FunctionType *FTy = F.getFunctionType();
1751
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001752 StringRef Name = F.getName();
1753 switch (Name[0]) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001754 case 's':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001755 if (Name == "strlen") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001756 if (FTy->getNumParams() != 1 ||
1757 !isa<PointerType>(FTy->getParamType(0)))
1758 continue;
1759 setOnlyReadsMemory(F);
1760 setDoesNotThrow(F);
1761 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001762 } else if (Name == "strcpy" ||
1763 Name == "stpcpy" ||
1764 Name == "strcat" ||
1765 Name == "strtol" ||
1766 Name == "strtod" ||
1767 Name == "strtof" ||
1768 Name == "strtoul" ||
1769 Name == "strtoll" ||
1770 Name == "strtold" ||
1771 Name == "strncat" ||
1772 Name == "strncpy" ||
1773 Name == "strtoull") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001774 if (FTy->getNumParams() < 2 ||
1775 !isa<PointerType>(FTy->getParamType(1)))
1776 continue;
1777 setDoesNotThrow(F);
1778 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001779 } else if (Name == "strxfrm") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001780 if (FTy->getNumParams() != 3 ||
1781 !isa<PointerType>(FTy->getParamType(0)) ||
1782 !isa<PointerType>(FTy->getParamType(1)))
1783 continue;
1784 setDoesNotThrow(F);
1785 setDoesNotCapture(F, 1);
1786 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001787 } else if (Name == "strcmp" ||
1788 Name == "strspn" ||
1789 Name == "strncmp" ||
1790 Name ==" strcspn" ||
1791 Name == "strcoll" ||
1792 Name == "strcasecmp" ||
1793 Name == "strncasecmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001794 if (FTy->getNumParams() < 2 ||
1795 !isa<PointerType>(FTy->getParamType(0)) ||
1796 !isa<PointerType>(FTy->getParamType(1)))
1797 continue;
1798 setOnlyReadsMemory(F);
1799 setDoesNotThrow(F);
1800 setDoesNotCapture(F, 1);
1801 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001802 } else if (Name == "strstr" ||
1803 Name == "strpbrk") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001804 if (FTy->getNumParams() != 2 ||
1805 !isa<PointerType>(FTy->getParamType(1)))
1806 continue;
1807 setOnlyReadsMemory(F);
1808 setDoesNotThrow(F);
1809 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001810 } else if (Name == "strtok" ||
1811 Name == "strtok_r") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001812 if (FTy->getNumParams() < 2 ||
1813 !isa<PointerType>(FTy->getParamType(1)))
1814 continue;
1815 setDoesNotThrow(F);
1816 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001817 } else if (Name == "scanf" ||
1818 Name == "setbuf" ||
1819 Name == "setvbuf") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001820 if (FTy->getNumParams() < 1 ||
1821 !isa<PointerType>(FTy->getParamType(0)))
1822 continue;
1823 setDoesNotThrow(F);
1824 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001825 } else if (Name == "strdup" ||
1826 Name == "strndup") {
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001827 if (FTy->getNumParams() < 1 ||
1828 !isa<PointerType>(FTy->getReturnType()) ||
1829 !isa<PointerType>(FTy->getParamType(0)))
1830 continue;
1831 setDoesNotThrow(F);
1832 setDoesNotAlias(F, 0);
1833 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001834 } else if (Name == "stat" ||
1835 Name == "sscanf" ||
1836 Name == "sprintf" ||
1837 Name == "statvfs") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001838 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001839 !isa<PointerType>(FTy->getParamType(0)) ||
1840 !isa<PointerType>(FTy->getParamType(1)))
1841 continue;
1842 setDoesNotThrow(F);
1843 setDoesNotCapture(F, 1);
1844 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001845 } else if (Name == "snprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001846 if (FTy->getNumParams() != 3 ||
1847 !isa<PointerType>(FTy->getParamType(0)) ||
1848 !isa<PointerType>(FTy->getParamType(2)))
1849 continue;
1850 setDoesNotThrow(F);
1851 setDoesNotCapture(F, 1);
1852 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001853 } else if (Name == "setitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001854 if (FTy->getNumParams() != 3 ||
1855 !isa<PointerType>(FTy->getParamType(1)) ||
1856 !isa<PointerType>(FTy->getParamType(2)))
1857 continue;
1858 setDoesNotThrow(F);
1859 setDoesNotCapture(F, 2);
1860 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001861 } else if (Name == "system") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001862 if (FTy->getNumParams() != 1 ||
1863 !isa<PointerType>(FTy->getParamType(0)))
1864 continue;
1865 // May throw; "system" is a valid pthread cancellation point.
1866 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001867 }
1868 break;
1869 case 'm':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001870 if (Name == "memcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001871 if (FTy->getNumParams() != 3 ||
1872 !isa<PointerType>(FTy->getParamType(0)) ||
1873 !isa<PointerType>(FTy->getParamType(1)))
1874 continue;
1875 setOnlyReadsMemory(F);
1876 setDoesNotThrow(F);
1877 setDoesNotCapture(F, 1);
1878 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001879 } else if (Name == "memchr" ||
1880 Name == "memrchr") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001881 if (FTy->getNumParams() != 3)
1882 continue;
1883 setOnlyReadsMemory(F);
1884 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001885 } else if (Name == "modf" ||
1886 Name == "modff" ||
1887 Name == "modfl" ||
1888 Name == "memcpy" ||
1889 Name == "memccpy" ||
1890 Name == "memmove") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001891 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001892 !isa<PointerType>(FTy->getParamType(1)))
1893 continue;
1894 setDoesNotThrow(F);
1895 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001896 } else if (Name == "memalign") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001897 if (!isa<PointerType>(FTy->getReturnType()))
1898 continue;
1899 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001900 } else if (Name == "mkdir" ||
1901 Name == "mktime") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001902 if (FTy->getNumParams() == 0 ||
1903 !isa<PointerType>(FTy->getParamType(0)))
1904 continue;
1905 setDoesNotThrow(F);
1906 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001907 }
1908 break;
1909 case 'r':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001910 if (Name == "realloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001911 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001912 !isa<PointerType>(FTy->getParamType(0)) ||
1913 !isa<PointerType>(FTy->getReturnType()))
1914 continue;
1915 setDoesNotThrow(F);
1916 setDoesNotAlias(F, 0);
1917 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001918 } else if (Name == "read") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001919 if (FTy->getNumParams() != 3 ||
1920 !isa<PointerType>(FTy->getParamType(1)))
1921 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001922 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001923 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001924 } else if (Name == "rmdir" ||
1925 Name == "rewind" ||
1926 Name == "remove" ||
1927 Name == "realpath") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001928 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001929 !isa<PointerType>(FTy->getParamType(0)))
1930 continue;
1931 setDoesNotThrow(F);
1932 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001933 } else if (Name == "rename" ||
1934 Name == "readlink") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001935 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001936 !isa<PointerType>(FTy->getParamType(0)) ||
1937 !isa<PointerType>(FTy->getParamType(1)))
1938 continue;
1939 setDoesNotThrow(F);
1940 setDoesNotCapture(F, 1);
1941 setDoesNotCapture(F, 2);
1942 }
1943 break;
1944 case 'w':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001945 if (Name == "write") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001946 if (FTy->getNumParams() != 3 ||
1947 !isa<PointerType>(FTy->getParamType(1)))
1948 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001949 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001950 setDoesNotCapture(F, 2);
1951 }
1952 break;
1953 case 'b':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001954 if (Name == "bcopy") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001955 if (FTy->getNumParams() != 3 ||
1956 !isa<PointerType>(FTy->getParamType(0)) ||
1957 !isa<PointerType>(FTy->getParamType(1)))
1958 continue;
1959 setDoesNotThrow(F);
1960 setDoesNotCapture(F, 1);
1961 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001962 } else if (Name == "bcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001963 if (FTy->getNumParams() != 3 ||
1964 !isa<PointerType>(FTy->getParamType(0)) ||
1965 !isa<PointerType>(FTy->getParamType(1)))
1966 continue;
1967 setDoesNotThrow(F);
1968 setOnlyReadsMemory(F);
1969 setDoesNotCapture(F, 1);
1970 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001971 } else if (Name == "bzero") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001972 if (FTy->getNumParams() != 2 ||
1973 !isa<PointerType>(FTy->getParamType(0)))
1974 continue;
1975 setDoesNotThrow(F);
1976 setDoesNotCapture(F, 1);
1977 }
1978 break;
1979 case 'c':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001980 if (Name == "calloc") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001981 if (FTy->getNumParams() != 2 ||
1982 !isa<PointerType>(FTy->getReturnType()))
1983 continue;
1984 setDoesNotThrow(F);
1985 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001986 } else if (Name == "chmod" ||
1987 Name == "chown" ||
1988 Name == "ctermid" ||
1989 Name == "clearerr" ||
1990 Name == "closedir") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001991 if (FTy->getNumParams() == 0 ||
1992 !isa<PointerType>(FTy->getParamType(0)))
1993 continue;
1994 setDoesNotThrow(F);
1995 setDoesNotCapture(F, 1);
1996 }
1997 break;
1998 case 'a':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001999 if (Name == "atoi" ||
2000 Name == "atol" ||
2001 Name == "atof" ||
2002 Name == "atoll") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002003 if (FTy->getNumParams() != 1 ||
2004 !isa<PointerType>(FTy->getParamType(0)))
2005 continue;
2006 setDoesNotThrow(F);
2007 setOnlyReadsMemory(F);
2008 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002009 } else if (Name == "access") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002010 if (FTy->getNumParams() != 2 ||
2011 !isa<PointerType>(FTy->getParamType(0)))
2012 continue;
2013 setDoesNotThrow(F);
2014 setDoesNotCapture(F, 1);
2015 }
2016 break;
2017 case 'f':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002018 if (Name == "fopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002019 if (FTy->getNumParams() != 2 ||
2020 !isa<PointerType>(FTy->getReturnType()) ||
2021 !isa<PointerType>(FTy->getParamType(0)) ||
2022 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002023 continue;
2024 setDoesNotThrow(F);
2025 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002026 setDoesNotCapture(F, 1);
2027 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002028 } else if (Name == "fdopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002029 if (FTy->getNumParams() != 2 ||
2030 !isa<PointerType>(FTy->getReturnType()) ||
2031 !isa<PointerType>(FTy->getParamType(1)))
2032 continue;
2033 setDoesNotThrow(F);
2034 setDoesNotAlias(F, 0);
2035 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002036 } else if (Name == "feof" ||
2037 Name == "free" ||
2038 Name == "fseek" ||
2039 Name == "ftell" ||
2040 Name == "fgetc" ||
2041 Name == "fseeko" ||
2042 Name == "ftello" ||
2043 Name == "fileno" ||
2044 Name == "fflush" ||
2045 Name == "fclose" ||
2046 Name == "fsetpos" ||
2047 Name == "flockfile" ||
2048 Name == "funlockfile" ||
2049 Name == "ftrylockfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002050 if (FTy->getNumParams() == 0 ||
2051 !isa<PointerType>(FTy->getParamType(0)))
2052 continue;
2053 setDoesNotThrow(F);
2054 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002055 } else if (Name == "ferror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002056 if (FTy->getNumParams() != 1 ||
2057 !isa<PointerType>(FTy->getParamType(0)))
2058 continue;
2059 setDoesNotThrow(F);
2060 setDoesNotCapture(F, 1);
2061 setOnlyReadsMemory(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002062 } else if (Name == "fputc" ||
2063 Name == "fstat" ||
2064 Name == "frexp" ||
2065 Name == "frexpf" ||
2066 Name == "frexpl" ||
2067 Name == "fstatvfs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002068 if (FTy->getNumParams() != 2 ||
2069 !isa<PointerType>(FTy->getParamType(1)))
2070 continue;
2071 setDoesNotThrow(F);
2072 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002073 } else if (Name == "fgets") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002074 if (FTy->getNumParams() != 3 ||
2075 !isa<PointerType>(FTy->getParamType(0)) ||
2076 !isa<PointerType>(FTy->getParamType(2)))
2077 continue;
2078 setDoesNotThrow(F);
2079 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002080 } else if (Name == "fread" ||
2081 Name == "fwrite") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002082 if (FTy->getNumParams() != 4 ||
2083 !isa<PointerType>(FTy->getParamType(0)) ||
2084 !isa<PointerType>(FTy->getParamType(3)))
2085 continue;
2086 setDoesNotThrow(F);
2087 setDoesNotCapture(F, 1);
2088 setDoesNotCapture(F, 4);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002089 } else if (Name == "fputs" ||
2090 Name == "fscanf" ||
2091 Name == "fprintf" ||
2092 Name == "fgetpos") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002093 if (FTy->getNumParams() < 2 ||
2094 !isa<PointerType>(FTy->getParamType(0)) ||
2095 !isa<PointerType>(FTy->getParamType(1)))
2096 continue;
2097 setDoesNotThrow(F);
2098 setDoesNotCapture(F, 1);
2099 setDoesNotCapture(F, 2);
2100 }
2101 break;
2102 case 'g':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002103 if (Name == "getc" ||
2104 Name == "getlogin_r" ||
2105 Name == "getc_unlocked") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002106 if (FTy->getNumParams() == 0 ||
2107 !isa<PointerType>(FTy->getParamType(0)))
2108 continue;
2109 setDoesNotThrow(F);
2110 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002111 } else if (Name == "getenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002112 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002113 !isa<PointerType>(FTy->getParamType(0)))
2114 continue;
2115 setDoesNotThrow(F);
2116 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002117 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002118 } else if (Name == "gets" ||
2119 Name == "getchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002120 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002121 } else if (Name == "getitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002122 if (FTy->getNumParams() != 2 ||
2123 !isa<PointerType>(FTy->getParamType(1)))
2124 continue;
2125 setDoesNotThrow(F);
2126 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002127 } else if (Name == "getpwnam") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002128 if (FTy->getNumParams() != 1 ||
2129 !isa<PointerType>(FTy->getParamType(0)))
2130 continue;
2131 setDoesNotThrow(F);
2132 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002133 }
2134 break;
2135 case 'u':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002136 if (Name == "ungetc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002137 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002138 !isa<PointerType>(FTy->getParamType(1)))
2139 continue;
2140 setDoesNotThrow(F);
2141 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002142 } else if (Name == "uname" ||
2143 Name == "unlink" ||
2144 Name == "unsetenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002145 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002146 !isa<PointerType>(FTy->getParamType(0)))
2147 continue;
2148 setDoesNotThrow(F);
2149 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002150 } else if (Name == "utime" ||
2151 Name == "utimes") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002152 if (FTy->getNumParams() != 2 ||
2153 !isa<PointerType>(FTy->getParamType(0)) ||
2154 !isa<PointerType>(FTy->getParamType(1)))
2155 continue;
2156 setDoesNotThrow(F);
2157 setDoesNotCapture(F, 1);
2158 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002159 }
2160 break;
2161 case 'p':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002162 if (Name == "putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002163 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002164 !isa<PointerType>(FTy->getParamType(1)))
2165 continue;
2166 setDoesNotThrow(F);
2167 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002168 } else if (Name == "puts" ||
2169 Name == "printf" ||
2170 Name == "perror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002171 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002172 !isa<PointerType>(FTy->getParamType(0)))
2173 continue;
2174 setDoesNotThrow(F);
2175 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002176 } else if (Name == "pread" ||
2177 Name == "pwrite") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002178 if (FTy->getNumParams() != 4 ||
2179 !isa<PointerType>(FTy->getParamType(1)))
2180 continue;
2181 // May throw; these are valid pthread cancellation points.
2182 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002183 } else if (Name == "putchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002184 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002185 } else if (Name == "popen") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002186 if (FTy->getNumParams() != 2 ||
2187 !isa<PointerType>(FTy->getReturnType()) ||
2188 !isa<PointerType>(FTy->getParamType(0)) ||
2189 !isa<PointerType>(FTy->getParamType(1)))
2190 continue;
2191 setDoesNotThrow(F);
2192 setDoesNotAlias(F, 0);
2193 setDoesNotCapture(F, 1);
2194 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002195 } else if (Name == "pclose") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002196 if (FTy->getNumParams() != 1 ||
2197 !isa<PointerType>(FTy->getParamType(0)))
2198 continue;
2199 setDoesNotThrow(F);
2200 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002201 }
2202 break;
2203 case 'v':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002204 if (Name == "vscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002205 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002206 !isa<PointerType>(FTy->getParamType(1)))
2207 continue;
2208 setDoesNotThrow(F);
2209 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002210 } else if (Name == "vsscanf" ||
2211 Name == "vfscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002212 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002213 !isa<PointerType>(FTy->getParamType(1)) ||
2214 !isa<PointerType>(FTy->getParamType(2)))
2215 continue;
2216 setDoesNotThrow(F);
2217 setDoesNotCapture(F, 1);
2218 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002219 } else if (Name == "valloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002220 if (!isa<PointerType>(FTy->getReturnType()))
2221 continue;
2222 setDoesNotThrow(F);
2223 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002224 } else if (Name == "vprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002225 if (FTy->getNumParams() != 2 ||
2226 !isa<PointerType>(FTy->getParamType(0)))
2227 continue;
2228 setDoesNotThrow(F);
2229 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002230 } else if (Name == "vfprintf" ||
2231 Name == "vsprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002232 if (FTy->getNumParams() != 3 ||
2233 !isa<PointerType>(FTy->getParamType(0)) ||
2234 !isa<PointerType>(FTy->getParamType(1)))
2235 continue;
2236 setDoesNotThrow(F);
2237 setDoesNotCapture(F, 1);
2238 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002239 } else if (Name == "vsnprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002240 if (FTy->getNumParams() != 4 ||
2241 !isa<PointerType>(FTy->getParamType(0)) ||
2242 !isa<PointerType>(FTy->getParamType(2)))
2243 continue;
2244 setDoesNotThrow(F);
2245 setDoesNotCapture(F, 1);
2246 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002247 }
2248 break;
2249 case 'o':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002250 if (Name == "open") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002251 if (FTy->getNumParams() < 2 ||
2252 !isa<PointerType>(FTy->getParamType(0)))
2253 continue;
2254 // May throw; "open" is a valid pthread cancellation point.
2255 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002256 } else if (Name == "opendir") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002257 if (FTy->getNumParams() != 1 ||
2258 !isa<PointerType>(FTy->getReturnType()) ||
2259 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002260 continue;
2261 setDoesNotThrow(F);
2262 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002263 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002264 }
2265 break;
2266 case 't':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002267 if (Name == "tmpfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002268 if (!isa<PointerType>(FTy->getReturnType()))
2269 continue;
2270 setDoesNotThrow(F);
2271 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002272 } else if (Name == "times") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002273 if (FTy->getNumParams() != 1 ||
2274 !isa<PointerType>(FTy->getParamType(0)))
2275 continue;
2276 setDoesNotThrow(F);
2277 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002278 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002279 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002280 case 'h':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002281 if (Name == "htonl" ||
2282 Name == "htons") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002283 setDoesNotThrow(F);
2284 setDoesNotAccessMemory(F);
2285 }
2286 break;
2287 case 'n':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002288 if (Name == "ntohl" ||
2289 Name == "ntohs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002290 setDoesNotThrow(F);
2291 setDoesNotAccessMemory(F);
2292 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002293 break;
2294 case 'l':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002295 if (Name == "lstat") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002296 if (FTy->getNumParams() != 2 ||
2297 !isa<PointerType>(FTy->getParamType(0)) ||
2298 !isa<PointerType>(FTy->getParamType(1)))
2299 continue;
2300 setDoesNotThrow(F);
2301 setDoesNotCapture(F, 1);
2302 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002303 } else if (Name == "lchown") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002304 if (FTy->getNumParams() != 3 ||
2305 !isa<PointerType>(FTy->getParamType(0)))
2306 continue;
2307 setDoesNotThrow(F);
2308 setDoesNotCapture(F, 1);
2309 }
2310 break;
2311 case 'q':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002312 if (Name == "qsort") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002313 if (FTy->getNumParams() != 4 ||
2314 !isa<PointerType>(FTy->getParamType(3)))
2315 continue;
2316 // May throw; places call through function pointer.
2317 setDoesNotCapture(F, 4);
2318 }
2319 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002320 case '_':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002321 if (Name == "__strdup" ||
2322 Name == "__strndup") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002323 if (FTy->getNumParams() < 1 ||
2324 !isa<PointerType>(FTy->getReturnType()) ||
2325 !isa<PointerType>(FTy->getParamType(0)))
2326 continue;
2327 setDoesNotThrow(F);
2328 setDoesNotAlias(F, 0);
2329 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002330 } else if (Name == "__strtok_r") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002331 if (FTy->getNumParams() != 3 ||
2332 !isa<PointerType>(FTy->getParamType(1)))
2333 continue;
2334 setDoesNotThrow(F);
2335 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002336 } else if (Name == "_IO_getc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002337 if (FTy->getNumParams() != 1 ||
2338 !isa<PointerType>(FTy->getParamType(0)))
2339 continue;
2340 setDoesNotThrow(F);
2341 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002342 } else if (Name == "_IO_putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002343 if (FTy->getNumParams() != 2 ||
2344 !isa<PointerType>(FTy->getParamType(1)))
2345 continue;
2346 setDoesNotThrow(F);
2347 setDoesNotCapture(F, 2);
2348 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002349 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002350 case 1:
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002351 if (Name == "\1__isoc99_scanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002352 if (FTy->getNumParams() < 1 ||
2353 !isa<PointerType>(FTy->getParamType(0)))
2354 continue;
2355 setDoesNotThrow(F);
2356 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002357 } else if (Name == "\1stat64" ||
2358 Name == "\1lstat64" ||
2359 Name == "\1statvfs64" ||
2360 Name == "\1__isoc99_sscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002361 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002362 !isa<PointerType>(FTy->getParamType(0)) ||
2363 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002364 continue;
2365 setDoesNotThrow(F);
2366 setDoesNotCapture(F, 1);
2367 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002368 } else if (Name == "\1fopen64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002369 if (FTy->getNumParams() != 2 ||
2370 !isa<PointerType>(FTy->getReturnType()) ||
2371 !isa<PointerType>(FTy->getParamType(0)) ||
2372 !isa<PointerType>(FTy->getParamType(1)))
2373 continue;
2374 setDoesNotThrow(F);
2375 setDoesNotAlias(F, 0);
2376 setDoesNotCapture(F, 1);
2377 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002378 } else if (Name == "\1fseeko64" ||
2379 Name == "\1ftello64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002380 if (FTy->getNumParams() == 0 ||
2381 !isa<PointerType>(FTy->getParamType(0)))
2382 continue;
2383 setDoesNotThrow(F);
2384 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002385 } else if (Name == "\1tmpfile64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002386 if (!isa<PointerType>(FTy->getReturnType()))
2387 continue;
2388 setDoesNotThrow(F);
2389 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002390 } else if (Name == "\1fstat64" ||
2391 Name == "\1fstatvfs64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002392 if (FTy->getNumParams() != 2 ||
2393 !isa<PointerType>(FTy->getParamType(1)))
2394 continue;
2395 setDoesNotThrow(F);
2396 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002397 } else if (Name == "\1open64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002398 if (FTy->getNumParams() < 2 ||
2399 !isa<PointerType>(FTy->getParamType(0)))
2400 continue;
2401 // May throw; "open" is a valid pthread cancellation point.
2402 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002403 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002404 break;
2405 }
2406 }
2407 return Modified;
2408}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002409
2410// TODO:
2411// Additional cases that we need to add to this file:
2412//
2413// cbrt:
2414// * cbrt(expN(X)) -> expN(x/3)
2415// * cbrt(sqrt(x)) -> pow(x,1/6)
2416// * cbrt(sqrt(x)) -> pow(x,1/9)
2417//
2418// cos, cosf, cosl:
2419// * cos(-x) -> cos(x)
2420//
2421// exp, expf, expl:
2422// * exp(log(x)) -> x
2423//
2424// log, logf, logl:
2425// * log(exp(x)) -> x
2426// * log(x**y) -> y*log(x)
2427// * log(exp(y)) -> y*log(e)
2428// * log(exp2(y)) -> y*log(2)
2429// * log(exp10(y)) -> y*log(10)
2430// * log(sqrt(x)) -> 0.5*log(x)
2431// * log(pow(x,y)) -> y*log(x)
2432//
2433// lround, lroundf, lroundl:
2434// * lround(cnst) -> cnst'
2435//
2436// memcmp:
2437// * memcmp(x,y,l) -> cnst
2438// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2439//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002440// pow, powf, powl:
2441// * pow(exp(x),y) -> exp(x*y)
2442// * pow(sqrt(x),y) -> pow(x,y*0.5)
2443// * pow(pow(x,y),z)-> pow(x,y*z)
2444//
2445// puts:
2446// * puts("") -> putchar("\n")
2447//
2448// round, roundf, roundl:
2449// * round(cnst) -> cnst'
2450//
2451// signbit:
2452// * signbit(cnst) -> cnst'
2453// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2454//
2455// sqrt, sqrtf, sqrtl:
2456// * sqrt(expN(x)) -> expN(x*0.5)
2457// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2458// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2459//
2460// stpcpy:
2461// * stpcpy(str, "literal") ->
2462// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2463// strrchr:
2464// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2465// (if c is a constant integer and s is a constant string)
2466// * strrchr(s1,0) -> strchr(s1,0)
2467//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002468// strpbrk:
2469// * strpbrk(s,a) -> offset_in_for(s,a)
2470// (if s and a are both constant strings)
2471// * strpbrk(s,"") -> 0
2472// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2473//
2474// strspn, strcspn:
2475// * strspn(s,a) -> const_int (if both args are constant)
2476// * strspn("",a) -> 0
2477// * strspn(s,"") -> 0
2478// * strcspn(s,a) -> const_int (if both args are constant)
2479// * strcspn("",a) -> 0
2480// * strcspn(s,"") -> strlen(a)
2481//
2482// strstr:
2483// * strstr(x,x) -> x
2484// * strstr(s1,s2) -> offset_of_s2_in(s1)
2485// (if s1 and s2 are constant strings)
2486//
2487// tan, tanf, tanl:
2488// * tan(atan(x)) -> x
2489//
2490// trunc, truncf, truncl:
2491// * trunc(cnst) -> cnst'
2492//
2493//