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/Transforms/Utils/BuildLibCalls.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Config/config.h"
37 STATISTIC(NumSimplified, "Number of library calls simplified");
38 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
40 //===----------------------------------------------------------------------===//
41 // Optimizer Base Class
42 //===----------------------------------------------------------------------===//
44 /// This class is the abstract base class for the set of optimizations that
45 /// corresponds to one library call.
47 class LibCallOptimization {
53 LibCallOptimization() { }
54 virtual ~LibCallOptimization() {}
56 /// CallOptimizer - This pure virtual method is implemented by base classes to
57 /// do various optimizations. If this returns null then no transformation was
58 /// performed. If it returns CI, then it transformed the call and CI is to be
59 /// deleted. If it returns something else, replace CI with the new value and
61 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
64 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
65 Caller = CI->getParent()->getParent();
67 if (CI->getCalledFunction())
68 Context = &CI->getCalledFunction()->getContext();
70 // We never change the calling convention.
71 if (CI->getCallingConv() != llvm::CallingConv::C)
74 return CallOptimizer(CI->getCalledFunction(), CI, B);
77 } // End anonymous namespace.
80 //===----------------------------------------------------------------------===//
82 //===----------------------------------------------------------------------===//
84 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
85 /// value is equal or not-equal to zero.
86 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
87 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
89 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
91 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
94 // Unknown instruction.
100 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
101 /// comparisons with With.
102 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
103 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
105 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
106 if (IC->isEquality() && IC->getOperand(1) == With)
108 // Unknown instruction.
114 //===----------------------------------------------------------------------===//
115 // String and Memory LibCall Optimizations
116 //===----------------------------------------------------------------------===//
118 //===---------------------------------------===//
119 // 'strcat' Optimizations
121 struct StrCatOpt : public LibCallOptimization {
122 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
123 // Verify the "strcat" function prototype.
124 const FunctionType *FT = Callee->getFunctionType();
125 if (FT->getNumParams() != 2 ||
126 FT->getReturnType() != B.getInt8PtrTy() ||
127 FT->getParamType(0) != FT->getReturnType() ||
128 FT->getParamType(1) != FT->getReturnType())
131 // Extract some information from the instruction
132 Value *Dst = CI->getArgOperand(0);
133 Value *Src = CI->getArgOperand(1);
135 // See if we can get the length of the input string.
136 uint64_t Len = GetStringLength(Src);
137 if (Len == 0) return 0;
138 --Len; // Unbias length.
140 // Handle the simple, do-nothing case: strcat(x, "") -> x
144 // These optimizations require TargetData.
147 EmitStrLenMemCpy(Src, Dst, Len, B);
151 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
152 // We need to find the end of the destination string. That's where the
153 // memory is to be moved to. We just generate a call to strlen.
154 Value *DstLen = EmitStrLen(Dst, B, TD);
156 // Now that we have the destination's length, we must index into the
157 // destination's pointer to get the actual memcpy destination (end of
158 // the string .. we're concatenating).
159 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
161 // We have enough information to now generate the memcpy call to do the
162 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
163 B.CreateMemCpy(CpyDst, Src,
164 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
168 //===---------------------------------------===//
169 // 'strncat' Optimizations
171 struct StrNCatOpt : public StrCatOpt {
172 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
173 // Verify the "strncat" function prototype.
174 const FunctionType *FT = Callee->getFunctionType();
175 if (FT->getNumParams() != 3 ||
176 FT->getReturnType() != B.getInt8PtrTy() ||
177 FT->getParamType(0) != FT->getReturnType() ||
178 FT->getParamType(1) != FT->getReturnType() ||
179 !FT->getParamType(2)->isIntegerTy())
182 // Extract some information from the instruction
183 Value *Dst = CI->getArgOperand(0);
184 Value *Src = CI->getArgOperand(1);
187 // We don't do anything if length is not constant
188 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
189 Len = LengthArg->getZExtValue();
193 // See if we can get the length of the input string.
194 uint64_t SrcLen = GetStringLength(Src);
195 if (SrcLen == 0) return 0;
196 --SrcLen; // Unbias length.
198 // Handle the simple, do-nothing cases:
199 // strncat(x, "", c) -> x
200 // strncat(x, c, 0) -> x
201 if (SrcLen == 0 || Len == 0) return Dst;
203 // These optimizations require TargetData.
206 // We don't optimize this case
207 if (Len < SrcLen) return 0;
209 // strncat(x, s, c) -> strcat(x, s)
210 // s is constant so the strcat can be optimized further
211 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
216 //===---------------------------------------===//
217 // 'strchr' Optimizations
219 struct StrChrOpt : public LibCallOptimization {
220 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
221 // Verify the "strchr" function prototype.
222 const FunctionType *FT = Callee->getFunctionType();
223 if (FT->getNumParams() != 2 ||
224 FT->getReturnType() != B.getInt8PtrTy() ||
225 FT->getParamType(0) != FT->getReturnType() ||
226 !FT->getParamType(1)->isIntegerTy(32))
229 Value *SrcStr = CI->getArgOperand(0);
231 // If the second operand is non-constant, see if we can compute the length
232 // of the input string and turn this into memchr.
233 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
235 // These optimizations require TargetData.
238 uint64_t Len = GetStringLength(SrcStr);
239 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
242 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
243 ConstantInt::get(TD->getIntPtrType(*Context), Len),
247 // Otherwise, the character is a constant, see if the first argument is
248 // a string literal. If so, we can constant fold.
250 if (!GetConstantStringInfo(SrcStr, Str))
253 // strchr can find the nul character.
256 // Compute the offset.
257 size_t I = Str.find(CharC->getSExtValue());
258 if (I == std::string::npos) // Didn't find the char. strchr returns null.
259 return Constant::getNullValue(CI->getType());
261 // strchr(s+n,c) -> gep(s+n+i,c)
262 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
266 //===---------------------------------------===//
267 // 'strrchr' Optimizations
269 struct StrRChrOpt : public LibCallOptimization {
270 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
271 // Verify the "strrchr" function prototype.
272 const FunctionType *FT = Callee->getFunctionType();
273 if (FT->getNumParams() != 2 ||
274 FT->getReturnType() != B.getInt8PtrTy() ||
275 FT->getParamType(0) != FT->getReturnType() ||
276 !FT->getParamType(1)->isIntegerTy(32))
279 Value *SrcStr = CI->getArgOperand(0);
280 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
282 // Cannot fold anything if we're not looking for a constant.
287 if (!GetConstantStringInfo(SrcStr, Str)) {
288 // strrchr(s, 0) -> strchr(s, 0)
289 if (TD && CharC->isZero())
290 return EmitStrChr(SrcStr, '\0', B, TD);
294 // strrchr can find the nul character.
297 // Compute the offset.
298 size_t I = Str.rfind(CharC->getSExtValue());
299 if (I == std::string::npos) // Didn't find the char. Return null.
300 return Constant::getNullValue(CI->getType());
302 // strrchr(s+n,c) -> gep(s+n+i,c)
303 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
307 //===---------------------------------------===//
308 // 'strcmp' Optimizations
310 struct StrCmpOpt : public LibCallOptimization {
311 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
312 // Verify the "strcmp" function prototype.
313 const FunctionType *FT = Callee->getFunctionType();
314 if (FT->getNumParams() != 2 ||
315 !FT->getReturnType()->isIntegerTy(32) ||
316 FT->getParamType(0) != FT->getParamType(1) ||
317 FT->getParamType(0) != B.getInt8PtrTy())
320 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
321 if (Str1P == Str2P) // strcmp(x,x) -> 0
322 return ConstantInt::get(CI->getType(), 0);
324 std::string Str1, Str2;
325 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
326 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
328 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
329 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
331 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
332 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
334 // strcmp(x, y) -> cnst (if both x and y are constant strings)
335 if (HasStr1 && HasStr2)
336 return ConstantInt::get(CI->getType(),
337 strcmp(Str1.c_str(),Str2.c_str()));
339 // strcmp(P, "x") -> memcmp(P, "x", 2)
340 uint64_t Len1 = GetStringLength(Str1P);
341 uint64_t Len2 = GetStringLength(Str2P);
343 // These optimizations require TargetData.
346 return EmitMemCmp(Str1P, Str2P,
347 ConstantInt::get(TD->getIntPtrType(*Context),
348 std::min(Len1, Len2)), B, TD);
355 //===---------------------------------------===//
356 // 'strncmp' Optimizations
358 struct StrNCmpOpt : public LibCallOptimization {
359 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
360 // Verify the "strncmp" function prototype.
361 const FunctionType *FT = Callee->getFunctionType();
362 if (FT->getNumParams() != 3 ||
363 !FT->getReturnType()->isIntegerTy(32) ||
364 FT->getParamType(0) != FT->getParamType(1) ||
365 FT->getParamType(0) != B.getInt8PtrTy() ||
366 !FT->getParamType(2)->isIntegerTy())
369 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
370 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
371 return ConstantInt::get(CI->getType(), 0);
373 // Get the length argument if it is constant.
375 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
376 Length = LengthArg->getZExtValue();
380 if (Length == 0) // strncmp(x,y,0) -> 0
381 return ConstantInt::get(CI->getType(), 0);
383 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
384 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
386 std::string Str1, Str2;
387 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
388 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
390 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
391 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
393 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
394 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
396 // strncmp(x, y) -> cnst (if both x and y are constant strings)
397 if (HasStr1 && HasStr2)
398 return ConstantInt::get(CI->getType(),
399 strncmp(Str1.c_str(), Str2.c_str(), Length));
405 //===---------------------------------------===//
406 // 'strcpy' Optimizations
408 struct StrCpyOpt : public LibCallOptimization {
409 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
411 StrCpyOpt(bool c) : OptChkCall(c) {}
413 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
414 // Verify the "strcpy" function prototype.
415 unsigned NumParams = OptChkCall ? 3 : 2;
416 const FunctionType *FT = Callee->getFunctionType();
417 if (FT->getNumParams() != NumParams ||
418 FT->getReturnType() != FT->getParamType(0) ||
419 FT->getParamType(0) != FT->getParamType(1) ||
420 FT->getParamType(0) != B.getInt8PtrTy())
423 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
424 if (Dst == Src) // strcpy(x,x) -> x
427 // These optimizations require TargetData.
430 // See if we can get the length of the input string.
431 uint64_t Len = GetStringLength(Src);
432 if (Len == 0) return 0;
434 // We have enough information to now generate the memcpy call to do the
435 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
437 EmitMemCpyChk(Dst, Src,
438 ConstantInt::get(TD->getIntPtrType(*Context), Len),
439 CI->getArgOperand(2), B, TD);
441 B.CreateMemCpy(Dst, Src,
442 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
447 //===---------------------------------------===//
448 // 'strncpy' Optimizations
450 struct StrNCpyOpt : public LibCallOptimization {
451 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
452 const FunctionType *FT = Callee->getFunctionType();
453 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
454 FT->getParamType(0) != FT->getParamType(1) ||
455 FT->getParamType(0) != B.getInt8PtrTy() ||
456 !FT->getParamType(2)->isIntegerTy())
459 Value *Dst = CI->getArgOperand(0);
460 Value *Src = CI->getArgOperand(1);
461 Value *LenOp = CI->getArgOperand(2);
463 // See if we can get the length of the input string.
464 uint64_t SrcLen = GetStringLength(Src);
465 if (SrcLen == 0) return 0;
469 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
470 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
475 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
476 Len = LengthArg->getZExtValue();
480 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
482 // These optimizations require TargetData.
485 // Let strncpy handle the zero padding
486 if (Len > SrcLen+1) return 0;
488 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
489 B.CreateMemCpy(Dst, Src,
490 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
496 //===---------------------------------------===//
497 // 'strlen' Optimizations
499 struct StrLenOpt : public LibCallOptimization {
500 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
501 const FunctionType *FT = Callee->getFunctionType();
502 if (FT->getNumParams() != 1 ||
503 FT->getParamType(0) != B.getInt8PtrTy() ||
504 !FT->getReturnType()->isIntegerTy())
507 Value *Src = CI->getArgOperand(0);
509 // Constant folding: strlen("xyz") -> 3
510 if (uint64_t Len = GetStringLength(Src))
511 return ConstantInt::get(CI->getType(), Len-1);
513 // strlen(x) != 0 --> *x != 0
514 // strlen(x) == 0 --> *x == 0
515 if (IsOnlyUsedInZeroEqualityComparison(CI))
516 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
522 //===---------------------------------------===//
523 // 'strpbrk' Optimizations
525 struct StrPBrkOpt : public LibCallOptimization {
526 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
527 const FunctionType *FT = Callee->getFunctionType();
528 if (FT->getNumParams() != 2 ||
529 FT->getParamType(0) != B.getInt8PtrTy() ||
530 FT->getParamType(1) != FT->getParamType(0) ||
531 FT->getReturnType() != FT->getParamType(0))
535 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
536 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
538 // strpbrk(s, "") -> NULL
539 // strpbrk("", s) -> NULL
540 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
541 return Constant::getNullValue(CI->getType());
544 if (HasS1 && HasS2) {
545 size_t I = S1.find_first_of(S2);
546 if (I == std::string::npos) // No match.
547 return Constant::getNullValue(CI->getType());
549 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
552 // strpbrk(s, "a") -> strchr(s, 'a')
553 if (TD && HasS2 && S2.size() == 1)
554 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
560 //===---------------------------------------===//
561 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
563 struct StrToOpt : public LibCallOptimization {
564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
565 const FunctionType *FT = Callee->getFunctionType();
566 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
567 !FT->getParamType(0)->isPointerTy() ||
568 !FT->getParamType(1)->isPointerTy())
571 Value *EndPtr = CI->getArgOperand(1);
572 if (isa<ConstantPointerNull>(EndPtr)) {
573 // With a null EndPtr, this function won't capture the main argument.
574 // It would be readonly too, except that it still may write to errno.
575 CI->addAttribute(1, Attribute::NoCapture);
582 //===---------------------------------------===//
583 // 'strspn' Optimizations
585 struct StrSpnOpt : public LibCallOptimization {
586 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
587 const FunctionType *FT = Callee->getFunctionType();
588 if (FT->getNumParams() != 2 ||
589 FT->getParamType(0) != B.getInt8PtrTy() ||
590 FT->getParamType(1) != FT->getParamType(0) ||
591 !FT->getReturnType()->isIntegerTy())
595 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
596 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
598 // strspn(s, "") -> 0
599 // strspn("", s) -> 0
600 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
601 return Constant::getNullValue(CI->getType());
605 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
611 //===---------------------------------------===//
612 // 'strcspn' Optimizations
614 struct StrCSpnOpt : public LibCallOptimization {
615 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
616 const FunctionType *FT = Callee->getFunctionType();
617 if (FT->getNumParams() != 2 ||
618 FT->getParamType(0) != B.getInt8PtrTy() ||
619 FT->getParamType(1) != FT->getParamType(0) ||
620 !FT->getReturnType()->isIntegerTy())
624 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
625 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
627 // strcspn("", s) -> 0
628 if (HasS1 && S1.empty())
629 return Constant::getNullValue(CI->getType());
633 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
635 // strcspn(s, "") -> strlen(s)
636 if (TD && HasS2 && S2.empty())
637 return EmitStrLen(CI->getArgOperand(0), B, TD);
643 //===---------------------------------------===//
644 // 'strstr' Optimizations
646 struct StrStrOpt : public LibCallOptimization {
647 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
648 const FunctionType *FT = Callee->getFunctionType();
649 if (FT->getNumParams() != 2 ||
650 !FT->getParamType(0)->isPointerTy() ||
651 !FT->getParamType(1)->isPointerTy() ||
652 !FT->getReturnType()->isPointerTy())
655 // fold strstr(x, x) -> x.
656 if (CI->getArgOperand(0) == CI->getArgOperand(1))
657 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
659 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
660 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
661 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
662 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
664 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
666 ICmpInst *Old = cast<ICmpInst>(*UI++);
667 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
668 ConstantInt::getNullValue(StrNCmp->getType()),
670 Old->replaceAllUsesWith(Cmp);
671 Old->eraseFromParent();
676 // See if either input string is a constant string.
677 std::string SearchStr, ToFindStr;
678 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
679 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
681 // fold strstr(x, "") -> x.
682 if (HasStr2 && ToFindStr.empty())
683 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
685 // If both strings are known, constant fold it.
686 if (HasStr1 && HasStr2) {
687 std::string::size_type Offset = SearchStr.find(ToFindStr);
689 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
690 return Constant::getNullValue(CI->getType());
692 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
693 Value *Result = CastToCStr(CI->getArgOperand(0), B);
694 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
695 return B.CreateBitCast(Result, CI->getType());
698 // fold strstr(x, "y") -> strchr(x, 'y').
699 if (HasStr2 && ToFindStr.size() == 1)
700 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
701 ToFindStr[0], B, TD), CI->getType());
707 //===---------------------------------------===//
708 // 'memcmp' Optimizations
710 struct MemCmpOpt : public LibCallOptimization {
711 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
712 const FunctionType *FT = Callee->getFunctionType();
713 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
714 !FT->getParamType(1)->isPointerTy() ||
715 !FT->getReturnType()->isIntegerTy(32))
718 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
720 if (LHS == RHS) // memcmp(s,s,x) -> 0
721 return Constant::getNullValue(CI->getType());
723 // Make sure we have a constant length.
724 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
726 uint64_t Len = LenC->getZExtValue();
728 if (Len == 0) // memcmp(s1,s2,0) -> 0
729 return Constant::getNullValue(CI->getType());
731 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
733 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
734 CI->getType(), "lhsv");
735 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
736 CI->getType(), "rhsv");
737 return B.CreateSub(LHSV, RHSV, "chardiff");
740 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
741 std::string LHSStr, RHSStr;
742 if (GetConstantStringInfo(LHS, LHSStr) &&
743 GetConstantStringInfo(RHS, RHSStr)) {
744 // Make sure we're not reading out-of-bounds memory.
745 if (Len > LHSStr.length() || Len > RHSStr.length())
747 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
748 return ConstantInt::get(CI->getType(), Ret);
755 //===---------------------------------------===//
756 // 'memcpy' Optimizations
758 struct MemCpyOpt : public LibCallOptimization {
759 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
760 // These optimizations require TargetData.
763 const FunctionType *FT = Callee->getFunctionType();
764 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
765 !FT->getParamType(0)->isPointerTy() ||
766 !FT->getParamType(1)->isPointerTy() ||
767 FT->getParamType(2) != TD->getIntPtrType(*Context))
770 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
771 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
772 CI->getArgOperand(2), 1);
773 return CI->getArgOperand(0);
777 //===---------------------------------------===//
778 // 'memmove' Optimizations
780 struct MemMoveOpt : public LibCallOptimization {
781 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
782 // These optimizations require TargetData.
785 const FunctionType *FT = Callee->getFunctionType();
786 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
787 !FT->getParamType(0)->isPointerTy() ||
788 !FT->getParamType(1)->isPointerTy() ||
789 FT->getParamType(2) != TD->getIntPtrType(*Context))
792 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
793 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
794 CI->getArgOperand(2), 1);
795 return CI->getArgOperand(0);
799 //===---------------------------------------===//
800 // 'memset' Optimizations
802 struct MemSetOpt : public LibCallOptimization {
803 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
804 // These optimizations require TargetData.
807 const FunctionType *FT = Callee->getFunctionType();
808 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
809 !FT->getParamType(0)->isPointerTy() ||
810 !FT->getParamType(1)->isIntegerTy() ||
811 FT->getParamType(2) != TD->getIntPtrType(*Context))
814 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
815 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
816 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
817 return CI->getArgOperand(0);
821 //===----------------------------------------------------------------------===//
822 // Math Library Optimizations
823 //===----------------------------------------------------------------------===//
825 //===---------------------------------------===//
826 // 'pow*' Optimizations
828 struct PowOpt : public LibCallOptimization {
829 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
830 const FunctionType *FT = Callee->getFunctionType();
831 // Just make sure this has 2 arguments of the same FP type, which match the
833 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
834 FT->getParamType(0) != FT->getParamType(1) ||
835 !FT->getParamType(0)->isFloatingPointTy())
838 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
839 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
840 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
842 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
843 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
846 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
847 if (Op2C == 0) return 0;
849 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
850 return ConstantFP::get(CI->getType(), 1.0);
852 if (Op2C->isExactlyValue(0.5)) {
853 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
854 // This is faster than calling pow, and still handles negative zero
855 // and negative infinite correctly.
856 // TODO: In fast-math mode, this could be just sqrt(x).
857 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
858 Value *Inf = ConstantFP::getInfinity(CI->getType());
859 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
860 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
861 Callee->getAttributes());
862 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
863 Callee->getAttributes());
864 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
865 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
869 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
871 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
872 return B.CreateFMul(Op1, Op1, "pow2");
873 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
874 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
880 //===---------------------------------------===//
881 // 'exp2' Optimizations
883 struct Exp2Opt : public LibCallOptimization {
884 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
885 const FunctionType *FT = Callee->getFunctionType();
886 // Just make sure this has 1 argument of FP type, which matches the
888 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
889 !FT->getParamType(0)->isFloatingPointTy())
892 Value *Op = CI->getArgOperand(0);
893 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
894 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
896 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
897 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
898 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty(), "tmp");
899 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
900 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
901 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty(), "tmp");
906 if (Op->getType()->isFloatTy())
908 else if (Op->getType()->isDoubleTy())
913 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
914 if (!Op->getType()->isFloatTy())
915 One = ConstantExpr::getFPExtend(One, Op->getType());
917 Module *M = Caller->getParent();
918 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
920 B.getInt32Ty(), NULL);
921 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
922 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
923 CI->setCallingConv(F->getCallingConv());
931 //===---------------------------------------===//
932 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
934 struct UnaryDoubleFPOpt : public LibCallOptimization {
935 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
936 const FunctionType *FT = Callee->getFunctionType();
937 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
938 !FT->getParamType(0)->isDoubleTy())
941 // If this is something like 'floor((double)floatval)', convert to floorf.
942 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
943 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
946 // floor((double)floatval) -> (double)floorf(floatval)
947 Value *V = Cast->getOperand(0);
948 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
949 Callee->getAttributes());
950 return B.CreateFPExt(V, B.getDoubleTy());
954 //===----------------------------------------------------------------------===//
955 // Integer Optimizations
956 //===----------------------------------------------------------------------===//
958 //===---------------------------------------===//
959 // 'ffs*' Optimizations
961 struct FFSOpt : public LibCallOptimization {
962 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
963 const FunctionType *FT = Callee->getFunctionType();
964 // Just make sure this has 2 arguments of the same FP type, which match the
966 if (FT->getNumParams() != 1 ||
967 !FT->getReturnType()->isIntegerTy(32) ||
968 !FT->getParamType(0)->isIntegerTy())
971 Value *Op = CI->getArgOperand(0);
974 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
975 if (CI->getValue() == 0) // ffs(0) -> 0.
976 return Constant::getNullValue(CI->getType());
977 // ffs(c) -> cttz(c)+1
978 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
981 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
982 const Type *ArgType = Op->getType();
983 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
984 Intrinsic::cttz, &ArgType, 1);
985 Value *V = B.CreateCall(F, Op, "cttz");
986 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
987 V = B.CreateIntCast(V, B.getInt32Ty(), false, "tmp");
989 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
990 return B.CreateSelect(Cond, V, B.getInt32(0));
994 //===---------------------------------------===//
995 // 'isdigit' Optimizations
997 struct IsDigitOpt : public LibCallOptimization {
998 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
999 const FunctionType *FT = Callee->getFunctionType();
1000 // We require integer(i32)
1001 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1002 !FT->getParamType(0)->isIntegerTy(32))
1005 // isdigit(c) -> (c-'0') <u 10
1006 Value *Op = CI->getArgOperand(0);
1007 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1008 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1009 return B.CreateZExt(Op, CI->getType());
1013 //===---------------------------------------===//
1014 // 'isascii' Optimizations
1016 struct IsAsciiOpt : public LibCallOptimization {
1017 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1018 const FunctionType *FT = Callee->getFunctionType();
1019 // We require integer(i32)
1020 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1021 !FT->getParamType(0)->isIntegerTy(32))
1024 // isascii(c) -> c <u 128
1025 Value *Op = CI->getArgOperand(0);
1026 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1027 return B.CreateZExt(Op, CI->getType());
1031 //===---------------------------------------===//
1032 // 'abs', 'labs', 'llabs' Optimizations
1034 struct AbsOpt : public LibCallOptimization {
1035 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1036 const FunctionType *FT = Callee->getFunctionType();
1037 // We require integer(integer) where the types agree.
1038 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1039 FT->getParamType(0) != FT->getReturnType())
1042 // abs(x) -> x >s -1 ? x : -x
1043 Value *Op = CI->getArgOperand(0);
1044 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1046 Value *Neg = B.CreateNeg(Op, "neg");
1047 return B.CreateSelect(Pos, Op, Neg);
1052 //===---------------------------------------===//
1053 // 'toascii' Optimizations
1055 struct ToAsciiOpt : public LibCallOptimization {
1056 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1057 const FunctionType *FT = Callee->getFunctionType();
1058 // We require i32(i32)
1059 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1060 !FT->getParamType(0)->isIntegerTy(32))
1063 // isascii(c) -> c & 0x7f
1064 return B.CreateAnd(CI->getArgOperand(0),
1065 ConstantInt::get(CI->getType(),0x7F));
1069 //===----------------------------------------------------------------------===//
1070 // Formatting and IO Optimizations
1071 //===----------------------------------------------------------------------===//
1073 //===---------------------------------------===//
1074 // 'printf' Optimizations
1076 struct PrintFOpt : public LibCallOptimization {
1077 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1078 // Require one fixed pointer argument and an integer/void result.
1079 const FunctionType *FT = Callee->getFunctionType();
1080 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1081 !(FT->getReturnType()->isIntegerTy() ||
1082 FT->getReturnType()->isVoidTy()))
1085 // Check for a fixed format string.
1086 std::string FormatStr;
1087 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
1090 // Empty format string -> noop.
1091 if (FormatStr.empty()) // Tolerate printf's declared void.
1092 return CI->use_empty() ? (Value*)CI :
1093 ConstantInt::get(CI->getType(), 0);
1095 // Do not do any of the following transformations if the printf return value
1096 // is used, in general the printf return value is not compatible with either
1097 // putchar() or puts().
1098 if (!CI->use_empty())
1101 // printf("x") -> putchar('x'), even for '%'.
1102 if (FormatStr.size() == 1) {
1103 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
1104 if (CI->use_empty()) return CI;
1105 return B.CreateIntCast(Res, CI->getType(), true);
1108 // printf("foo\n") --> puts("foo")
1109 if (FormatStr[FormatStr.size()-1] == '\n' &&
1110 FormatStr.find('%') == std::string::npos) { // no format characters.
1111 // Create a string literal with no \n on it. We expect the constant merge
1112 // pass to be run after this pass, to merge duplicate strings.
1113 FormatStr.erase(FormatStr.end()-1);
1114 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1115 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1116 GlobalVariable::InternalLinkage, C, "str");
1118 return CI->use_empty() ? (Value*)CI :
1119 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1122 // Optimize specific format strings.
1123 // printf("%c", chr) --> putchar(chr)
1124 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1125 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1126 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
1128 if (CI->use_empty()) return CI;
1129 return B.CreateIntCast(Res, CI->getType(), true);
1132 // printf("%s\n", str) --> puts(str)
1133 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1134 CI->getArgOperand(1)->getType()->isPointerTy()) {
1135 EmitPutS(CI->getArgOperand(1), B, TD);
1142 //===---------------------------------------===//
1143 // 'sprintf' Optimizations
1145 struct SPrintFOpt : public LibCallOptimization {
1146 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1147 // Require two fixed pointer arguments and an integer result.
1148 const FunctionType *FT = Callee->getFunctionType();
1149 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1150 !FT->getParamType(1)->isPointerTy() ||
1151 !FT->getReturnType()->isIntegerTy())
1154 // Check for a fixed format string.
1155 std::string FormatStr;
1156 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1159 // If we just have a format string (nothing else crazy) transform it.
1160 if (CI->getNumArgOperands() == 2) {
1161 // Make sure there's no % in the constant array. We could try to handle
1162 // %% -> % in the future if we cared.
1163 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1164 if (FormatStr[i] == '%')
1165 return 0; // we found a format specifier, bail out.
1167 // These optimizations require TargetData.
1170 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1171 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1172 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1173 FormatStr.size() + 1), 1); // nul byte.
1174 return ConstantInt::get(CI->getType(), FormatStr.size());
1177 // The remaining optimizations require the format string to be "%s" or "%c"
1178 // and have an extra operand.
1179 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1180 CI->getNumArgOperands() < 3)
1183 // Decode the second character of the format string.
1184 if (FormatStr[1] == 'c') {
1185 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1186 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1187 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1188 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1189 B.CreateStore(V, Ptr);
1190 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1191 B.CreateStore(B.getInt8(0), Ptr);
1193 return ConstantInt::get(CI->getType(), 1);
1196 if (FormatStr[1] == 's') {
1197 // These optimizations require TargetData.
1200 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1201 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1203 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
1204 Value *IncLen = B.CreateAdd(Len,
1205 ConstantInt::get(Len->getType(), 1),
1207 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1209 // The sprintf result is the unincremented number of bytes in the string.
1210 return B.CreateIntCast(Len, CI->getType(), false);
1216 //===---------------------------------------===//
1217 // 'fwrite' Optimizations
1219 struct FWriteOpt : public LibCallOptimization {
1220 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1221 // Require a pointer, an integer, an integer, a pointer, returning integer.
1222 const FunctionType *FT = Callee->getFunctionType();
1223 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1224 !FT->getParamType(1)->isIntegerTy() ||
1225 !FT->getParamType(2)->isIntegerTy() ||
1226 !FT->getParamType(3)->isPointerTy() ||
1227 !FT->getReturnType()->isIntegerTy())
1230 // Get the element size and count.
1231 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1232 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1233 if (!SizeC || !CountC) return 0;
1234 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1236 // If this is writing zero records, remove the call (it's a noop).
1238 return ConstantInt::get(CI->getType(), 0);
1240 // If this is writing one byte, turn it into fputc.
1241 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1242 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1243 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
1244 return ConstantInt::get(CI->getType(), 1);
1251 //===---------------------------------------===//
1252 // 'fputs' Optimizations
1254 struct FPutsOpt : public LibCallOptimization {
1255 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1256 // These optimizations require TargetData.
1259 // Require two pointers. Also, we can't optimize if return value is used.
1260 const FunctionType *FT = Callee->getFunctionType();
1261 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1262 !FT->getParamType(1)->isPointerTy() ||
1266 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1267 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1269 EmitFWrite(CI->getArgOperand(0),
1270 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1271 CI->getArgOperand(1), B, TD);
1272 return CI; // Known to have no uses (see above).
1276 //===---------------------------------------===//
1277 // 'fprintf' Optimizations
1279 struct FPrintFOpt : public LibCallOptimization {
1280 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1281 // Require two fixed paramters as pointers and integer result.
1282 const FunctionType *FT = Callee->getFunctionType();
1283 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1284 !FT->getParamType(1)->isPointerTy() ||
1285 !FT->getReturnType()->isIntegerTy())
1288 // All the optimizations depend on the format string.
1289 std::string FormatStr;
1290 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1293 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1294 if (CI->getNumArgOperands() == 2) {
1295 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1296 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1297 return 0; // We found a format specifier.
1299 // These optimizations require TargetData.
1302 EmitFWrite(CI->getArgOperand(1),
1303 ConstantInt::get(TD->getIntPtrType(*Context),
1305 CI->getArgOperand(0), B, TD);
1306 return ConstantInt::get(CI->getType(), FormatStr.size());
1309 // The remaining optimizations require the format string to be "%s" or "%c"
1310 // and have an extra operand.
1311 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1312 CI->getNumArgOperands() < 3)
1315 // Decode the second character of the format string.
1316 if (FormatStr[1] == 'c') {
1317 // fprintf(F, "%c", chr) --> fputc(chr, F)
1318 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1319 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1320 return ConstantInt::get(CI->getType(), 1);
1323 if (FormatStr[1] == 's') {
1324 // fprintf(F, "%s", str) --> fputs(str, F)
1325 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1327 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1334 //===---------------------------------------===//
1335 // 'puts' Optimizations
1337 struct PutsOpt : public LibCallOptimization {
1338 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1339 // Require one fixed pointer argument and an integer/void result.
1340 const FunctionType *FT = Callee->getFunctionType();
1341 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1342 !(FT->getReturnType()->isIntegerTy() ||
1343 FT->getReturnType()->isVoidTy()))
1346 // Check for a constant string.
1348 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1351 if (Str.empty() && CI->use_empty()) {
1352 // puts("") -> putchar('\n')
1353 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1354 if (CI->use_empty()) return CI;
1355 return B.CreateIntCast(Res, CI->getType(), true);
1362 } // end anonymous namespace.
1364 //===----------------------------------------------------------------------===//
1365 // SimplifyLibCalls Pass Implementation
1366 //===----------------------------------------------------------------------===//
1369 /// This pass optimizes well known library functions from libc and libm.
1371 class SimplifyLibCalls : public FunctionPass {
1372 StringMap<LibCallOptimization*> Optimizations;
1373 // String and Memory LibCall Optimizations
1374 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1375 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1376 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1377 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1378 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1379 // Math Library Optimizations
1380 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1381 // Integer Optimizations
1382 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1384 // Formatting and IO Optimizations
1385 SPrintFOpt SPrintF; PrintFOpt PrintF;
1386 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1389 bool Modified; // This is only used by doInitialization.
1391 static char ID; // Pass identification
1392 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1393 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1395 void InitOptimizations();
1396 bool runOnFunction(Function &F);
1398 void setDoesNotAccessMemory(Function &F);
1399 void setOnlyReadsMemory(Function &F);
1400 void setDoesNotThrow(Function &F);
1401 void setDoesNotCapture(Function &F, unsigned n);
1402 void setDoesNotAlias(Function &F, unsigned n);
1403 bool doInitialization(Module &M);
1405 void inferPrototypeAttributes(Function &F);
1406 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1409 char SimplifyLibCalls::ID = 0;
1410 } // end anonymous namespace.
1412 INITIALIZE_PASS(SimplifyLibCalls, "simplify-libcalls",
1413 "Simplify well-known library calls", false, false)
1415 // Public interface to the Simplify LibCalls pass.
1416 FunctionPass *llvm::createSimplifyLibCallsPass() {
1417 return new SimplifyLibCalls();
1420 /// Optimizations - Populate the Optimizations map with all the optimizations
1422 void SimplifyLibCalls::InitOptimizations() {
1423 // String and Memory LibCall Optimizations
1424 Optimizations["strcat"] = &StrCat;
1425 Optimizations["strncat"] = &StrNCat;
1426 Optimizations["strchr"] = &StrChr;
1427 Optimizations["strrchr"] = &StrRChr;
1428 Optimizations["strcmp"] = &StrCmp;
1429 Optimizations["strncmp"] = &StrNCmp;
1430 Optimizations["strcpy"] = &StrCpy;
1431 Optimizations["strncpy"] = &StrNCpy;
1432 Optimizations["strlen"] = &StrLen;
1433 Optimizations["strpbrk"] = &StrPBrk;
1434 Optimizations["strtol"] = &StrTo;
1435 Optimizations["strtod"] = &StrTo;
1436 Optimizations["strtof"] = &StrTo;
1437 Optimizations["strtoul"] = &StrTo;
1438 Optimizations["strtoll"] = &StrTo;
1439 Optimizations["strtold"] = &StrTo;
1440 Optimizations["strtoull"] = &StrTo;
1441 Optimizations["strspn"] = &StrSpn;
1442 Optimizations["strcspn"] = &StrCSpn;
1443 Optimizations["strstr"] = &StrStr;
1444 Optimizations["memcmp"] = &MemCmp;
1445 Optimizations["memcpy"] = &MemCpy;
1446 Optimizations["memmove"] = &MemMove;
1447 Optimizations["memset"] = &MemSet;
1449 // _chk variants of String and Memory LibCall Optimizations.
1450 Optimizations["__strcpy_chk"] = &StrCpyChk;
1452 // Math Library Optimizations
1453 Optimizations["powf"] = &Pow;
1454 Optimizations["pow"] = &Pow;
1455 Optimizations["powl"] = &Pow;
1456 Optimizations["llvm.pow.f32"] = &Pow;
1457 Optimizations["llvm.pow.f64"] = &Pow;
1458 Optimizations["llvm.pow.f80"] = &Pow;
1459 Optimizations["llvm.pow.f128"] = &Pow;
1460 Optimizations["llvm.pow.ppcf128"] = &Pow;
1461 Optimizations["exp2l"] = &Exp2;
1462 Optimizations["exp2"] = &Exp2;
1463 Optimizations["exp2f"] = &Exp2;
1464 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1465 Optimizations["llvm.exp2.f128"] = &Exp2;
1466 Optimizations["llvm.exp2.f80"] = &Exp2;
1467 Optimizations["llvm.exp2.f64"] = &Exp2;
1468 Optimizations["llvm.exp2.f32"] = &Exp2;
1471 Optimizations["floor"] = &UnaryDoubleFP;
1474 Optimizations["ceil"] = &UnaryDoubleFP;
1477 Optimizations["round"] = &UnaryDoubleFP;
1480 Optimizations["rint"] = &UnaryDoubleFP;
1482 #ifdef HAVE_NEARBYINTF
1483 Optimizations["nearbyint"] = &UnaryDoubleFP;
1486 // Integer Optimizations
1487 Optimizations["ffs"] = &FFS;
1488 Optimizations["ffsl"] = &FFS;
1489 Optimizations["ffsll"] = &FFS;
1490 Optimizations["abs"] = &Abs;
1491 Optimizations["labs"] = &Abs;
1492 Optimizations["llabs"] = &Abs;
1493 Optimizations["isdigit"] = &IsDigit;
1494 Optimizations["isascii"] = &IsAscii;
1495 Optimizations["toascii"] = &ToAscii;
1497 // Formatting and IO Optimizations
1498 Optimizations["sprintf"] = &SPrintF;
1499 Optimizations["printf"] = &PrintF;
1500 Optimizations["fwrite"] = &FWrite;
1501 Optimizations["fputs"] = &FPuts;
1502 Optimizations["fprintf"] = &FPrintF;
1503 Optimizations["puts"] = &Puts;
1507 /// runOnFunction - Top level algorithm.
1509 bool SimplifyLibCalls::runOnFunction(Function &F) {
1510 if (Optimizations.empty())
1511 InitOptimizations();
1513 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1515 IRBuilder<> Builder(F.getContext());
1517 bool Changed = false;
1518 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1519 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1520 // Ignore non-calls.
1521 CallInst *CI = dyn_cast<CallInst>(I++);
1524 // Ignore indirect calls and calls to non-external functions.
1525 Function *Callee = CI->getCalledFunction();
1526 if (Callee == 0 || !Callee->isDeclaration() ||
1527 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1530 // Ignore unknown calls.
1531 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1534 // Set the builder to the instruction after the call.
1535 Builder.SetInsertPoint(BB, I);
1537 // Try to optimize this call.
1538 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1539 if (Result == 0) continue;
1541 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1542 dbgs() << " into: " << *Result << "\n");
1544 // Something changed!
1548 // Inspect the instruction after the call (which was potentially just
1552 if (CI != Result && !CI->use_empty()) {
1553 CI->replaceAllUsesWith(Result);
1554 if (!Result->hasName())
1555 Result->takeName(CI);
1557 CI->eraseFromParent();
1563 // Utility methods for doInitialization.
1565 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1566 if (!F.doesNotAccessMemory()) {
1567 F.setDoesNotAccessMemory();
1572 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1573 if (!F.onlyReadsMemory()) {
1574 F.setOnlyReadsMemory();
1579 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1580 if (!F.doesNotThrow()) {
1581 F.setDoesNotThrow();
1586 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1587 if (!F.doesNotCapture(n)) {
1588 F.setDoesNotCapture(n);
1593 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1594 if (!F.doesNotAlias(n)) {
1595 F.setDoesNotAlias(n);
1602 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1603 const FunctionType *FTy = F.getFunctionType();
1605 StringRef Name = F.getName();
1608 if (Name == "strlen") {
1609 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1611 setOnlyReadsMemory(F);
1613 setDoesNotCapture(F, 1);
1614 } else if (Name == "strchr" ||
1615 Name == "strrchr") {
1616 if (FTy->getNumParams() != 2 ||
1617 !FTy->getParamType(0)->isPointerTy() ||
1618 !FTy->getParamType(1)->isIntegerTy())
1620 setOnlyReadsMemory(F);
1622 } else if (Name == "strcpy" ||
1628 Name == "strtoul" ||
1629 Name == "strtoll" ||
1630 Name == "strtold" ||
1631 Name == "strncat" ||
1632 Name == "strncpy" ||
1633 Name == "strtoull") {
1634 if (FTy->getNumParams() < 2 ||
1635 !FTy->getParamType(1)->isPointerTy())
1638 setDoesNotCapture(F, 2);
1639 } else if (Name == "strxfrm") {
1640 if (FTy->getNumParams() != 3 ||
1641 !FTy->getParamType(0)->isPointerTy() ||
1642 !FTy->getParamType(1)->isPointerTy())
1645 setDoesNotCapture(F, 1);
1646 setDoesNotCapture(F, 2);
1647 } else if (Name == "strcmp" ||
1649 Name == "strncmp" ||
1650 Name == "strcspn" ||
1651 Name == "strcoll" ||
1652 Name == "strcasecmp" ||
1653 Name == "strncasecmp") {
1654 if (FTy->getNumParams() < 2 ||
1655 !FTy->getParamType(0)->isPointerTy() ||
1656 !FTy->getParamType(1)->isPointerTy())
1658 setOnlyReadsMemory(F);
1660 setDoesNotCapture(F, 1);
1661 setDoesNotCapture(F, 2);
1662 } else if (Name == "strstr" ||
1663 Name == "strpbrk") {
1664 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1666 setOnlyReadsMemory(F);
1668 setDoesNotCapture(F, 2);
1669 } else if (Name == "strtok" ||
1670 Name == "strtok_r") {
1671 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1674 setDoesNotCapture(F, 2);
1675 } else if (Name == "scanf" ||
1677 Name == "setvbuf") {
1678 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1681 setDoesNotCapture(F, 1);
1682 } else if (Name == "strdup" ||
1683 Name == "strndup") {
1684 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1685 !FTy->getParamType(0)->isPointerTy())
1688 setDoesNotAlias(F, 0);
1689 setDoesNotCapture(F, 1);
1690 } else if (Name == "stat" ||
1692 Name == "sprintf" ||
1693 Name == "statvfs") {
1694 if (FTy->getNumParams() < 2 ||
1695 !FTy->getParamType(0)->isPointerTy() ||
1696 !FTy->getParamType(1)->isPointerTy())
1699 setDoesNotCapture(F, 1);
1700 setDoesNotCapture(F, 2);
1701 } else if (Name == "snprintf") {
1702 if (FTy->getNumParams() != 3 ||
1703 !FTy->getParamType(0)->isPointerTy() ||
1704 !FTy->getParamType(2)->isPointerTy())
1707 setDoesNotCapture(F, 1);
1708 setDoesNotCapture(F, 3);
1709 } else if (Name == "setitimer") {
1710 if (FTy->getNumParams() != 3 ||
1711 !FTy->getParamType(1)->isPointerTy() ||
1712 !FTy->getParamType(2)->isPointerTy())
1715 setDoesNotCapture(F, 2);
1716 setDoesNotCapture(F, 3);
1717 } else if (Name == "system") {
1718 if (FTy->getNumParams() != 1 ||
1719 !FTy->getParamType(0)->isPointerTy())
1721 // May throw; "system" is a valid pthread cancellation point.
1722 setDoesNotCapture(F, 1);
1726 if (Name == "malloc") {
1727 if (FTy->getNumParams() != 1 ||
1728 !FTy->getReturnType()->isPointerTy())
1731 setDoesNotAlias(F, 0);
1732 } else if (Name == "memcmp") {
1733 if (FTy->getNumParams() != 3 ||
1734 !FTy->getParamType(0)->isPointerTy() ||
1735 !FTy->getParamType(1)->isPointerTy())
1737 setOnlyReadsMemory(F);
1739 setDoesNotCapture(F, 1);
1740 setDoesNotCapture(F, 2);
1741 } else if (Name == "memchr" ||
1742 Name == "memrchr") {
1743 if (FTy->getNumParams() != 3)
1745 setOnlyReadsMemory(F);
1747 } else if (Name == "modf" ||
1751 Name == "memccpy" ||
1752 Name == "memmove") {
1753 if (FTy->getNumParams() < 2 ||
1754 !FTy->getParamType(1)->isPointerTy())
1757 setDoesNotCapture(F, 2);
1758 } else if (Name == "memalign") {
1759 if (!FTy->getReturnType()->isPointerTy())
1761 setDoesNotAlias(F, 0);
1762 } else if (Name == "mkdir" ||
1764 if (FTy->getNumParams() == 0 ||
1765 !FTy->getParamType(0)->isPointerTy())
1768 setDoesNotCapture(F, 1);
1772 if (Name == "realloc") {
1773 if (FTy->getNumParams() != 2 ||
1774 !FTy->getParamType(0)->isPointerTy() ||
1775 !FTy->getReturnType()->isPointerTy())
1778 setDoesNotAlias(F, 0);
1779 setDoesNotCapture(F, 1);
1780 } else if (Name == "read") {
1781 if (FTy->getNumParams() != 3 ||
1782 !FTy->getParamType(1)->isPointerTy())
1784 // May throw; "read" is a valid pthread cancellation point.
1785 setDoesNotCapture(F, 2);
1786 } else if (Name == "rmdir" ||
1789 Name == "realpath") {
1790 if (FTy->getNumParams() < 1 ||
1791 !FTy->getParamType(0)->isPointerTy())
1794 setDoesNotCapture(F, 1);
1795 } else if (Name == "rename" ||
1796 Name == "readlink") {
1797 if (FTy->getNumParams() < 2 ||
1798 !FTy->getParamType(0)->isPointerTy() ||
1799 !FTy->getParamType(1)->isPointerTy())
1802 setDoesNotCapture(F, 1);
1803 setDoesNotCapture(F, 2);
1807 if (Name == "write") {
1808 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1810 // May throw; "write" is a valid pthread cancellation point.
1811 setDoesNotCapture(F, 2);
1815 if (Name == "bcopy") {
1816 if (FTy->getNumParams() != 3 ||
1817 !FTy->getParamType(0)->isPointerTy() ||
1818 !FTy->getParamType(1)->isPointerTy())
1821 setDoesNotCapture(F, 1);
1822 setDoesNotCapture(F, 2);
1823 } else if (Name == "bcmp") {
1824 if (FTy->getNumParams() != 3 ||
1825 !FTy->getParamType(0)->isPointerTy() ||
1826 !FTy->getParamType(1)->isPointerTy())
1829 setOnlyReadsMemory(F);
1830 setDoesNotCapture(F, 1);
1831 setDoesNotCapture(F, 2);
1832 } else if (Name == "bzero") {
1833 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1836 setDoesNotCapture(F, 1);
1840 if (Name == "calloc") {
1841 if (FTy->getNumParams() != 2 ||
1842 !FTy->getReturnType()->isPointerTy())
1845 setDoesNotAlias(F, 0);
1846 } else if (Name == "chmod" ||
1848 Name == "ctermid" ||
1849 Name == "clearerr" ||
1850 Name == "closedir") {
1851 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1854 setDoesNotCapture(F, 1);
1858 if (Name == "atoi" ||
1862 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1865 setOnlyReadsMemory(F);
1866 setDoesNotCapture(F, 1);
1867 } else if (Name == "access") {
1868 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1871 setDoesNotCapture(F, 1);
1875 if (Name == "fopen") {
1876 if (FTy->getNumParams() != 2 ||
1877 !FTy->getReturnType()->isPointerTy() ||
1878 !FTy->getParamType(0)->isPointerTy() ||
1879 !FTy->getParamType(1)->isPointerTy())
1882 setDoesNotAlias(F, 0);
1883 setDoesNotCapture(F, 1);
1884 setDoesNotCapture(F, 2);
1885 } else if (Name == "fdopen") {
1886 if (FTy->getNumParams() != 2 ||
1887 !FTy->getReturnType()->isPointerTy() ||
1888 !FTy->getParamType(1)->isPointerTy())
1891 setDoesNotAlias(F, 0);
1892 setDoesNotCapture(F, 2);
1893 } else if (Name == "feof" ||
1903 Name == "fsetpos" ||
1904 Name == "flockfile" ||
1905 Name == "funlockfile" ||
1906 Name == "ftrylockfile") {
1907 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1910 setDoesNotCapture(F, 1);
1911 } else if (Name == "ferror") {
1912 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1915 setDoesNotCapture(F, 1);
1916 setOnlyReadsMemory(F);
1917 } else if (Name == "fputc" ||
1922 Name == "fstatvfs") {
1923 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1926 setDoesNotCapture(F, 2);
1927 } else if (Name == "fgets") {
1928 if (FTy->getNumParams() != 3 ||
1929 !FTy->getParamType(0)->isPointerTy() ||
1930 !FTy->getParamType(2)->isPointerTy())
1933 setDoesNotCapture(F, 3);
1934 } else if (Name == "fread" ||
1936 if (FTy->getNumParams() != 4 ||
1937 !FTy->getParamType(0)->isPointerTy() ||
1938 !FTy->getParamType(3)->isPointerTy())
1941 setDoesNotCapture(F, 1);
1942 setDoesNotCapture(F, 4);
1943 } else if (Name == "fputs" ||
1945 Name == "fprintf" ||
1946 Name == "fgetpos") {
1947 if (FTy->getNumParams() < 2 ||
1948 !FTy->getParamType(0)->isPointerTy() ||
1949 !FTy->getParamType(1)->isPointerTy())
1952 setDoesNotCapture(F, 1);
1953 setDoesNotCapture(F, 2);
1957 if (Name == "getc" ||
1958 Name == "getlogin_r" ||
1959 Name == "getc_unlocked") {
1960 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1963 setDoesNotCapture(F, 1);
1964 } else if (Name == "getenv") {
1965 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1968 setOnlyReadsMemory(F);
1969 setDoesNotCapture(F, 1);
1970 } else if (Name == "gets" ||
1971 Name == "getchar") {
1973 } else if (Name == "getitimer") {
1974 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1977 setDoesNotCapture(F, 2);
1978 } else if (Name == "getpwnam") {
1979 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1982 setDoesNotCapture(F, 1);
1986 if (Name == "ungetc") {
1987 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1990 setDoesNotCapture(F, 2);
1991 } else if (Name == "uname" ||
1993 Name == "unsetenv") {
1994 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1997 setDoesNotCapture(F, 1);
1998 } else if (Name == "utime" ||
2000 if (FTy->getNumParams() != 2 ||
2001 !FTy->getParamType(0)->isPointerTy() ||
2002 !FTy->getParamType(1)->isPointerTy())
2005 setDoesNotCapture(F, 1);
2006 setDoesNotCapture(F, 2);
2010 if (Name == "putc") {
2011 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2014 setDoesNotCapture(F, 2);
2015 } else if (Name == "puts" ||
2018 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2021 setDoesNotCapture(F, 1);
2022 } else if (Name == "pread" ||
2024 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2026 // May throw; these are valid pthread cancellation points.
2027 setDoesNotCapture(F, 2);
2028 } else if (Name == "putchar") {
2030 } else if (Name == "popen") {
2031 if (FTy->getNumParams() != 2 ||
2032 !FTy->getReturnType()->isPointerTy() ||
2033 !FTy->getParamType(0)->isPointerTy() ||
2034 !FTy->getParamType(1)->isPointerTy())
2037 setDoesNotAlias(F, 0);
2038 setDoesNotCapture(F, 1);
2039 setDoesNotCapture(F, 2);
2040 } else if (Name == "pclose") {
2041 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2044 setDoesNotCapture(F, 1);
2048 if (Name == "vscanf") {
2049 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2052 setDoesNotCapture(F, 1);
2053 } else if (Name == "vsscanf" ||
2054 Name == "vfscanf") {
2055 if (FTy->getNumParams() != 3 ||
2056 !FTy->getParamType(1)->isPointerTy() ||
2057 !FTy->getParamType(2)->isPointerTy())
2060 setDoesNotCapture(F, 1);
2061 setDoesNotCapture(F, 2);
2062 } else if (Name == "valloc") {
2063 if (!FTy->getReturnType()->isPointerTy())
2066 setDoesNotAlias(F, 0);
2067 } else if (Name == "vprintf") {
2068 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2071 setDoesNotCapture(F, 1);
2072 } else if (Name == "vfprintf" ||
2073 Name == "vsprintf") {
2074 if (FTy->getNumParams() != 3 ||
2075 !FTy->getParamType(0)->isPointerTy() ||
2076 !FTy->getParamType(1)->isPointerTy())
2079 setDoesNotCapture(F, 1);
2080 setDoesNotCapture(F, 2);
2081 } else if (Name == "vsnprintf") {
2082 if (FTy->getNumParams() != 4 ||
2083 !FTy->getParamType(0)->isPointerTy() ||
2084 !FTy->getParamType(2)->isPointerTy())
2087 setDoesNotCapture(F, 1);
2088 setDoesNotCapture(F, 3);
2092 if (Name == "open") {
2093 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2095 // May throw; "open" is a valid pthread cancellation point.
2096 setDoesNotCapture(F, 1);
2097 } else if (Name == "opendir") {
2098 if (FTy->getNumParams() != 1 ||
2099 !FTy->getReturnType()->isPointerTy() ||
2100 !FTy->getParamType(0)->isPointerTy())
2103 setDoesNotAlias(F, 0);
2104 setDoesNotCapture(F, 1);
2108 if (Name == "tmpfile") {
2109 if (!FTy->getReturnType()->isPointerTy())
2112 setDoesNotAlias(F, 0);
2113 } else if (Name == "times") {
2114 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2117 setDoesNotCapture(F, 1);
2121 if (Name == "htonl" ||
2124 setDoesNotAccessMemory(F);
2128 if (Name == "ntohl" ||
2131 setDoesNotAccessMemory(F);
2135 if (Name == "lstat") {
2136 if (FTy->getNumParams() != 2 ||
2137 !FTy->getParamType(0)->isPointerTy() ||
2138 !FTy->getParamType(1)->isPointerTy())
2141 setDoesNotCapture(F, 1);
2142 setDoesNotCapture(F, 2);
2143 } else if (Name == "lchown") {
2144 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2147 setDoesNotCapture(F, 1);
2151 if (Name == "qsort") {
2152 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2154 // May throw; places call through function pointer.
2155 setDoesNotCapture(F, 4);
2159 if (Name == "__strdup" ||
2160 Name == "__strndup") {
2161 if (FTy->getNumParams() < 1 ||
2162 !FTy->getReturnType()->isPointerTy() ||
2163 !FTy->getParamType(0)->isPointerTy())
2166 setDoesNotAlias(F, 0);
2167 setDoesNotCapture(F, 1);
2168 } else if (Name == "__strtok_r") {
2169 if (FTy->getNumParams() != 3 ||
2170 !FTy->getParamType(1)->isPointerTy())
2173 setDoesNotCapture(F, 2);
2174 } else if (Name == "_IO_getc") {
2175 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2178 setDoesNotCapture(F, 1);
2179 } else if (Name == "_IO_putc") {
2180 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2183 setDoesNotCapture(F, 2);
2187 if (Name == "\1__isoc99_scanf") {
2188 if (FTy->getNumParams() < 1 ||
2189 !FTy->getParamType(0)->isPointerTy())
2192 setDoesNotCapture(F, 1);
2193 } else if (Name == "\1stat64" ||
2194 Name == "\1lstat64" ||
2195 Name == "\1statvfs64" ||
2196 Name == "\1__isoc99_sscanf") {
2197 if (FTy->getNumParams() < 1 ||
2198 !FTy->getParamType(0)->isPointerTy() ||
2199 !FTy->getParamType(1)->isPointerTy())
2202 setDoesNotCapture(F, 1);
2203 setDoesNotCapture(F, 2);
2204 } else if (Name == "\1fopen64") {
2205 if (FTy->getNumParams() != 2 ||
2206 !FTy->getReturnType()->isPointerTy() ||
2207 !FTy->getParamType(0)->isPointerTy() ||
2208 !FTy->getParamType(1)->isPointerTy())
2211 setDoesNotAlias(F, 0);
2212 setDoesNotCapture(F, 1);
2213 setDoesNotCapture(F, 2);
2214 } else if (Name == "\1fseeko64" ||
2215 Name == "\1ftello64") {
2216 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2219 setDoesNotCapture(F, 1);
2220 } else if (Name == "\1tmpfile64") {
2221 if (!FTy->getReturnType()->isPointerTy())
2224 setDoesNotAlias(F, 0);
2225 } else if (Name == "\1fstat64" ||
2226 Name == "\1fstatvfs64") {
2227 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2230 setDoesNotCapture(F, 2);
2231 } else if (Name == "\1open64") {
2232 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2234 // May throw; "open" is a valid pthread cancellation point.
2235 setDoesNotCapture(F, 1);
2241 /// doInitialization - Add attributes to well-known functions.
2243 bool SimplifyLibCalls::doInitialization(Module &M) {
2245 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2247 if (F.isDeclaration() && F.hasName())
2248 inferPrototypeAttributes(F);
2254 // Additional cases that we need to add to this file:
2257 // * cbrt(expN(X)) -> expN(x/3)
2258 // * cbrt(sqrt(x)) -> pow(x,1/6)
2259 // * cbrt(sqrt(x)) -> pow(x,1/9)
2262 // * cos(-x) -> cos(x)
2265 // * exp(log(x)) -> x
2268 // * log(exp(x)) -> x
2269 // * log(x**y) -> y*log(x)
2270 // * log(exp(y)) -> y*log(e)
2271 // * log(exp2(y)) -> y*log(2)
2272 // * log(exp10(y)) -> y*log(10)
2273 // * log(sqrt(x)) -> 0.5*log(x)
2274 // * log(pow(x,y)) -> y*log(x)
2276 // lround, lroundf, lroundl:
2277 // * lround(cnst) -> cnst'
2280 // * pow(exp(x),y) -> exp(x*y)
2281 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2282 // * pow(pow(x,y),z)-> pow(x,y*z)
2284 // round, roundf, roundl:
2285 // * round(cnst) -> cnst'
2288 // * signbit(cnst) -> cnst'
2289 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2291 // sqrt, sqrtf, sqrtl:
2292 // * sqrt(expN(x)) -> expN(x*0.5)
2293 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2294 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2297 // * stpcpy(str, "literal") ->
2298 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2301 // * tan(atan(x)) -> x
2303 // trunc, truncf, truncl:
2304 // * trunc(cnst) -> cnst'