1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Config/config.h"
36 STATISTIC(NumSimplified, "Number of library calls simplified");
37 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
39 //===----------------------------------------------------------------------===//
40 // Optimizer Base Class
41 //===----------------------------------------------------------------------===//
43 /// This class is the abstract base class for the set of optimizations that
44 /// corresponds to one library call.
46 class LibCallOptimization {
52 LibCallOptimization() { }
53 virtual ~LibCallOptimization() {}
55 /// CallOptimizer - This pure virtual method is implemented by base classes to
56 /// do various optimizations. If this returns null then no transformation was
57 /// performed. If it returns CI, then it transformed the call and CI is to be
58 /// deleted. If it returns something else, replace CI with the new value and
60 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
63 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
64 Caller = CI->getParent()->getParent();
66 if (CI->getCalledFunction())
67 Context = &CI->getCalledFunction()->getContext();
68 return CallOptimizer(CI->getCalledFunction(), CI, B);
71 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
72 Value *CastToCStr(Value *V, IRBuilder<> &B);
74 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
75 /// specified pointer. Ptr is required to be some pointer type, and the
76 /// return value has 'intptr_t' type.
77 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
79 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
80 /// specified pointer and character. Ptr is required to be some pointer type,
81 /// and the return value has 'i8*' type.
82 Value *EmitStrChr(Value *Ptr, char C, IRBuilder<> &B);
84 /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
85 /// specified pointer arguments.
86 Value *EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B);
88 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
89 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
90 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
91 unsigned Align, IRBuilder<> &B);
93 /// EmitMemMove - Emit a call to the memmove function to the builder. This
94 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
95 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
96 unsigned Align, IRBuilder<> &B);
98 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
99 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
100 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
102 /// EmitMemCmp - Emit a call to the memcmp function.
103 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
105 /// EmitMemSet - Emit a call to the memset function
106 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
108 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name'
109 /// (e.g. 'floor'). This function is known to take a single of type matching
110 /// 'Op' and returns one value with the same type. If 'Op' is a long double,
111 /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
113 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
114 const AttrListPtr &Attrs);
116 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
118 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
120 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
122 void EmitPutS(Value *Str, IRBuilder<> &B);
124 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
125 /// an i32, and File is a pointer to FILE.
126 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
128 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
129 /// pointer and File is a pointer to FILE.
130 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
132 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
133 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
134 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
137 } // End anonymous namespace.
139 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
140 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
141 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
144 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
145 /// specified pointer. This always returns an integer value of size intptr_t.
146 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
147 Module *M = Caller->getParent();
148 AttributeWithIndex AWI[2];
149 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
150 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
151 Attribute::NoUnwind);
153 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
154 TD->getIntPtrType(*Context),
155 Type::getInt8PtrTy(*Context),
157 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
158 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
159 CI->setCallingConv(F->getCallingConv());
164 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
165 /// specified pointer and character. Ptr is required to be some pointer type,
166 /// and the return value has 'i8*' type.
167 Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
168 Module *M = Caller->getParent();
169 AttributeWithIndex AWI =
170 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
172 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
173 const Type *I32Ty = Type::getInt32Ty(*Context);
174 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
175 I8Ptr, I8Ptr, I32Ty, NULL);
176 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
177 ConstantInt::get(I32Ty, C), "strchr");
178 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
179 CI->setCallingConv(F->getCallingConv());
183 /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
184 /// specified pointer arguments.
185 Value *LibCallOptimization::EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B) {
186 Module *M = Caller->getParent();
187 AttributeWithIndex AWI[2];
188 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
189 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
190 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
191 Value *StrCpy = M->getOrInsertFunction("strcpy", AttrListPtr::get(AWI, 2),
192 I8Ptr, I8Ptr, I8Ptr, NULL);
193 CallInst *CI = B.CreateCall2(StrCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
195 if (const Function *F = dyn_cast<Function>(StrCpy->stripPointerCasts()))
196 CI->setCallingConv(F->getCallingConv());
200 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
201 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
202 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
203 unsigned Align, IRBuilder<> &B) {
204 Module *M = Caller->getParent();
205 const Type *Ty = Len->getType();
206 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
207 Dst = CastToCStr(Dst, B);
208 Src = CastToCStr(Src, B);
209 return B.CreateCall4(MemCpy, Dst, Src, Len,
210 ConstantInt::get(Type::getInt32Ty(*Context), Align));
213 /// EmitMemMove - Emit a call to the memmove function to the builder. This
214 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
215 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
216 unsigned Align, IRBuilder<> &B) {
217 Module *M = Caller->getParent();
218 const Type *Ty = TD->getIntPtrType(*Context);
219 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
220 Dst = CastToCStr(Dst, B);
221 Src = CastToCStr(Src, B);
222 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
223 return B.CreateCall4(MemMove, Dst, Src, Len, A);
226 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
227 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
228 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
229 Value *Len, IRBuilder<> &B) {
230 Module *M = Caller->getParent();
231 AttributeWithIndex AWI;
232 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
234 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
235 Type::getInt8PtrTy(*Context),
236 Type::getInt8PtrTy(*Context),
237 Type::getInt32Ty(*Context),
238 TD->getIntPtrType(*Context),
240 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
242 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
243 CI->setCallingConv(F->getCallingConv());
248 /// EmitMemCmp - Emit a call to the memcmp function.
249 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
250 Value *Len, IRBuilder<> &B) {
251 Module *M = Caller->getParent();
252 AttributeWithIndex AWI[3];
253 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
254 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
255 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
256 Attribute::NoUnwind);
258 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
259 Type::getInt32Ty(*Context),
260 Type::getInt8PtrTy(*Context),
261 Type::getInt8PtrTy(*Context),
262 TD->getIntPtrType(*Context), NULL);
263 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
266 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
267 CI->setCallingConv(F->getCallingConv());
272 /// EmitMemSet - Emit a call to the memset function
273 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
274 Value *Len, IRBuilder<> &B) {
275 Module *M = Caller->getParent();
276 Intrinsic::ID IID = Intrinsic::memset;
278 Tys[0] = Len->getType();
279 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
280 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
281 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
284 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
285 /// 'floor'). This function is known to take a single of type matching 'Op' and
286 /// returns one value with the same type. If 'Op' is a long double, 'l' is
287 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
288 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
290 const AttrListPtr &Attrs) {
292 if (!Op->getType()->isDoubleTy()) {
293 // If we need to add a suffix, copy into NameBuffer.
294 unsigned NameLen = strlen(Name);
295 assert(NameLen < sizeof(NameBuffer)-2);
296 memcpy(NameBuffer, Name, NameLen);
297 if (Op->getType()->isFloatTy())
298 NameBuffer[NameLen] = 'f'; // floorf
300 NameBuffer[NameLen] = 'l'; // floorl
301 NameBuffer[NameLen+1] = 0;
305 Module *M = Caller->getParent();
306 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
307 Op->getType(), NULL);
308 CallInst *CI = B.CreateCall(Callee, Op, Name);
309 CI->setAttributes(Attrs);
310 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
311 CI->setCallingConv(F->getCallingConv());
316 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
318 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
319 Module *M = Caller->getParent();
320 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
321 Type::getInt32Ty(*Context), NULL);
322 CallInst *CI = B.CreateCall(PutChar,
323 B.CreateIntCast(Char,
324 Type::getInt32Ty(*Context),
329 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
330 CI->setCallingConv(F->getCallingConv());
334 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
336 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
337 Module *M = Caller->getParent();
338 AttributeWithIndex AWI[2];
339 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
340 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
342 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
343 Type::getInt32Ty(*Context),
344 Type::getInt8PtrTy(*Context),
346 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
347 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
348 CI->setCallingConv(F->getCallingConv());
352 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
353 /// an integer and File is a pointer to FILE.
354 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
355 Module *M = Caller->getParent();
356 AttributeWithIndex AWI[2];
357 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
358 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
360 if (File->getType()->isPointerTy())
361 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
362 Type::getInt32Ty(*Context),
363 Type::getInt32Ty(*Context), File->getType(),
366 F = M->getOrInsertFunction("fputc",
367 Type::getInt32Ty(*Context),
368 Type::getInt32Ty(*Context),
369 File->getType(), NULL);
370 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
372 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
374 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
375 CI->setCallingConv(Fn->getCallingConv());
378 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
379 /// pointer and File is a pointer to FILE.
380 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
381 Module *M = Caller->getParent();
382 AttributeWithIndex AWI[3];
383 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
384 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
385 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
387 if (File->getType()->isPointerTy())
388 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
389 Type::getInt32Ty(*Context),
390 Type::getInt8PtrTy(*Context),
391 File->getType(), NULL);
393 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
394 Type::getInt8PtrTy(*Context),
395 File->getType(), NULL);
396 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
398 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
399 CI->setCallingConv(Fn->getCallingConv());
402 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
403 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
404 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
406 Module *M = Caller->getParent();
407 AttributeWithIndex AWI[3];
408 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
409 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
410 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
412 if (File->getType()->isPointerTy())
413 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
414 TD->getIntPtrType(*Context),
415 Type::getInt8PtrTy(*Context),
416 TD->getIntPtrType(*Context),
417 TD->getIntPtrType(*Context),
418 File->getType(), NULL);
420 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
421 Type::getInt8PtrTy(*Context),
422 TD->getIntPtrType(*Context),
423 TD->getIntPtrType(*Context),
424 File->getType(), NULL);
425 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
426 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
428 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
429 CI->setCallingConv(Fn->getCallingConv());
432 //===----------------------------------------------------------------------===//
434 //===----------------------------------------------------------------------===//
436 /// GetStringLengthH - If we can compute the length of the string pointed to by
437 /// the specified pointer, return 'len+1'. If we can't, return 0.
438 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
439 // Look through noop bitcast instructions.
440 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
441 return GetStringLengthH(BCI->getOperand(0), PHIs);
443 // If this is a PHI node, there are two cases: either we have already seen it
445 if (PHINode *PN = dyn_cast<PHINode>(V)) {
446 if (!PHIs.insert(PN))
447 return ~0ULL; // already in the set.
449 // If it was new, see if all the input strings are the same length.
450 uint64_t LenSoFar = ~0ULL;
451 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
452 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
453 if (Len == 0) return 0; // Unknown length -> unknown.
455 if (Len == ~0ULL) continue;
457 if (Len != LenSoFar && LenSoFar != ~0ULL)
458 return 0; // Disagree -> unknown.
462 // Success, all agree.
466 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
467 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
468 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
469 if (Len1 == 0) return 0;
470 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
471 if (Len2 == 0) return 0;
472 if (Len1 == ~0ULL) return Len2;
473 if (Len2 == ~0ULL) return Len1;
474 if (Len1 != Len2) return 0;
478 // If the value is not a GEP instruction nor a constant expression with a
479 // GEP instruction, then return unknown.
481 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
483 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
484 if (CE->getOpcode() != Instruction::GetElementPtr)
491 // Make sure the GEP has exactly three arguments.
492 if (GEP->getNumOperands() != 3)
495 // Check to make sure that the first operand of the GEP is an integer and
496 // has value 0 so that we are sure we're indexing into the initializer.
497 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
503 // If the second index isn't a ConstantInt, then this is a variable index
504 // into the array. If this occurs, we can't say anything meaningful about
506 uint64_t StartIdx = 0;
507 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
508 StartIdx = CI->getZExtValue();
512 // The GEP instruction, constant or instruction, must reference a global
513 // variable that is a constant and is initialized. The referenced constant
514 // initializer is the array that we'll use for optimization.
515 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
516 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
517 GV->mayBeOverridden())
519 Constant *GlobalInit = GV->getInitializer();
521 // Handle the ConstantAggregateZero case, which is a degenerate case. The
522 // initializer is constant zero so the length of the string must be zero.
523 if (isa<ConstantAggregateZero>(GlobalInit))
524 return 1; // Len = 0 offset by 1.
526 // Must be a Constant Array
527 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
528 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
531 // Get the number of elements in the array
532 uint64_t NumElts = Array->getType()->getNumElements();
534 // Traverse the constant array from StartIdx (derived above) which is
535 // the place the GEP refers to in the array.
536 for (unsigned i = StartIdx; i != NumElts; ++i) {
537 Constant *Elt = Array->getOperand(i);
538 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
539 if (!CI) // This array isn't suitable, non-int initializer.
542 return i-StartIdx+1; // We found end of string, success!
545 return 0; // The array isn't null terminated, conservatively return 'unknown'.
548 /// GetStringLength - If we can compute the length of the string pointed to by
549 /// the specified pointer, return 'len+1'. If we can't, return 0.
550 static uint64_t GetStringLength(Value *V) {
551 if (!V->getType()->isPointerTy()) return 0;
553 SmallPtrSet<PHINode*, 32> PHIs;
554 uint64_t Len = GetStringLengthH(V, PHIs);
555 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
556 // an empty string as a length.
557 return Len == ~0ULL ? 1 : Len;
560 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
561 /// value is equal or not-equal to zero.
562 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
563 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
565 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
566 if (IC->isEquality())
567 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
568 if (C->isNullValue())
570 // Unknown instruction.
576 //===----------------------------------------------------------------------===//
577 // String and Memory LibCall Optimizations
578 //===----------------------------------------------------------------------===//
580 //===---------------------------------------===//
581 // 'strcat' Optimizations
583 struct StrCatOpt : public LibCallOptimization {
584 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
585 // Verify the "strcat" function prototype.
586 const FunctionType *FT = Callee->getFunctionType();
587 if (FT->getNumParams() != 2 ||
588 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
589 FT->getParamType(0) != FT->getReturnType() ||
590 FT->getParamType(1) != FT->getReturnType())
593 // Extract some information from the instruction
594 Value *Dst = CI->getOperand(1);
595 Value *Src = CI->getOperand(2);
597 // See if we can get the length of the input string.
598 uint64_t Len = GetStringLength(Src);
599 if (Len == 0) return 0;
600 --Len; // Unbias length.
602 // Handle the simple, do-nothing case: strcat(x, "") -> x
606 // These optimizations require TargetData.
609 EmitStrLenMemCpy(Src, Dst, Len, B);
613 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
614 // We need to find the end of the destination string. That's where the
615 // memory is to be moved to. We just generate a call to strlen.
616 Value *DstLen = EmitStrLen(Dst, B);
618 // Now that we have the destination's length, we must index into the
619 // destination's pointer to get the actual memcpy destination (end of
620 // the string .. we're concatenating).
621 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
623 // We have enough information to now generate the memcpy call to do the
624 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
625 EmitMemCpy(CpyDst, Src,
626 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
630 //===---------------------------------------===//
631 // 'strncat' Optimizations
633 struct StrNCatOpt : public StrCatOpt {
634 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
635 // Verify the "strncat" function prototype.
636 const FunctionType *FT = Callee->getFunctionType();
637 if (FT->getNumParams() != 3 ||
638 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
639 FT->getParamType(0) != FT->getReturnType() ||
640 FT->getParamType(1) != FT->getReturnType() ||
641 !FT->getParamType(2)->isIntegerTy())
644 // Extract some information from the instruction
645 Value *Dst = CI->getOperand(1);
646 Value *Src = CI->getOperand(2);
649 // We don't do anything if length is not constant
650 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
651 Len = LengthArg->getZExtValue();
655 // See if we can get the length of the input string.
656 uint64_t SrcLen = GetStringLength(Src);
657 if (SrcLen == 0) return 0;
658 --SrcLen; // Unbias length.
660 // Handle the simple, do-nothing cases:
661 // strncat(x, "", c) -> x
662 // strncat(x, c, 0) -> x
663 if (SrcLen == 0 || Len == 0) return Dst;
665 // These optimizations require TargetData.
668 // We don't optimize this case
669 if (Len < SrcLen) return 0;
671 // strncat(x, s, c) -> strcat(x, s)
672 // s is constant so the strcat can be optimized further
673 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
678 //===---------------------------------------===//
679 // 'strchr' Optimizations
681 struct StrChrOpt : public LibCallOptimization {
682 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
683 // Verify the "strchr" function prototype.
684 const FunctionType *FT = Callee->getFunctionType();
685 if (FT->getNumParams() != 2 ||
686 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
687 FT->getParamType(0) != FT->getReturnType())
690 Value *SrcStr = CI->getOperand(1);
692 // If the second operand is non-constant, see if we can compute the length
693 // of the input string and turn this into memchr.
694 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
696 // These optimizations require TargetData.
699 uint64_t Len = GetStringLength(SrcStr);
700 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
703 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
704 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
707 // Otherwise, the character is a constant, see if the first argument is
708 // a string literal. If so, we can constant fold.
710 if (!GetConstantStringInfo(SrcStr, Str))
713 // strchr can find the nul character.
715 char CharValue = CharC->getSExtValue();
717 // Compute the offset.
720 if (i == Str.size()) // Didn't find the char. strchr returns null.
721 return Constant::getNullValue(CI->getType());
722 // Did we find our match?
723 if (Str[i] == CharValue)
728 // strchr(s+n,c) -> gep(s+n+i,c)
729 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
730 return B.CreateGEP(SrcStr, Idx, "strchr");
734 //===---------------------------------------===//
735 // 'strcmp' Optimizations
737 struct StrCmpOpt : public LibCallOptimization {
738 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
739 // Verify the "strcmp" function prototype.
740 const FunctionType *FT = Callee->getFunctionType();
741 if (FT->getNumParams() != 2 ||
742 !FT->getReturnType()->isIntegerTy(32) ||
743 FT->getParamType(0) != FT->getParamType(1) ||
744 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
747 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
748 if (Str1P == Str2P) // strcmp(x,x) -> 0
749 return ConstantInt::get(CI->getType(), 0);
751 std::string Str1, Str2;
752 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
753 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
755 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
756 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
758 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
759 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
761 // strcmp(x, y) -> cnst (if both x and y are constant strings)
762 if (HasStr1 && HasStr2)
763 return ConstantInt::get(CI->getType(),
764 strcmp(Str1.c_str(),Str2.c_str()));
766 // strcmp(P, "x") -> memcmp(P, "x", 2)
767 uint64_t Len1 = GetStringLength(Str1P);
768 uint64_t Len2 = GetStringLength(Str2P);
770 // These optimizations require TargetData.
773 return EmitMemCmp(Str1P, Str2P,
774 ConstantInt::get(TD->getIntPtrType(*Context),
775 std::min(Len1, Len2)), B);
782 //===---------------------------------------===//
783 // 'strncmp' Optimizations
785 struct StrNCmpOpt : public LibCallOptimization {
786 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
787 // Verify the "strncmp" function prototype.
788 const FunctionType *FT = Callee->getFunctionType();
789 if (FT->getNumParams() != 3 ||
790 !FT->getReturnType()->isIntegerTy(32) ||
791 FT->getParamType(0) != FT->getParamType(1) ||
792 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
793 !FT->getParamType(2)->isIntegerTy())
796 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
797 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
798 return ConstantInt::get(CI->getType(), 0);
800 // Get the length argument if it is constant.
802 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
803 Length = LengthArg->getZExtValue();
807 if (Length == 0) // strncmp(x,y,0) -> 0
808 return ConstantInt::get(CI->getType(), 0);
810 std::string Str1, Str2;
811 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
812 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
814 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
815 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
817 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
818 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
820 // strncmp(x, y) -> cnst (if both x and y are constant strings)
821 if (HasStr1 && HasStr2)
822 return ConstantInt::get(CI->getType(),
823 strncmp(Str1.c_str(), Str2.c_str(), Length));
829 //===---------------------------------------===//
830 // 'strcpy' Optimizations
832 struct StrCpyOpt : public LibCallOptimization {
833 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
834 // Verify the "strcpy" function prototype.
835 const FunctionType *FT = Callee->getFunctionType();
836 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
837 FT->getParamType(0) != FT->getParamType(1) ||
838 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
841 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
842 if (Dst == Src) // strcpy(x,x) -> x
845 // These optimizations require TargetData.
848 // See if we can get the length of the input string.
849 uint64_t Len = GetStringLength(Src);
850 if (Len == 0) return 0;
852 // We have enough information to now generate the memcpy call to do the
853 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
855 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
860 //===---------------------------------------===//
861 // 'strncpy' Optimizations
863 struct StrNCpyOpt : public LibCallOptimization {
864 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
865 const FunctionType *FT = Callee->getFunctionType();
866 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
867 FT->getParamType(0) != FT->getParamType(1) ||
868 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
869 !FT->getParamType(2)->isIntegerTy())
872 Value *Dst = CI->getOperand(1);
873 Value *Src = CI->getOperand(2);
874 Value *LenOp = CI->getOperand(3);
876 // See if we can get the length of the input string.
877 uint64_t SrcLen = GetStringLength(Src);
878 if (SrcLen == 0) return 0;
882 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
883 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
889 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
890 Len = LengthArg->getZExtValue();
894 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
896 // These optimizations require TargetData.
899 // Let strncpy handle the zero padding
900 if (Len > SrcLen+1) return 0;
902 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
904 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
910 //===---------------------------------------===//
911 // 'strlen' Optimizations
913 struct StrLenOpt : public LibCallOptimization {
914 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
915 const FunctionType *FT = Callee->getFunctionType();
916 if (FT->getNumParams() != 1 ||
917 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
918 !FT->getReturnType()->isIntegerTy())
921 Value *Src = CI->getOperand(1);
923 // Constant folding: strlen("xyz") -> 3
924 if (uint64_t Len = GetStringLength(Src))
925 return ConstantInt::get(CI->getType(), Len-1);
927 // strlen(x) != 0 --> *x != 0
928 // strlen(x) == 0 --> *x == 0
929 if (IsOnlyUsedInZeroEqualityComparison(CI))
930 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
935 //===---------------------------------------===//
936 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
938 struct StrToOpt : public LibCallOptimization {
939 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
940 const FunctionType *FT = Callee->getFunctionType();
941 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
942 !FT->getParamType(0)->isPointerTy() ||
943 !FT->getParamType(1)->isPointerTy())
946 Value *EndPtr = CI->getOperand(2);
947 if (isa<ConstantPointerNull>(EndPtr)) {
948 CI->setOnlyReadsMemory();
949 CI->addAttribute(1, Attribute::NoCapture);
956 //===---------------------------------------===//
957 // 'strstr' Optimizations
959 struct StrStrOpt : public LibCallOptimization {
960 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
961 const FunctionType *FT = Callee->getFunctionType();
962 if (FT->getNumParams() != 2 ||
963 !FT->getParamType(0)->isPointerTy() ||
964 !FT->getParamType(1)->isPointerTy() ||
965 !FT->getReturnType()->isPointerTy())
968 // fold strstr(x, x) -> x.
969 if (CI->getOperand(1) == CI->getOperand(2))
970 return B.CreateBitCast(CI->getOperand(1), CI->getType());
972 // See if either input string is a constant string.
973 std::string SearchStr, ToFindStr;
974 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
975 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
977 // fold strstr(x, "") -> x.
978 if (HasStr2 && ToFindStr.empty())
979 return B.CreateBitCast(CI->getOperand(1), CI->getType());
981 // If both strings are known, constant fold it.
982 if (HasStr1 && HasStr2) {
983 std::string::size_type Offset = SearchStr.find(ToFindStr);
985 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
986 return Constant::getNullValue(CI->getType());
988 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
989 Value *Result = CastToCStr(CI->getOperand(1), B);
990 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
991 return B.CreateBitCast(Result, CI->getType());
994 // fold strstr(x, "y") -> strchr(x, 'y').
995 if (HasStr2 && ToFindStr.size() == 1)
996 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
1003 //===---------------------------------------===//
1004 // 'memcmp' Optimizations
1006 struct MemCmpOpt : public LibCallOptimization {
1007 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1008 const FunctionType *FT = Callee->getFunctionType();
1009 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
1010 !FT->getParamType(1)->isPointerTy() ||
1011 !FT->getReturnType()->isIntegerTy(32))
1014 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
1016 if (LHS == RHS) // memcmp(s,s,x) -> 0
1017 return Constant::getNullValue(CI->getType());
1019 // Make sure we have a constant length.
1020 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1021 if (!LenC) return 0;
1022 uint64_t Len = LenC->getZExtValue();
1024 if (Len == 0) // memcmp(s1,s2,0) -> 0
1025 return Constant::getNullValue(CI->getType());
1027 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1028 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1029 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
1030 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
1033 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1034 std::string LHSStr, RHSStr;
1035 if (GetConstantStringInfo(LHS, LHSStr) &&
1036 GetConstantStringInfo(RHS, RHSStr)) {
1037 // Make sure we're not reading out-of-bounds memory.
1038 if (Len > LHSStr.length() || Len > RHSStr.length())
1040 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1041 return ConstantInt::get(CI->getType(), Ret);
1048 //===---------------------------------------===//
1049 // 'memcpy' Optimizations
1051 struct MemCpyOpt : public LibCallOptimization {
1052 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1053 // These optimizations require TargetData.
1056 const FunctionType *FT = Callee->getFunctionType();
1057 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1058 !FT->getParamType(0)->isPointerTy() ||
1059 !FT->getParamType(1)->isPointerTy() ||
1060 FT->getParamType(2) != TD->getIntPtrType(*Context))
1063 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1064 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1065 return CI->getOperand(1);
1069 //===---------------------------------------===//
1070 // 'memmove' Optimizations
1072 struct MemMoveOpt : public LibCallOptimization {
1073 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1074 // These optimizations require TargetData.
1077 const FunctionType *FT = Callee->getFunctionType();
1078 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1079 !FT->getParamType(0)->isPointerTy() ||
1080 !FT->getParamType(1)->isPointerTy() ||
1081 FT->getParamType(2) != TD->getIntPtrType(*Context))
1084 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1085 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1086 return CI->getOperand(1);
1090 //===---------------------------------------===//
1091 // 'memset' Optimizations
1093 struct MemSetOpt : public LibCallOptimization {
1094 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1095 // These optimizations require TargetData.
1098 const FunctionType *FT = Callee->getFunctionType();
1099 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1100 !FT->getParamType(0)->isPointerTy() ||
1101 !FT->getParamType(1)->isIntegerTy() ||
1102 FT->getParamType(2) != TD->getIntPtrType(*Context))
1105 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1106 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1108 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1109 return CI->getOperand(1);
1113 //===----------------------------------------------------------------------===//
1114 // Object Size Checking Optimizations
1115 //===----------------------------------------------------------------------===//
1117 //===---------------------------------------===//
1118 // 'memcpy_chk' Optimizations
1120 struct MemCpyChkOpt : public LibCallOptimization {
1121 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1122 // These optimizations require TargetData.
1125 const FunctionType *FT = Callee->getFunctionType();
1126 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1127 !FT->getParamType(0)->isPointerTy() ||
1128 !FT->getParamType(1)->isPointerTy() ||
1129 !FT->getParamType(3)->isIntegerTy() ||
1130 FT->getParamType(2) != TD->getIntPtrType(*Context))
1133 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1136 if (SizeCI->isAllOnesValue()) {
1137 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1138 return CI->getOperand(1);
1145 //===---------------------------------------===//
1146 // 'memset_chk' Optimizations
1148 struct MemSetChkOpt : public LibCallOptimization {
1149 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1150 // These optimizations require TargetData.
1153 const FunctionType *FT = Callee->getFunctionType();
1154 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1155 !FT->getParamType(0)->isPointerTy() ||
1156 !FT->getParamType(1)->isIntegerTy() ||
1157 !FT->getParamType(3)->isIntegerTy() ||
1158 FT->getParamType(2) != TD->getIntPtrType(*Context))
1161 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1164 if (SizeCI->isAllOnesValue()) {
1165 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1167 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1168 return CI->getOperand(1);
1175 //===---------------------------------------===//
1176 // 'memmove_chk' Optimizations
1178 struct MemMoveChkOpt : public LibCallOptimization {
1179 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1180 // These optimizations require TargetData.
1183 const FunctionType *FT = Callee->getFunctionType();
1184 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1185 !FT->getParamType(0)->isPointerTy() ||
1186 !FT->getParamType(1)->isPointerTy() ||
1187 !FT->getParamType(3)->isIntegerTy() ||
1188 FT->getParamType(2) != TD->getIntPtrType(*Context))
1191 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1194 if (SizeCI->isAllOnesValue()) {
1195 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1197 return CI->getOperand(1);
1204 struct StrCpyChkOpt : public LibCallOptimization {
1205 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1206 const FunctionType *FT = Callee->getFunctionType();
1207 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1208 !FT->getParamType(0)->isPointerTy() ||
1209 !FT->getParamType(1)->isPointerTy())
1212 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(3));
1216 // If a) we don't have any length information, or b) we know this will
1217 // fit then just lower to a plain strcpy. Otherwise we'll keep our
1218 // strcpy_chk call which may fail at runtime if the size is too long.
1219 // TODO: It might be nice to get a maximum length out of the possible
1220 // string lengths for varying.
1221 if (SizeCI->isAllOnesValue() ||
1222 SizeCI->getZExtValue() >= GetStringLength(CI->getOperand(2)))
1223 return EmitStrCpy(CI->getOperand(1), CI->getOperand(2), B);
1230 //===----------------------------------------------------------------------===//
1231 // Math Library Optimizations
1232 //===----------------------------------------------------------------------===//
1234 //===---------------------------------------===//
1235 // 'pow*' Optimizations
1237 struct PowOpt : public LibCallOptimization {
1238 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1239 const FunctionType *FT = Callee->getFunctionType();
1240 // Just make sure this has 2 arguments of the same FP type, which match the
1242 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1243 FT->getParamType(0) != FT->getParamType(1) ||
1244 !FT->getParamType(0)->isFloatingPointTy())
1247 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1248 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1249 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1251 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1252 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1255 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1256 if (Op2C == 0) return 0;
1258 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1259 return ConstantFP::get(CI->getType(), 1.0);
1261 if (Op2C->isExactlyValue(0.5)) {
1262 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1263 // This is faster than calling pow, and still handles negative zero
1264 // and negative infinite correctly.
1265 // TODO: In fast-math mode, this could be just sqrt(x).
1266 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1267 Value *Inf = ConstantFP::getInfinity(CI->getType());
1268 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1269 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1270 Callee->getAttributes());
1271 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1272 Callee->getAttributes());
1273 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1274 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1278 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1280 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1281 return B.CreateFMul(Op1, Op1, "pow2");
1282 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1283 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1289 //===---------------------------------------===//
1290 // 'exp2' Optimizations
1292 struct Exp2Opt : public LibCallOptimization {
1293 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1294 const FunctionType *FT = Callee->getFunctionType();
1295 // Just make sure this has 1 argument of FP type, which matches the
1297 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1298 !FT->getParamType(0)->isFloatingPointTy())
1301 Value *Op = CI->getOperand(1);
1302 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1303 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1304 Value *LdExpArg = 0;
1305 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1306 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1307 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1308 Type::getInt32Ty(*Context), "tmp");
1309 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1310 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1311 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1312 Type::getInt32Ty(*Context), "tmp");
1317 if (Op->getType()->isFloatTy())
1319 else if (Op->getType()->isDoubleTy())
1324 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1325 if (!Op->getType()->isFloatTy())
1326 One = ConstantExpr::getFPExtend(One, Op->getType());
1328 Module *M = Caller->getParent();
1329 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1331 Type::getInt32Ty(*Context),NULL);
1332 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1333 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1334 CI->setCallingConv(F->getCallingConv());
1342 //===---------------------------------------===//
1343 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1345 struct UnaryDoubleFPOpt : public LibCallOptimization {
1346 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1347 const FunctionType *FT = Callee->getFunctionType();
1348 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1349 !FT->getParamType(0)->isDoubleTy())
1352 // If this is something like 'floor((double)floatval)', convert to floorf.
1353 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1354 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1357 // floor((double)floatval) -> (double)floorf(floatval)
1358 Value *V = Cast->getOperand(0);
1359 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1360 Callee->getAttributes());
1361 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1365 //===----------------------------------------------------------------------===//
1366 // Integer Optimizations
1367 //===----------------------------------------------------------------------===//
1369 //===---------------------------------------===//
1370 // 'ffs*' Optimizations
1372 struct FFSOpt : public LibCallOptimization {
1373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1374 const FunctionType *FT = Callee->getFunctionType();
1375 // Just make sure this has 2 arguments of the same FP type, which match the
1377 if (FT->getNumParams() != 1 ||
1378 !FT->getReturnType()->isIntegerTy(32) ||
1379 !FT->getParamType(0)->isIntegerTy())
1382 Value *Op = CI->getOperand(1);
1385 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1386 if (CI->getValue() == 0) // ffs(0) -> 0.
1387 return Constant::getNullValue(CI->getType());
1388 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1389 CI->getValue().countTrailingZeros()+1);
1392 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1393 const Type *ArgType = Op->getType();
1394 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1395 Intrinsic::cttz, &ArgType, 1);
1396 Value *V = B.CreateCall(F, Op, "cttz");
1397 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1398 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1400 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1401 return B.CreateSelect(Cond, V,
1402 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1406 //===---------------------------------------===//
1407 // 'isdigit' Optimizations
1409 struct IsDigitOpt : public LibCallOptimization {
1410 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1411 const FunctionType *FT = Callee->getFunctionType();
1412 // We require integer(i32)
1413 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1414 !FT->getParamType(0)->isIntegerTy(32))
1417 // isdigit(c) -> (c-'0') <u 10
1418 Value *Op = CI->getOperand(1);
1419 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1421 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1423 return B.CreateZExt(Op, CI->getType());
1427 //===---------------------------------------===//
1428 // 'isascii' Optimizations
1430 struct IsAsciiOpt : public LibCallOptimization {
1431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1432 const FunctionType *FT = Callee->getFunctionType();
1433 // We require integer(i32)
1434 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1435 !FT->getParamType(0)->isIntegerTy(32))
1438 // isascii(c) -> c <u 128
1439 Value *Op = CI->getOperand(1);
1440 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1442 return B.CreateZExt(Op, CI->getType());
1446 //===---------------------------------------===//
1447 // 'abs', 'labs', 'llabs' Optimizations
1449 struct AbsOpt : public LibCallOptimization {
1450 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1451 const FunctionType *FT = Callee->getFunctionType();
1452 // We require integer(integer) where the types agree.
1453 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1454 FT->getParamType(0) != FT->getReturnType())
1457 // abs(x) -> x >s -1 ? x : -x
1458 Value *Op = CI->getOperand(1);
1459 Value *Pos = B.CreateICmpSGT(Op,
1460 Constant::getAllOnesValue(Op->getType()),
1462 Value *Neg = B.CreateNeg(Op, "neg");
1463 return B.CreateSelect(Pos, Op, Neg);
1468 //===---------------------------------------===//
1469 // 'toascii' Optimizations
1471 struct ToAsciiOpt : public LibCallOptimization {
1472 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1473 const FunctionType *FT = Callee->getFunctionType();
1474 // We require i32(i32)
1475 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1476 !FT->getParamType(0)->isIntegerTy(32))
1479 // isascii(c) -> c & 0x7f
1480 return B.CreateAnd(CI->getOperand(1),
1481 ConstantInt::get(CI->getType(),0x7F));
1485 //===----------------------------------------------------------------------===//
1486 // Formatting and IO Optimizations
1487 //===----------------------------------------------------------------------===//
1489 //===---------------------------------------===//
1490 // 'printf' Optimizations
1492 struct PrintFOpt : public LibCallOptimization {
1493 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1494 // Require one fixed pointer argument and an integer/void result.
1495 const FunctionType *FT = Callee->getFunctionType();
1496 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1497 !(FT->getReturnType()->isIntegerTy() ||
1498 FT->getReturnType()->isVoidTy()))
1501 // Check for a fixed format string.
1502 std::string FormatStr;
1503 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1506 // Empty format string -> noop.
1507 if (FormatStr.empty()) // Tolerate printf's declared void.
1508 return CI->use_empty() ? (Value*)CI :
1509 ConstantInt::get(CI->getType(), 0);
1511 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1512 // in case there is an error writing to stdout.
1513 if (FormatStr.size() == 1) {
1514 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1516 if (CI->use_empty()) return CI;
1517 return B.CreateIntCast(Res, CI->getType(), true);
1520 // printf("foo\n") --> puts("foo")
1521 if (FormatStr[FormatStr.size()-1] == '\n' &&
1522 FormatStr.find('%') == std::string::npos) { // no format characters.
1523 // Create a string literal with no \n on it. We expect the constant merge
1524 // pass to be run after this pass, to merge duplicate strings.
1525 FormatStr.erase(FormatStr.end()-1);
1526 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1527 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1528 GlobalVariable::InternalLinkage, C, "str");
1530 return CI->use_empty() ? (Value*)CI :
1531 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1534 // Optimize specific format strings.
1535 // printf("%c", chr) --> putchar(*(i8*)dst)
1536 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1537 CI->getOperand(2)->getType()->isIntegerTy()) {
1538 Value *Res = EmitPutChar(CI->getOperand(2), B);
1540 if (CI->use_empty()) return CI;
1541 return B.CreateIntCast(Res, CI->getType(), true);
1544 // printf("%s\n", str) --> puts(str)
1545 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1546 CI->getOperand(2)->getType()->isPointerTy() &&
1548 EmitPutS(CI->getOperand(2), B);
1555 //===---------------------------------------===//
1556 // 'sprintf' Optimizations
1558 struct SPrintFOpt : public LibCallOptimization {
1559 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1560 // Require two fixed pointer arguments and an integer result.
1561 const FunctionType *FT = Callee->getFunctionType();
1562 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1563 !FT->getParamType(1)->isPointerTy() ||
1564 !FT->getReturnType()->isIntegerTy())
1567 // Check for a fixed format string.
1568 std::string FormatStr;
1569 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1572 // If we just have a format string (nothing else crazy) transform it.
1573 if (CI->getNumOperands() == 3) {
1574 // Make sure there's no % in the constant array. We could try to handle
1575 // %% -> % in the future if we cared.
1576 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1577 if (FormatStr[i] == '%')
1578 return 0; // we found a format specifier, bail out.
1580 // These optimizations require TargetData.
1583 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1584 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1586 (TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1587 return ConstantInt::get(CI->getType(), FormatStr.size());
1590 // The remaining optimizations require the format string to be "%s" or "%c"
1591 // and have an extra operand.
1592 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1595 // Decode the second character of the format string.
1596 if (FormatStr[1] == 'c') {
1597 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1598 if (!CI->getOperand(3)->getType()->isIntegerTy()) return 0;
1599 Value *V = B.CreateTrunc(CI->getOperand(3),
1600 Type::getInt8Ty(*Context), "char");
1601 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1602 B.CreateStore(V, Ptr);
1603 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1605 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1607 return ConstantInt::get(CI->getType(), 1);
1610 if (FormatStr[1] == 's') {
1611 // These optimizations require TargetData.
1614 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1615 if (!CI->getOperand(3)->getType()->isPointerTy()) return 0;
1617 Value *Len = EmitStrLen(CI->getOperand(3), B);
1618 Value *IncLen = B.CreateAdd(Len,
1619 ConstantInt::get(Len->getType(), 1),
1621 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1623 // The sprintf result is the unincremented number of bytes in the string.
1624 return B.CreateIntCast(Len, CI->getType(), false);
1630 //===---------------------------------------===//
1631 // 'fwrite' Optimizations
1633 struct FWriteOpt : public LibCallOptimization {
1634 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1635 // Require a pointer, an integer, an integer, a pointer, returning integer.
1636 const FunctionType *FT = Callee->getFunctionType();
1637 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1638 !FT->getParamType(1)->isIntegerTy() ||
1639 !FT->getParamType(2)->isIntegerTy() ||
1640 !FT->getParamType(3)->isPointerTy() ||
1641 !FT->getReturnType()->isIntegerTy())
1644 // Get the element size and count.
1645 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1646 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1647 if (!SizeC || !CountC) return 0;
1648 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1650 // If this is writing zero records, remove the call (it's a noop).
1652 return ConstantInt::get(CI->getType(), 0);
1654 // If this is writing one byte, turn it into fputc.
1655 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1656 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1657 EmitFPutC(Char, CI->getOperand(4), B);
1658 return ConstantInt::get(CI->getType(), 1);
1665 //===---------------------------------------===//
1666 // 'fputs' Optimizations
1668 struct FPutsOpt : public LibCallOptimization {
1669 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1670 // These optimizations require TargetData.
1673 // Require two pointers. Also, we can't optimize if return value is used.
1674 const FunctionType *FT = Callee->getFunctionType();
1675 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1676 !FT->getParamType(1)->isPointerTy() ||
1680 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1681 uint64_t Len = GetStringLength(CI->getOperand(1));
1683 EmitFWrite(CI->getOperand(1),
1684 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1685 CI->getOperand(2), B);
1686 return CI; // Known to have no uses (see above).
1690 //===---------------------------------------===//
1691 // 'fprintf' Optimizations
1693 struct FPrintFOpt : public LibCallOptimization {
1694 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1695 // Require two fixed paramters as pointers and integer result.
1696 const FunctionType *FT = Callee->getFunctionType();
1697 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1698 !FT->getParamType(1)->isPointerTy() ||
1699 !FT->getReturnType()->isIntegerTy())
1702 // All the optimizations depend on the format string.
1703 std::string FormatStr;
1704 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1707 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1708 if (CI->getNumOperands() == 3) {
1709 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1710 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1711 return 0; // We found a format specifier.
1713 // These optimizations require TargetData.
1716 EmitFWrite(CI->getOperand(2),
1717 ConstantInt::get(TD->getIntPtrType(*Context),
1719 CI->getOperand(1), B);
1720 return ConstantInt::get(CI->getType(), FormatStr.size());
1723 // The remaining optimizations require the format string to be "%s" or "%c"
1724 // and have an extra operand.
1725 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1728 // Decode the second character of the format string.
1729 if (FormatStr[1] == 'c') {
1730 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1731 if (!CI->getOperand(3)->getType()->isIntegerTy()) return 0;
1732 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1733 return ConstantInt::get(CI->getType(), 1);
1736 if (FormatStr[1] == 's') {
1737 // fprintf(F, "%s", str) -> fputs(str, F)
1738 if (!CI->getOperand(3)->getType()->isPointerTy() || !CI->use_empty())
1740 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1747 } // end anonymous namespace.
1749 //===----------------------------------------------------------------------===//
1750 // SimplifyLibCalls Pass Implementation
1751 //===----------------------------------------------------------------------===//
1754 /// This pass optimizes well known library functions from libc and libm.
1756 class SimplifyLibCalls : public FunctionPass {
1757 StringMap<LibCallOptimization*> Optimizations;
1758 // String and Memory LibCall Optimizations
1759 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1760 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1761 StrToOpt StrTo; StrStrOpt StrStr;
1762 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1763 // Math Library Optimizations
1764 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1765 // Integer Optimizations
1766 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1768 // Formatting and IO Optimizations
1769 SPrintFOpt SPrintF; PrintFOpt PrintF;
1770 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1772 // Object Size Checking
1773 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1774 StrCpyChkOpt StrCpyChk;
1776 bool Modified; // This is only used by doInitialization.
1778 static char ID; // Pass identification
1779 SimplifyLibCalls() : FunctionPass(&ID) {}
1781 void InitOptimizations();
1782 bool runOnFunction(Function &F);
1784 void setDoesNotAccessMemory(Function &F);
1785 void setOnlyReadsMemory(Function &F);
1786 void setDoesNotThrow(Function &F);
1787 void setDoesNotCapture(Function &F, unsigned n);
1788 void setDoesNotAlias(Function &F, unsigned n);
1789 bool doInitialization(Module &M);
1791 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1794 char SimplifyLibCalls::ID = 0;
1795 } // end anonymous namespace.
1797 static RegisterPass<SimplifyLibCalls>
1798 X("simplify-libcalls", "Simplify well-known library calls");
1800 // Public interface to the Simplify LibCalls pass.
1801 FunctionPass *llvm::createSimplifyLibCallsPass() {
1802 return new SimplifyLibCalls();
1805 /// Optimizations - Populate the Optimizations map with all the optimizations
1807 void SimplifyLibCalls::InitOptimizations() {
1808 // String and Memory LibCall Optimizations
1809 Optimizations["strcat"] = &StrCat;
1810 Optimizations["strncat"] = &StrNCat;
1811 Optimizations["strchr"] = &StrChr;
1812 Optimizations["strcmp"] = &StrCmp;
1813 Optimizations["strncmp"] = &StrNCmp;
1814 Optimizations["strcpy"] = &StrCpy;
1815 Optimizations["strncpy"] = &StrNCpy;
1816 Optimizations["strlen"] = &StrLen;
1817 Optimizations["strtol"] = &StrTo;
1818 Optimizations["strtod"] = &StrTo;
1819 Optimizations["strtof"] = &StrTo;
1820 Optimizations["strtoul"] = &StrTo;
1821 Optimizations["strtoll"] = &StrTo;
1822 Optimizations["strtold"] = &StrTo;
1823 Optimizations["strtoull"] = &StrTo;
1824 Optimizations["strstr"] = &StrStr;
1825 Optimizations["memcmp"] = &MemCmp;
1826 Optimizations["memcpy"] = &MemCpy;
1827 Optimizations["memmove"] = &MemMove;
1828 Optimizations["memset"] = &MemSet;
1830 // Math Library Optimizations
1831 Optimizations["powf"] = &Pow;
1832 Optimizations["pow"] = &Pow;
1833 Optimizations["powl"] = &Pow;
1834 Optimizations["llvm.pow.f32"] = &Pow;
1835 Optimizations["llvm.pow.f64"] = &Pow;
1836 Optimizations["llvm.pow.f80"] = &Pow;
1837 Optimizations["llvm.pow.f128"] = &Pow;
1838 Optimizations["llvm.pow.ppcf128"] = &Pow;
1839 Optimizations["exp2l"] = &Exp2;
1840 Optimizations["exp2"] = &Exp2;
1841 Optimizations["exp2f"] = &Exp2;
1842 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1843 Optimizations["llvm.exp2.f128"] = &Exp2;
1844 Optimizations["llvm.exp2.f80"] = &Exp2;
1845 Optimizations["llvm.exp2.f64"] = &Exp2;
1846 Optimizations["llvm.exp2.f32"] = &Exp2;
1849 Optimizations["floor"] = &UnaryDoubleFP;
1852 Optimizations["ceil"] = &UnaryDoubleFP;
1855 Optimizations["round"] = &UnaryDoubleFP;
1858 Optimizations["rint"] = &UnaryDoubleFP;
1860 #ifdef HAVE_NEARBYINTF
1861 Optimizations["nearbyint"] = &UnaryDoubleFP;
1864 // Integer Optimizations
1865 Optimizations["ffs"] = &FFS;
1866 Optimizations["ffsl"] = &FFS;
1867 Optimizations["ffsll"] = &FFS;
1868 Optimizations["abs"] = &Abs;
1869 Optimizations["labs"] = &Abs;
1870 Optimizations["llabs"] = &Abs;
1871 Optimizations["isdigit"] = &IsDigit;
1872 Optimizations["isascii"] = &IsAscii;
1873 Optimizations["toascii"] = &ToAscii;
1875 // Formatting and IO Optimizations
1876 Optimizations["sprintf"] = &SPrintF;
1877 Optimizations["printf"] = &PrintF;
1878 Optimizations["fwrite"] = &FWrite;
1879 Optimizations["fputs"] = &FPuts;
1880 Optimizations["fprintf"] = &FPrintF;
1882 // Object Size Checking
1883 Optimizations["__memcpy_chk"] = &MemCpyChk;
1884 Optimizations["__memset_chk"] = &MemSetChk;
1885 Optimizations["__memmove_chk"] = &MemMoveChk;
1886 Optimizations["__strcpy_chk"] = &StrCpyChk;
1890 /// runOnFunction - Top level algorithm.
1892 bool SimplifyLibCalls::runOnFunction(Function &F) {
1893 if (Optimizations.empty())
1894 InitOptimizations();
1896 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1898 IRBuilder<> Builder(F.getContext());
1900 bool Changed = false;
1901 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1902 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1903 // Ignore non-calls.
1904 CallInst *CI = dyn_cast<CallInst>(I++);
1907 // Ignore indirect calls and calls to non-external functions.
1908 Function *Callee = CI->getCalledFunction();
1909 if (Callee == 0 || !Callee->isDeclaration() ||
1910 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1913 // Ignore unknown calls.
1914 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1917 // Set the builder to the instruction after the call.
1918 Builder.SetInsertPoint(BB, I);
1920 // Try to optimize this call.
1921 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1922 if (Result == 0) continue;
1924 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1925 dbgs() << " into: " << *Result << "\n");
1927 // Something changed!
1931 // Inspect the instruction after the call (which was potentially just
1935 if (CI != Result && !CI->use_empty()) {
1936 CI->replaceAllUsesWith(Result);
1937 if (!Result->hasName())
1938 Result->takeName(CI);
1940 CI->eraseFromParent();
1946 // Utility methods for doInitialization.
1948 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1949 if (!F.doesNotAccessMemory()) {
1950 F.setDoesNotAccessMemory();
1955 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1956 if (!F.onlyReadsMemory()) {
1957 F.setOnlyReadsMemory();
1962 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1963 if (!F.doesNotThrow()) {
1964 F.setDoesNotThrow();
1969 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1970 if (!F.doesNotCapture(n)) {
1971 F.setDoesNotCapture(n);
1976 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1977 if (!F.doesNotAlias(n)) {
1978 F.setDoesNotAlias(n);
1984 /// doInitialization - Add attributes to well-known functions.
1986 bool SimplifyLibCalls::doInitialization(Module &M) {
1988 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1990 if (!F.isDeclaration())
1996 const FunctionType *FTy = F.getFunctionType();
1998 StringRef Name = F.getName();
2001 if (Name == "strlen") {
2002 if (FTy->getNumParams() != 1 ||
2003 !FTy->getParamType(0)->isPointerTy())
2005 setOnlyReadsMemory(F);
2007 setDoesNotCapture(F, 1);
2008 } else if (Name == "strcpy" ||
2014 Name == "strtoul" ||
2015 Name == "strtoll" ||
2016 Name == "strtold" ||
2017 Name == "strncat" ||
2018 Name == "strncpy" ||
2019 Name == "strtoull") {
2020 if (FTy->getNumParams() < 2 ||
2021 !FTy->getParamType(1)->isPointerTy())
2024 setDoesNotCapture(F, 2);
2025 } else if (Name == "strxfrm") {
2026 if (FTy->getNumParams() != 3 ||
2027 !FTy->getParamType(0)->isPointerTy() ||
2028 !FTy->getParamType(1)->isPointerTy())
2031 setDoesNotCapture(F, 1);
2032 setDoesNotCapture(F, 2);
2033 } else if (Name == "strcmp" ||
2035 Name == "strncmp" ||
2036 Name ==" strcspn" ||
2037 Name == "strcoll" ||
2038 Name == "strcasecmp" ||
2039 Name == "strncasecmp") {
2040 if (FTy->getNumParams() < 2 ||
2041 !FTy->getParamType(0)->isPointerTy() ||
2042 !FTy->getParamType(1)->isPointerTy())
2044 setOnlyReadsMemory(F);
2046 setDoesNotCapture(F, 1);
2047 setDoesNotCapture(F, 2);
2048 } else if (Name == "strstr" ||
2049 Name == "strpbrk") {
2050 if (FTy->getNumParams() != 2 ||
2051 !FTy->getParamType(1)->isPointerTy())
2053 setOnlyReadsMemory(F);
2055 setDoesNotCapture(F, 2);
2056 } else if (Name == "strtok" ||
2057 Name == "strtok_r") {
2058 if (FTy->getNumParams() < 2 ||
2059 !FTy->getParamType(1)->isPointerTy())
2062 setDoesNotCapture(F, 2);
2063 } else if (Name == "scanf" ||
2065 Name == "setvbuf") {
2066 if (FTy->getNumParams() < 1 ||
2067 !FTy->getParamType(0)->isPointerTy())
2070 setDoesNotCapture(F, 1);
2071 } else if (Name == "strdup" ||
2072 Name == "strndup") {
2073 if (FTy->getNumParams() < 1 ||
2074 !FTy->getReturnType()->isPointerTy() ||
2075 !FTy->getParamType(0)->isPointerTy())
2078 setDoesNotAlias(F, 0);
2079 setDoesNotCapture(F, 1);
2080 } else if (Name == "stat" ||
2082 Name == "sprintf" ||
2083 Name == "statvfs") {
2084 if (FTy->getNumParams() < 2 ||
2085 !FTy->getParamType(0)->isPointerTy() ||
2086 !FTy->getParamType(1)->isPointerTy())
2089 setDoesNotCapture(F, 1);
2090 setDoesNotCapture(F, 2);
2091 } else if (Name == "snprintf") {
2092 if (FTy->getNumParams() != 3 ||
2093 !FTy->getParamType(0)->isPointerTy() ||
2094 !FTy->getParamType(2)->isPointerTy())
2097 setDoesNotCapture(F, 1);
2098 setDoesNotCapture(F, 3);
2099 } else if (Name == "setitimer") {
2100 if (FTy->getNumParams() != 3 ||
2101 !FTy->getParamType(1)->isPointerTy() ||
2102 !FTy->getParamType(2)->isPointerTy())
2105 setDoesNotCapture(F, 2);
2106 setDoesNotCapture(F, 3);
2107 } else if (Name == "system") {
2108 if (FTy->getNumParams() != 1 ||
2109 !FTy->getParamType(0)->isPointerTy())
2111 // May throw; "system" is a valid pthread cancellation point.
2112 setDoesNotCapture(F, 1);
2116 if (Name == "malloc") {
2117 if (FTy->getNumParams() != 1 ||
2118 !FTy->getReturnType()->isPointerTy())
2121 setDoesNotAlias(F, 0);
2122 } else if (Name == "memcmp") {
2123 if (FTy->getNumParams() != 3 ||
2124 !FTy->getParamType(0)->isPointerTy() ||
2125 !FTy->getParamType(1)->isPointerTy())
2127 setOnlyReadsMemory(F);
2129 setDoesNotCapture(F, 1);
2130 setDoesNotCapture(F, 2);
2131 } else if (Name == "memchr" ||
2132 Name == "memrchr") {
2133 if (FTy->getNumParams() != 3)
2135 setOnlyReadsMemory(F);
2137 } else if (Name == "modf" ||
2141 Name == "memccpy" ||
2142 Name == "memmove") {
2143 if (FTy->getNumParams() < 2 ||
2144 !FTy->getParamType(1)->isPointerTy())
2147 setDoesNotCapture(F, 2);
2148 } else if (Name == "memalign") {
2149 if (!FTy->getReturnType()->isPointerTy())
2151 setDoesNotAlias(F, 0);
2152 } else if (Name == "mkdir" ||
2154 if (FTy->getNumParams() == 0 ||
2155 !FTy->getParamType(0)->isPointerTy())
2158 setDoesNotCapture(F, 1);
2162 if (Name == "realloc") {
2163 if (FTy->getNumParams() != 2 ||
2164 !FTy->getParamType(0)->isPointerTy() ||
2165 !FTy->getReturnType()->isPointerTy())
2168 setDoesNotAlias(F, 0);
2169 setDoesNotCapture(F, 1);
2170 } else if (Name == "read") {
2171 if (FTy->getNumParams() != 3 ||
2172 !FTy->getParamType(1)->isPointerTy())
2174 // May throw; "read" is a valid pthread cancellation point.
2175 setDoesNotCapture(F, 2);
2176 } else if (Name == "rmdir" ||
2179 Name == "realpath") {
2180 if (FTy->getNumParams() < 1 ||
2181 !FTy->getParamType(0)->isPointerTy())
2184 setDoesNotCapture(F, 1);
2185 } else if (Name == "rename" ||
2186 Name == "readlink") {
2187 if (FTy->getNumParams() < 2 ||
2188 !FTy->getParamType(0)->isPointerTy() ||
2189 !FTy->getParamType(1)->isPointerTy())
2192 setDoesNotCapture(F, 1);
2193 setDoesNotCapture(F, 2);
2197 if (Name == "write") {
2198 if (FTy->getNumParams() != 3 ||
2199 !FTy->getParamType(1)->isPointerTy())
2201 // May throw; "write" is a valid pthread cancellation point.
2202 setDoesNotCapture(F, 2);
2206 if (Name == "bcopy") {
2207 if (FTy->getNumParams() != 3 ||
2208 !FTy->getParamType(0)->isPointerTy() ||
2209 !FTy->getParamType(1)->isPointerTy())
2212 setDoesNotCapture(F, 1);
2213 setDoesNotCapture(F, 2);
2214 } else if (Name == "bcmp") {
2215 if (FTy->getNumParams() != 3 ||
2216 !FTy->getParamType(0)->isPointerTy() ||
2217 !FTy->getParamType(1)->isPointerTy())
2220 setOnlyReadsMemory(F);
2221 setDoesNotCapture(F, 1);
2222 setDoesNotCapture(F, 2);
2223 } else if (Name == "bzero") {
2224 if (FTy->getNumParams() != 2 ||
2225 !FTy->getParamType(0)->isPointerTy())
2228 setDoesNotCapture(F, 1);
2232 if (Name == "calloc") {
2233 if (FTy->getNumParams() != 2 ||
2234 !FTy->getReturnType()->isPointerTy())
2237 setDoesNotAlias(F, 0);
2238 } else if (Name == "chmod" ||
2240 Name == "ctermid" ||
2241 Name == "clearerr" ||
2242 Name == "closedir") {
2243 if (FTy->getNumParams() == 0 ||
2244 !FTy->getParamType(0)->isPointerTy())
2247 setDoesNotCapture(F, 1);
2251 if (Name == "atoi" ||
2255 if (FTy->getNumParams() != 1 ||
2256 !FTy->getParamType(0)->isPointerTy())
2259 setOnlyReadsMemory(F);
2260 setDoesNotCapture(F, 1);
2261 } else if (Name == "access") {
2262 if (FTy->getNumParams() != 2 ||
2263 !FTy->getParamType(0)->isPointerTy())
2266 setDoesNotCapture(F, 1);
2270 if (Name == "fopen") {
2271 if (FTy->getNumParams() != 2 ||
2272 !FTy->getReturnType()->isPointerTy() ||
2273 !FTy->getParamType(0)->isPointerTy() ||
2274 !FTy->getParamType(1)->isPointerTy())
2277 setDoesNotAlias(F, 0);
2278 setDoesNotCapture(F, 1);
2279 setDoesNotCapture(F, 2);
2280 } else if (Name == "fdopen") {
2281 if (FTy->getNumParams() != 2 ||
2282 !FTy->getReturnType()->isPointerTy() ||
2283 !FTy->getParamType(1)->isPointerTy())
2286 setDoesNotAlias(F, 0);
2287 setDoesNotCapture(F, 2);
2288 } else if (Name == "feof" ||
2298 Name == "fsetpos" ||
2299 Name == "flockfile" ||
2300 Name == "funlockfile" ||
2301 Name == "ftrylockfile") {
2302 if (FTy->getNumParams() == 0 ||
2303 !FTy->getParamType(0)->isPointerTy())
2306 setDoesNotCapture(F, 1);
2307 } else if (Name == "ferror") {
2308 if (FTy->getNumParams() != 1 ||
2309 !FTy->getParamType(0)->isPointerTy())
2312 setDoesNotCapture(F, 1);
2313 setOnlyReadsMemory(F);
2314 } else if (Name == "fputc" ||
2319 Name == "fstatvfs") {
2320 if (FTy->getNumParams() != 2 ||
2321 !FTy->getParamType(1)->isPointerTy())
2324 setDoesNotCapture(F, 2);
2325 } else if (Name == "fgets") {
2326 if (FTy->getNumParams() != 3 ||
2327 !FTy->getParamType(0)->isPointerTy() ||
2328 !FTy->getParamType(2)->isPointerTy())
2331 setDoesNotCapture(F, 3);
2332 } else if (Name == "fread" ||
2334 if (FTy->getNumParams() != 4 ||
2335 !FTy->getParamType(0)->isPointerTy() ||
2336 !FTy->getParamType(3)->isPointerTy())
2339 setDoesNotCapture(F, 1);
2340 setDoesNotCapture(F, 4);
2341 } else if (Name == "fputs" ||
2343 Name == "fprintf" ||
2344 Name == "fgetpos") {
2345 if (FTy->getNumParams() < 2 ||
2346 !FTy->getParamType(0)->isPointerTy() ||
2347 !FTy->getParamType(1)->isPointerTy())
2350 setDoesNotCapture(F, 1);
2351 setDoesNotCapture(F, 2);
2355 if (Name == "getc" ||
2356 Name == "getlogin_r" ||
2357 Name == "getc_unlocked") {
2358 if (FTy->getNumParams() == 0 ||
2359 !FTy->getParamType(0)->isPointerTy())
2362 setDoesNotCapture(F, 1);
2363 } else if (Name == "getenv") {
2364 if (FTy->getNumParams() != 1 ||
2365 !FTy->getParamType(0)->isPointerTy())
2368 setOnlyReadsMemory(F);
2369 setDoesNotCapture(F, 1);
2370 } else if (Name == "gets" ||
2371 Name == "getchar") {
2373 } else if (Name == "getitimer") {
2374 if (FTy->getNumParams() != 2 ||
2375 !FTy->getParamType(1)->isPointerTy())
2378 setDoesNotCapture(F, 2);
2379 } else if (Name == "getpwnam") {
2380 if (FTy->getNumParams() != 1 ||
2381 !FTy->getParamType(0)->isPointerTy())
2384 setDoesNotCapture(F, 1);
2388 if (Name == "ungetc") {
2389 if (FTy->getNumParams() != 2 ||
2390 !FTy->getParamType(1)->isPointerTy())
2393 setDoesNotCapture(F, 2);
2394 } else if (Name == "uname" ||
2396 Name == "unsetenv") {
2397 if (FTy->getNumParams() != 1 ||
2398 !FTy->getParamType(0)->isPointerTy())
2401 setDoesNotCapture(F, 1);
2402 } else if (Name == "utime" ||
2404 if (FTy->getNumParams() != 2 ||
2405 !FTy->getParamType(0)->isPointerTy() ||
2406 !FTy->getParamType(1)->isPointerTy())
2409 setDoesNotCapture(F, 1);
2410 setDoesNotCapture(F, 2);
2414 if (Name == "putc") {
2415 if (FTy->getNumParams() != 2 ||
2416 !FTy->getParamType(1)->isPointerTy())
2419 setDoesNotCapture(F, 2);
2420 } else if (Name == "puts" ||
2423 if (FTy->getNumParams() != 1 ||
2424 !FTy->getParamType(0)->isPointerTy())
2427 setDoesNotCapture(F, 1);
2428 } else if (Name == "pread" ||
2430 if (FTy->getNumParams() != 4 ||
2431 !FTy->getParamType(1)->isPointerTy())
2433 // May throw; these are valid pthread cancellation points.
2434 setDoesNotCapture(F, 2);
2435 } else if (Name == "putchar") {
2437 } else if (Name == "popen") {
2438 if (FTy->getNumParams() != 2 ||
2439 !FTy->getReturnType()->isPointerTy() ||
2440 !FTy->getParamType(0)->isPointerTy() ||
2441 !FTy->getParamType(1)->isPointerTy())
2444 setDoesNotAlias(F, 0);
2445 setDoesNotCapture(F, 1);
2446 setDoesNotCapture(F, 2);
2447 } else if (Name == "pclose") {
2448 if (FTy->getNumParams() != 1 ||
2449 !FTy->getParamType(0)->isPointerTy())
2452 setDoesNotCapture(F, 1);
2456 if (Name == "vscanf") {
2457 if (FTy->getNumParams() != 2 ||
2458 !FTy->getParamType(1)->isPointerTy())
2461 setDoesNotCapture(F, 1);
2462 } else if (Name == "vsscanf" ||
2463 Name == "vfscanf") {
2464 if (FTy->getNumParams() != 3 ||
2465 !FTy->getParamType(1)->isPointerTy() ||
2466 !FTy->getParamType(2)->isPointerTy())
2469 setDoesNotCapture(F, 1);
2470 setDoesNotCapture(F, 2);
2471 } else if (Name == "valloc") {
2472 if (!FTy->getReturnType()->isPointerTy())
2475 setDoesNotAlias(F, 0);
2476 } else if (Name == "vprintf") {
2477 if (FTy->getNumParams() != 2 ||
2478 !FTy->getParamType(0)->isPointerTy())
2481 setDoesNotCapture(F, 1);
2482 } else if (Name == "vfprintf" ||
2483 Name == "vsprintf") {
2484 if (FTy->getNumParams() != 3 ||
2485 !FTy->getParamType(0)->isPointerTy() ||
2486 !FTy->getParamType(1)->isPointerTy())
2489 setDoesNotCapture(F, 1);
2490 setDoesNotCapture(F, 2);
2491 } else if (Name == "vsnprintf") {
2492 if (FTy->getNumParams() != 4 ||
2493 !FTy->getParamType(0)->isPointerTy() ||
2494 !FTy->getParamType(2)->isPointerTy())
2497 setDoesNotCapture(F, 1);
2498 setDoesNotCapture(F, 3);
2502 if (Name == "open") {
2503 if (FTy->getNumParams() < 2 ||
2504 !FTy->getParamType(0)->isPointerTy())
2506 // May throw; "open" is a valid pthread cancellation point.
2507 setDoesNotCapture(F, 1);
2508 } else if (Name == "opendir") {
2509 if (FTy->getNumParams() != 1 ||
2510 !FTy->getReturnType()->isPointerTy() ||
2511 !FTy->getParamType(0)->isPointerTy())
2514 setDoesNotAlias(F, 0);
2515 setDoesNotCapture(F, 1);
2519 if (Name == "tmpfile") {
2520 if (!FTy->getReturnType()->isPointerTy())
2523 setDoesNotAlias(F, 0);
2524 } else if (Name == "times") {
2525 if (FTy->getNumParams() != 1 ||
2526 !FTy->getParamType(0)->isPointerTy())
2529 setDoesNotCapture(F, 1);
2533 if (Name == "htonl" ||
2536 setDoesNotAccessMemory(F);
2540 if (Name == "ntohl" ||
2543 setDoesNotAccessMemory(F);
2547 if (Name == "lstat") {
2548 if (FTy->getNumParams() != 2 ||
2549 !FTy->getParamType(0)->isPointerTy() ||
2550 !FTy->getParamType(1)->isPointerTy())
2553 setDoesNotCapture(F, 1);
2554 setDoesNotCapture(F, 2);
2555 } else if (Name == "lchown") {
2556 if (FTy->getNumParams() != 3 ||
2557 !FTy->getParamType(0)->isPointerTy())
2560 setDoesNotCapture(F, 1);
2564 if (Name == "qsort") {
2565 if (FTy->getNumParams() != 4 ||
2566 !FTy->getParamType(3)->isPointerTy())
2568 // May throw; places call through function pointer.
2569 setDoesNotCapture(F, 4);
2573 if (Name == "__strdup" ||
2574 Name == "__strndup") {
2575 if (FTy->getNumParams() < 1 ||
2576 !FTy->getReturnType()->isPointerTy() ||
2577 !FTy->getParamType(0)->isPointerTy())
2580 setDoesNotAlias(F, 0);
2581 setDoesNotCapture(F, 1);
2582 } else if (Name == "__strtok_r") {
2583 if (FTy->getNumParams() != 3 ||
2584 !FTy->getParamType(1)->isPointerTy())
2587 setDoesNotCapture(F, 2);
2588 } else if (Name == "_IO_getc") {
2589 if (FTy->getNumParams() != 1 ||
2590 !FTy->getParamType(0)->isPointerTy())
2593 setDoesNotCapture(F, 1);
2594 } else if (Name == "_IO_putc") {
2595 if (FTy->getNumParams() != 2 ||
2596 !FTy->getParamType(1)->isPointerTy())
2599 setDoesNotCapture(F, 2);
2603 if (Name == "\1__isoc99_scanf") {
2604 if (FTy->getNumParams() < 1 ||
2605 !FTy->getParamType(0)->isPointerTy())
2608 setDoesNotCapture(F, 1);
2609 } else if (Name == "\1stat64" ||
2610 Name == "\1lstat64" ||
2611 Name == "\1statvfs64" ||
2612 Name == "\1__isoc99_sscanf") {
2613 if (FTy->getNumParams() < 1 ||
2614 !FTy->getParamType(0)->isPointerTy() ||
2615 !FTy->getParamType(1)->isPointerTy())
2618 setDoesNotCapture(F, 1);
2619 setDoesNotCapture(F, 2);
2620 } else if (Name == "\1fopen64") {
2621 if (FTy->getNumParams() != 2 ||
2622 !FTy->getReturnType()->isPointerTy() ||
2623 !FTy->getParamType(0)->isPointerTy() ||
2624 !FTy->getParamType(1)->isPointerTy())
2627 setDoesNotAlias(F, 0);
2628 setDoesNotCapture(F, 1);
2629 setDoesNotCapture(F, 2);
2630 } else if (Name == "\1fseeko64" ||
2631 Name == "\1ftello64") {
2632 if (FTy->getNumParams() == 0 ||
2633 !FTy->getParamType(0)->isPointerTy())
2636 setDoesNotCapture(F, 1);
2637 } else if (Name == "\1tmpfile64") {
2638 if (!FTy->getReturnType()->isPointerTy())
2641 setDoesNotAlias(F, 0);
2642 } else if (Name == "\1fstat64" ||
2643 Name == "\1fstatvfs64") {
2644 if (FTy->getNumParams() != 2 ||
2645 !FTy->getParamType(1)->isPointerTy())
2648 setDoesNotCapture(F, 2);
2649 } else if (Name == "\1open64") {
2650 if (FTy->getNumParams() < 2 ||
2651 !FTy->getParamType(0)->isPointerTy())
2653 // May throw; "open" is a valid pthread cancellation point.
2654 setDoesNotCapture(F, 1);
2663 // Additional cases that we need to add to this file:
2666 // * cbrt(expN(X)) -> expN(x/3)
2667 // * cbrt(sqrt(x)) -> pow(x,1/6)
2668 // * cbrt(sqrt(x)) -> pow(x,1/9)
2671 // * cos(-x) -> cos(x)
2674 // * exp(log(x)) -> x
2677 // * log(exp(x)) -> x
2678 // * log(x**y) -> y*log(x)
2679 // * log(exp(y)) -> y*log(e)
2680 // * log(exp2(y)) -> y*log(2)
2681 // * log(exp10(y)) -> y*log(10)
2682 // * log(sqrt(x)) -> 0.5*log(x)
2683 // * log(pow(x,y)) -> y*log(x)
2685 // lround, lroundf, lroundl:
2686 // * lround(cnst) -> cnst'
2689 // * pow(exp(x),y) -> exp(x*y)
2690 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2691 // * pow(pow(x,y),z)-> pow(x,y*z)
2694 // * puts("") -> putchar("\n")
2696 // round, roundf, roundl:
2697 // * round(cnst) -> cnst'
2700 // * signbit(cnst) -> cnst'
2701 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2703 // sqrt, sqrtf, sqrtl:
2704 // * sqrt(expN(x)) -> expN(x*0.5)
2705 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2706 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2709 // * stpcpy(str, "literal") ->
2710 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2712 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2713 // (if c is a constant integer and s is a constant string)
2714 // * strrchr(s1,0) -> strchr(s1,0)
2717 // * strpbrk(s,a) -> offset_in_for(s,a)
2718 // (if s and a are both constant strings)
2719 // * strpbrk(s,"") -> 0
2720 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2723 // * strspn(s,a) -> const_int (if both args are constant)
2724 // * strspn("",a) -> 0
2725 // * strspn(s,"") -> 0
2726 // * strcspn(s,a) -> const_int (if both args are constant)
2727 // * strcspn("",a) -> 0
2728 // * strcspn(s,"") -> strlen(a)
2731 // * tan(atan(x)) -> x
2733 // trunc, truncf, truncl:
2734 // * trunc(cnst) -> cnst'