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/IRBuilder.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/DataLayout.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
39 STATISTIC(NumSimplified, "Number of library calls simplified");
40 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
42 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46 //===----------------------------------------------------------------------===//
47 // Optimizer Base Class
48 //===----------------------------------------------------------------------===//
50 /// This class is the abstract base class for the set of optimizations that
51 /// corresponds to one library call.
53 class LibCallOptimization {
57 const TargetLibraryInfo *TLI;
60 LibCallOptimization() { }
61 virtual ~LibCallOptimization() {}
63 /// CallOptimizer - This pure virtual method is implemented by base classes to
64 /// do various optimizations. If this returns null then no transformation was
65 /// performed. If it returns CI, then it transformed the call and CI is to be
66 /// deleted. If it returns something else, replace CI with the new value and
68 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
71 Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
72 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
73 Caller = CI->getParent()->getParent();
76 if (CI->getCalledFunction())
77 Context = &CI->getCalledFunction()->getContext();
79 // We never change the calling convention.
80 if (CI->getCallingConv() != llvm::CallingConv::C)
83 return CallOptimizer(CI->getCalledFunction(), CI, B);
86 } // End anonymous namespace.
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
94 /// value is equal or not-equal to zero.
95 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
96 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
98 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
100 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
101 if (C->isNullValue())
103 // Unknown instruction.
109 static bool CallHasFloatingPointArgument(const CallInst *CI) {
110 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
112 if ((*it)->getType()->isFloatingPointTy())
118 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
119 /// comparisons with With.
120 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
121 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
123 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
124 if (IC->isEquality() && IC->getOperand(1) == With)
126 // Unknown instruction.
132 //===----------------------------------------------------------------------===//
133 // String and Memory LibCall Optimizations
134 //===----------------------------------------------------------------------===//
137 //===---------------------------------------===//
138 // 'strncpy' Optimizations
140 struct StrNCpyOpt : public LibCallOptimization {
141 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
142 FunctionType *FT = Callee->getFunctionType();
143 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
144 FT->getParamType(0) != FT->getParamType(1) ||
145 FT->getParamType(0) != B.getInt8PtrTy() ||
146 !FT->getParamType(2)->isIntegerTy())
149 Value *Dst = CI->getArgOperand(0);
150 Value *Src = CI->getArgOperand(1);
151 Value *LenOp = CI->getArgOperand(2);
153 // See if we can get the length of the input string.
154 uint64_t SrcLen = GetStringLength(Src);
155 if (SrcLen == 0) return 0;
159 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
160 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
165 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
166 Len = LengthArg->getZExtValue();
170 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
172 // These optimizations require DataLayout.
175 // Let strncpy handle the zero padding
176 if (Len > SrcLen+1) return 0;
178 Type *PT = FT->getParamType(0);
179 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
180 B.CreateMemCpy(Dst, Src,
181 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
187 //===---------------------------------------===//
188 // 'strlen' Optimizations
190 struct StrLenOpt : public LibCallOptimization {
191 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
192 FunctionType *FT = Callee->getFunctionType();
193 if (FT->getNumParams() != 1 ||
194 FT->getParamType(0) != B.getInt8PtrTy() ||
195 !FT->getReturnType()->isIntegerTy())
198 Value *Src = CI->getArgOperand(0);
200 // Constant folding: strlen("xyz") -> 3
201 if (uint64_t Len = GetStringLength(Src))
202 return ConstantInt::get(CI->getType(), Len-1);
204 // strlen(x) != 0 --> *x != 0
205 // strlen(x) == 0 --> *x == 0
206 if (IsOnlyUsedInZeroEqualityComparison(CI))
207 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
213 //===---------------------------------------===//
214 // 'strpbrk' Optimizations
216 struct StrPBrkOpt : public LibCallOptimization {
217 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
218 FunctionType *FT = Callee->getFunctionType();
219 if (FT->getNumParams() != 2 ||
220 FT->getParamType(0) != B.getInt8PtrTy() ||
221 FT->getParamType(1) != FT->getParamType(0) ||
222 FT->getReturnType() != FT->getParamType(0))
226 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
227 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
229 // strpbrk(s, "") -> NULL
230 // strpbrk("", s) -> NULL
231 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
232 return Constant::getNullValue(CI->getType());
235 if (HasS1 && HasS2) {
236 size_t I = S1.find_first_of(S2);
237 if (I == std::string::npos) // No match.
238 return Constant::getNullValue(CI->getType());
240 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
243 // strpbrk(s, "a") -> strchr(s, 'a')
244 if (TD && HasS2 && S2.size() == 1)
245 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
251 //===---------------------------------------===//
252 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
254 struct StrToOpt : public LibCallOptimization {
255 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
256 FunctionType *FT = Callee->getFunctionType();
257 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
258 !FT->getParamType(0)->isPointerTy() ||
259 !FT->getParamType(1)->isPointerTy())
262 Value *EndPtr = CI->getArgOperand(1);
263 if (isa<ConstantPointerNull>(EndPtr)) {
264 // With a null EndPtr, this function won't capture the main argument.
265 // It would be readonly too, except that it still may write to errno.
266 CI->addAttribute(1, Attributes::get(Callee->getContext(),
267 Attributes::NoCapture));
274 //===---------------------------------------===//
275 // 'strspn' Optimizations
277 struct StrSpnOpt : public LibCallOptimization {
278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
279 FunctionType *FT = Callee->getFunctionType();
280 if (FT->getNumParams() != 2 ||
281 FT->getParamType(0) != B.getInt8PtrTy() ||
282 FT->getParamType(1) != FT->getParamType(0) ||
283 !FT->getReturnType()->isIntegerTy())
287 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
288 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
290 // strspn(s, "") -> 0
291 // strspn("", s) -> 0
292 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
293 return Constant::getNullValue(CI->getType());
296 if (HasS1 && HasS2) {
297 size_t Pos = S1.find_first_not_of(S2);
298 if (Pos == StringRef::npos) Pos = S1.size();
299 return ConstantInt::get(CI->getType(), Pos);
306 //===---------------------------------------===//
307 // 'strcspn' Optimizations
309 struct StrCSpnOpt : public LibCallOptimization {
310 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
311 FunctionType *FT = Callee->getFunctionType();
312 if (FT->getNumParams() != 2 ||
313 FT->getParamType(0) != B.getInt8PtrTy() ||
314 FT->getParamType(1) != FT->getParamType(0) ||
315 !FT->getReturnType()->isIntegerTy())
319 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
320 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
322 // strcspn("", s) -> 0
323 if (HasS1 && S1.empty())
324 return Constant::getNullValue(CI->getType());
327 if (HasS1 && HasS2) {
328 size_t Pos = S1.find_first_of(S2);
329 if (Pos == StringRef::npos) Pos = S1.size();
330 return ConstantInt::get(CI->getType(), Pos);
333 // strcspn(s, "") -> strlen(s)
334 if (TD && HasS2 && S2.empty())
335 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
341 //===---------------------------------------===//
342 // 'strstr' Optimizations
344 struct StrStrOpt : public LibCallOptimization {
345 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
346 FunctionType *FT = Callee->getFunctionType();
347 if (FT->getNumParams() != 2 ||
348 !FT->getParamType(0)->isPointerTy() ||
349 !FT->getParamType(1)->isPointerTy() ||
350 !FT->getReturnType()->isPointerTy())
353 // fold strstr(x, x) -> x.
354 if (CI->getArgOperand(0) == CI->getArgOperand(1))
355 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
357 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
358 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
359 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
362 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
366 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
368 ICmpInst *Old = cast<ICmpInst>(*UI++);
369 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
370 ConstantInt::getNullValue(StrNCmp->getType()),
372 Old->replaceAllUsesWith(Cmp);
373 Old->eraseFromParent();
378 // See if either input string is a constant string.
379 StringRef SearchStr, ToFindStr;
380 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
381 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
383 // fold strstr(x, "") -> x.
384 if (HasStr2 && ToFindStr.empty())
385 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
387 // If both strings are known, constant fold it.
388 if (HasStr1 && HasStr2) {
389 std::string::size_type Offset = SearchStr.find(ToFindStr);
391 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
392 return Constant::getNullValue(CI->getType());
394 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
395 Value *Result = CastToCStr(CI->getArgOperand(0), B);
396 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
397 return B.CreateBitCast(Result, CI->getType());
400 // fold strstr(x, "y") -> strchr(x, 'y').
401 if (HasStr2 && ToFindStr.size() == 1) {
402 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
403 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
410 //===---------------------------------------===//
411 // 'memcmp' Optimizations
413 struct MemCmpOpt : public LibCallOptimization {
414 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
415 FunctionType *FT = Callee->getFunctionType();
416 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
417 !FT->getParamType(1)->isPointerTy() ||
418 !FT->getReturnType()->isIntegerTy(32))
421 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
423 if (LHS == RHS) // memcmp(s,s,x) -> 0
424 return Constant::getNullValue(CI->getType());
426 // Make sure we have a constant length.
427 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
429 uint64_t Len = LenC->getZExtValue();
431 if (Len == 0) // memcmp(s1,s2,0) -> 0
432 return Constant::getNullValue(CI->getType());
434 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
436 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
437 CI->getType(), "lhsv");
438 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
439 CI->getType(), "rhsv");
440 return B.CreateSub(LHSV, RHSV, "chardiff");
443 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
444 StringRef LHSStr, RHSStr;
445 if (getConstantStringInfo(LHS, LHSStr) &&
446 getConstantStringInfo(RHS, RHSStr)) {
447 // Make sure we're not reading out-of-bounds memory.
448 if (Len > LHSStr.size() || Len > RHSStr.size())
450 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
451 return ConstantInt::get(CI->getType(), Ret);
458 //===---------------------------------------===//
459 // 'memcpy' Optimizations
461 struct MemCpyOpt : public LibCallOptimization {
462 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
463 // These optimizations require DataLayout.
466 FunctionType *FT = Callee->getFunctionType();
467 Type *PT = FT->getParamType(0);
468 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
469 !FT->getParamType(0)->isPointerTy() ||
470 !FT->getParamType(1)->isPointerTy() ||
471 FT->getParamType(2) != TD->getIntPtrType(PT))
474 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
475 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
476 CI->getArgOperand(2), 1);
477 return CI->getArgOperand(0);
481 //===---------------------------------------===//
482 // 'memmove' Optimizations
484 struct MemMoveOpt : public LibCallOptimization {
485 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
486 // These optimizations require DataLayout.
489 FunctionType *FT = Callee->getFunctionType();
490 Type *PT = FT->getParamType(0);
491 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
492 !FT->getParamType(0)->isPointerTy() ||
493 !FT->getParamType(1)->isPointerTy() ||
494 FT->getParamType(2) != TD->getIntPtrType(PT))
497 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
498 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
499 CI->getArgOperand(2), 1);
500 return CI->getArgOperand(0);
504 //===---------------------------------------===//
505 // 'memset' Optimizations
507 struct MemSetOpt : public LibCallOptimization {
508 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
509 // These optimizations require DataLayout.
512 FunctionType *FT = Callee->getFunctionType();
513 Type *PT = FT->getParamType(0);
514 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
515 !FT->getParamType(0)->isPointerTy() ||
516 !FT->getParamType(1)->isIntegerTy() ||
517 FT->getParamType(2) != TD->getIntPtrType(PT))
520 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
521 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
522 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
523 return CI->getArgOperand(0);
527 //===----------------------------------------------------------------------===//
528 // Math Library Optimizations
529 //===----------------------------------------------------------------------===//
531 //===---------------------------------------===//
532 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
534 struct UnaryDoubleFPOpt : public LibCallOptimization {
536 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
537 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
538 FunctionType *FT = Callee->getFunctionType();
539 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
540 !FT->getParamType(0)->isDoubleTy())
544 // Check if all the uses for function like 'sin' are converted to float.
545 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
547 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
548 if (Cast == 0 || !Cast->getType()->isFloatTy())
553 // If this is something like 'floor((double)floatval)', convert to floorf.
554 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
555 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
558 // floor((double)floatval) -> (double)floorf(floatval)
559 Value *V = Cast->getOperand(0);
560 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
561 return B.CreateFPExt(V, B.getDoubleTy());
565 //===---------------------------------------===//
566 // 'cos*' Optimizations
567 struct CosOpt : public LibCallOptimization {
568 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
570 if (UnsafeFPShrink && Callee->getName() == "cos" &&
571 TLI->has(LibFunc::cosf)) {
572 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
573 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
576 FunctionType *FT = Callee->getFunctionType();
577 // Just make sure this has 1 argument of FP type, which matches the
579 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
580 !FT->getParamType(0)->isFloatingPointTy())
584 Value *Op1 = CI->getArgOperand(0);
585 if (BinaryOperator::isFNeg(Op1)) {
586 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
587 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
593 //===---------------------------------------===//
594 // 'pow*' Optimizations
596 struct PowOpt : public LibCallOptimization {
597 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
599 if (UnsafeFPShrink && Callee->getName() == "pow" &&
600 TLI->has(LibFunc::powf)) {
601 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
602 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
605 FunctionType *FT = Callee->getFunctionType();
606 // Just make sure this has 2 arguments of the same FP type, which match the
608 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
609 FT->getParamType(0) != FT->getParamType(1) ||
610 !FT->getParamType(0)->isFloatingPointTy())
613 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
614 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
615 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
617 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
618 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
621 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
622 if (Op2C == 0) return Ret;
624 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
625 return ConstantFP::get(CI->getType(), 1.0);
627 if (Op2C->isExactlyValue(0.5)) {
628 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
629 // This is faster than calling pow, and still handles negative zero
630 // and negative infinity correctly.
631 // TODO: In fast-math mode, this could be just sqrt(x).
632 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
633 Value *Inf = ConstantFP::getInfinity(CI->getType());
634 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
635 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
636 Callee->getAttributes());
637 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
638 Callee->getAttributes());
639 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
640 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
644 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
646 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
647 return B.CreateFMul(Op1, Op1, "pow2");
648 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
649 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
655 //===---------------------------------------===//
656 // 'exp2' Optimizations
658 struct Exp2Opt : public LibCallOptimization {
659 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
661 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
662 TLI->has(LibFunc::exp2)) {
663 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
664 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
667 FunctionType *FT = Callee->getFunctionType();
668 // Just make sure this has 1 argument of FP type, which matches the
670 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
671 !FT->getParamType(0)->isFloatingPointTy())
674 Value *Op = CI->getArgOperand(0);
675 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
676 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
678 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
679 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
680 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
681 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
682 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
683 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
688 if (Op->getType()->isFloatTy())
690 else if (Op->getType()->isDoubleTy())
695 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
696 if (!Op->getType()->isFloatTy())
697 One = ConstantExpr::getFPExtend(One, Op->getType());
699 Module *M = Caller->getParent();
700 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
702 B.getInt32Ty(), NULL);
703 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
704 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
705 CI->setCallingConv(F->getCallingConv());
713 //===----------------------------------------------------------------------===//
714 // Integer Optimizations
715 //===----------------------------------------------------------------------===//
717 //===---------------------------------------===//
718 // 'ffs*' Optimizations
720 struct FFSOpt : public LibCallOptimization {
721 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
722 FunctionType *FT = Callee->getFunctionType();
723 // Just make sure this has 2 arguments of the same FP type, which match the
725 if (FT->getNumParams() != 1 ||
726 !FT->getReturnType()->isIntegerTy(32) ||
727 !FT->getParamType(0)->isIntegerTy())
730 Value *Op = CI->getArgOperand(0);
733 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
734 if (CI->isZero()) // ffs(0) -> 0.
735 return B.getInt32(0);
736 // ffs(c) -> cttz(c)+1
737 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
740 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
741 Type *ArgType = Op->getType();
742 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
743 Intrinsic::cttz, ArgType);
744 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
745 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
746 V = B.CreateIntCast(V, B.getInt32Ty(), false);
748 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
749 return B.CreateSelect(Cond, V, B.getInt32(0));
753 //===---------------------------------------===//
754 // 'isdigit' Optimizations
756 struct IsDigitOpt : public LibCallOptimization {
757 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
758 FunctionType *FT = Callee->getFunctionType();
759 // We require integer(i32)
760 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
761 !FT->getParamType(0)->isIntegerTy(32))
764 // isdigit(c) -> (c-'0') <u 10
765 Value *Op = CI->getArgOperand(0);
766 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
767 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
768 return B.CreateZExt(Op, CI->getType());
772 //===---------------------------------------===//
773 // 'isascii' Optimizations
775 struct IsAsciiOpt : public LibCallOptimization {
776 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
777 FunctionType *FT = Callee->getFunctionType();
778 // We require integer(i32)
779 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
780 !FT->getParamType(0)->isIntegerTy(32))
783 // isascii(c) -> c <u 128
784 Value *Op = CI->getArgOperand(0);
785 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
786 return B.CreateZExt(Op, CI->getType());
790 //===---------------------------------------===//
791 // 'abs', 'labs', 'llabs' Optimizations
793 struct AbsOpt : public LibCallOptimization {
794 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
795 FunctionType *FT = Callee->getFunctionType();
796 // We require integer(integer) where the types agree.
797 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
798 FT->getParamType(0) != FT->getReturnType())
801 // abs(x) -> x >s -1 ? x : -x
802 Value *Op = CI->getArgOperand(0);
803 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
805 Value *Neg = B.CreateNeg(Op, "neg");
806 return B.CreateSelect(Pos, Op, Neg);
811 //===---------------------------------------===//
812 // 'toascii' Optimizations
814 struct ToAsciiOpt : public LibCallOptimization {
815 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
816 FunctionType *FT = Callee->getFunctionType();
817 // We require i32(i32)
818 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
819 !FT->getParamType(0)->isIntegerTy(32))
822 // isascii(c) -> c & 0x7f
823 return B.CreateAnd(CI->getArgOperand(0),
824 ConstantInt::get(CI->getType(),0x7F));
828 //===----------------------------------------------------------------------===//
829 // Formatting and IO Optimizations
830 //===----------------------------------------------------------------------===//
832 //===---------------------------------------===//
833 // 'printf' Optimizations
835 struct PrintFOpt : public LibCallOptimization {
836 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
838 // Check for a fixed format string.
840 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
843 // Empty format string -> noop.
844 if (FormatStr.empty()) // Tolerate printf's declared void.
845 return CI->use_empty() ? (Value*)CI :
846 ConstantInt::get(CI->getType(), 0);
848 // Do not do any of the following transformations if the printf return value
849 // is used, in general the printf return value is not compatible with either
850 // putchar() or puts().
851 if (!CI->use_empty())
854 // printf("x") -> putchar('x'), even for '%'.
855 if (FormatStr.size() == 1) {
856 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
857 if (CI->use_empty() || !Res) return Res;
858 return B.CreateIntCast(Res, CI->getType(), true);
861 // printf("foo\n") --> puts("foo")
862 if (FormatStr[FormatStr.size()-1] == '\n' &&
863 FormatStr.find('%') == std::string::npos) { // no format characters.
864 // Create a string literal with no \n on it. We expect the constant merge
865 // pass to be run after this pass, to merge duplicate strings.
866 FormatStr = FormatStr.drop_back();
867 Value *GV = B.CreateGlobalString(FormatStr, "str");
868 Value *NewCI = EmitPutS(GV, B, TD, TLI);
869 return (CI->use_empty() || !NewCI) ?
871 ConstantInt::get(CI->getType(), FormatStr.size()+1);
874 // Optimize specific format strings.
875 // printf("%c", chr) --> putchar(chr)
876 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
877 CI->getArgOperand(1)->getType()->isIntegerTy()) {
878 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
880 if (CI->use_empty() || !Res) return Res;
881 return B.CreateIntCast(Res, CI->getType(), true);
884 // printf("%s\n", str) --> puts(str)
885 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
886 CI->getArgOperand(1)->getType()->isPointerTy()) {
887 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
892 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
893 // Require one fixed pointer argument and an integer/void result.
894 FunctionType *FT = Callee->getFunctionType();
895 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
896 !(FT->getReturnType()->isIntegerTy() ||
897 FT->getReturnType()->isVoidTy()))
900 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
904 // printf(format, ...) -> iprintf(format, ...) if no floating point
906 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
907 Module *M = B.GetInsertBlock()->getParent()->getParent();
908 Constant *IPrintFFn =
909 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
910 CallInst *New = cast<CallInst>(CI->clone());
911 New->setCalledFunction(IPrintFFn);
919 //===---------------------------------------===//
920 // 'sprintf' Optimizations
922 struct SPrintFOpt : public LibCallOptimization {
923 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
925 // Check for a fixed format string.
927 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
930 // If we just have a format string (nothing else crazy) transform it.
931 if (CI->getNumArgOperands() == 2) {
932 // Make sure there's no % in the constant array. We could try to handle
933 // %% -> % in the future if we cared.
934 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
935 if (FormatStr[i] == '%')
936 return 0; // we found a format specifier, bail out.
938 // These optimizations require DataLayout.
941 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
942 Type *AT = CI->getArgOperand(0)->getType();
943 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
944 ConstantInt::get(TD->getIntPtrType(AT), // Copy the
945 FormatStr.size() + 1), 1); // nul byte.
946 return ConstantInt::get(CI->getType(), FormatStr.size());
949 // The remaining optimizations require the format string to be "%s" or "%c"
950 // and have an extra operand.
951 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
952 CI->getNumArgOperands() < 3)
955 // Decode the second character of the format string.
956 if (FormatStr[1] == 'c') {
957 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
958 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
959 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
960 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
961 B.CreateStore(V, Ptr);
962 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
963 B.CreateStore(B.getInt8(0), Ptr);
965 return ConstantInt::get(CI->getType(), 1);
968 if (FormatStr[1] == 's') {
969 // These optimizations require DataLayout.
972 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
973 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
975 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
978 Value *IncLen = B.CreateAdd(Len,
979 ConstantInt::get(Len->getType(), 1),
981 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
983 // The sprintf result is the unincremented number of bytes in the string.
984 return B.CreateIntCast(Len, CI->getType(), false);
989 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
990 // Require two fixed pointer arguments and an integer result.
991 FunctionType *FT = Callee->getFunctionType();
992 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
993 !FT->getParamType(1)->isPointerTy() ||
994 !FT->getReturnType()->isIntegerTy())
997 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1001 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1003 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1004 Module *M = B.GetInsertBlock()->getParent()->getParent();
1005 Constant *SIPrintFFn =
1006 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1007 CallInst *New = cast<CallInst>(CI->clone());
1008 New->setCalledFunction(SIPrintFFn);
1016 //===---------------------------------------===//
1017 // 'fwrite' Optimizations
1019 struct FWriteOpt : public LibCallOptimization {
1020 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1021 // Require a pointer, an integer, an integer, a pointer, returning integer.
1022 FunctionType *FT = Callee->getFunctionType();
1023 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1024 !FT->getParamType(1)->isIntegerTy() ||
1025 !FT->getParamType(2)->isIntegerTy() ||
1026 !FT->getParamType(3)->isPointerTy() ||
1027 !FT->getReturnType()->isIntegerTy())
1030 // Get the element size and count.
1031 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1032 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1033 if (!SizeC || !CountC) return 0;
1034 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1036 // If this is writing zero records, remove the call (it's a noop).
1038 return ConstantInt::get(CI->getType(), 0);
1040 // If this is writing one byte, turn it into fputc.
1041 // This optimisation is only valid, if the return value is unused.
1042 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1043 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1044 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1045 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1052 //===---------------------------------------===//
1053 // 'fputs' Optimizations
1055 struct FPutsOpt : public LibCallOptimization {
1056 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1057 // These optimizations require DataLayout.
1060 // Require two pointers. Also, we can't optimize if return value is used.
1061 FunctionType *FT = Callee->getFunctionType();
1062 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1063 !FT->getParamType(1)->isPointerTy() ||
1067 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1068 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1070 // Known to have no uses (see above).
1071 Type *PT = FT->getParamType(0);
1072 return EmitFWrite(CI->getArgOperand(0),
1073 ConstantInt::get(TD->getIntPtrType(PT), Len-1),
1074 CI->getArgOperand(1), B, TD, TLI);
1078 //===---------------------------------------===//
1079 // 'fprintf' Optimizations
1081 struct FPrintFOpt : public LibCallOptimization {
1082 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1084 // All the optimizations depend on the format string.
1085 StringRef FormatStr;
1086 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1089 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1090 if (CI->getNumArgOperands() == 2) {
1091 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1092 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1093 return 0; // We found a format specifier.
1095 // These optimizations require DataLayout.
1098 Type *AT = CI->getArgOperand(1)->getType();
1099 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1100 ConstantInt::get(TD->getIntPtrType(AT),
1102 CI->getArgOperand(0), B, TD, TLI);
1103 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
1106 // The remaining optimizations require the format string to be "%s" or "%c"
1107 // and have an extra operand.
1108 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1109 CI->getNumArgOperands() < 3)
1112 // Decode the second character of the format string.
1113 if (FormatStr[1] == 'c') {
1114 // fprintf(F, "%c", chr) --> fputc(chr, F)
1115 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1116 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1118 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1121 if (FormatStr[1] == 's') {
1122 // fprintf(F, "%s", str) --> fputs(str, F)
1123 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1125 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1130 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1131 // Require two fixed paramters as pointers and integer result.
1132 FunctionType *FT = Callee->getFunctionType();
1133 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1134 !FT->getParamType(1)->isPointerTy() ||
1135 !FT->getReturnType()->isIntegerTy())
1138 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1142 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1143 // floating point arguments.
1144 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1145 Module *M = B.GetInsertBlock()->getParent()->getParent();
1146 Constant *FIPrintFFn =
1147 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1148 CallInst *New = cast<CallInst>(CI->clone());
1149 New->setCalledFunction(FIPrintFFn);
1157 //===---------------------------------------===//
1158 // 'puts' Optimizations
1160 struct PutsOpt : public LibCallOptimization {
1161 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1162 // Require one fixed pointer argument and an integer/void result.
1163 FunctionType *FT = Callee->getFunctionType();
1164 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1165 !(FT->getReturnType()->isIntegerTy() ||
1166 FT->getReturnType()->isVoidTy()))
1169 // Check for a constant string.
1171 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1174 if (Str.empty() && CI->use_empty()) {
1175 // puts("") -> putchar('\n')
1176 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1177 if (CI->use_empty() || !Res) return Res;
1178 return B.CreateIntCast(Res, CI->getType(), true);
1185 } // end anonymous namespace.
1187 //===----------------------------------------------------------------------===//
1188 // SimplifyLibCalls Pass Implementation
1189 //===----------------------------------------------------------------------===//
1192 /// This pass optimizes well known library functions from libc and libm.
1194 class SimplifyLibCalls : public FunctionPass {
1195 TargetLibraryInfo *TLI;
1197 StringMap<LibCallOptimization*> Optimizations;
1198 // String and Memory LibCall Optimizations
1200 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1201 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1202 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1203 // Math Library Optimizations
1204 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1205 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
1206 // Integer Optimizations
1207 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1209 // Formatting and IO Optimizations
1210 SPrintFOpt SPrintF; PrintFOpt PrintF;
1211 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1214 bool Modified; // This is only used by doInitialization.
1216 static char ID; // Pass identification
1217 SimplifyLibCalls() : FunctionPass(ID), UnaryDoubleFP(false),
1218 UnsafeUnaryDoubleFP(true) {
1219 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1221 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1222 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1224 void InitOptimizations();
1225 bool runOnFunction(Function &F);
1227 void setDoesNotAccessMemory(Function &F);
1228 void setOnlyReadsMemory(Function &F);
1229 void setDoesNotThrow(Function &F);
1230 void setDoesNotCapture(Function &F, unsigned n);
1231 void setDoesNotAlias(Function &F, unsigned n);
1232 bool doInitialization(Module &M);
1234 void inferPrototypeAttributes(Function &F);
1235 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1236 AU.addRequired<TargetLibraryInfo>();
1239 } // end anonymous namespace.
1241 char SimplifyLibCalls::ID = 0;
1243 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1244 "Simplify well-known library calls", false, false)
1245 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1246 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1247 "Simplify well-known library calls", false, false)
1249 // Public interface to the Simplify LibCalls pass.
1250 FunctionPass *llvm::createSimplifyLibCallsPass() {
1251 return new SimplifyLibCalls();
1254 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1256 Optimizations[TLI->getName(F)] = Opt;
1259 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1260 LibCallOptimization* Opt) {
1261 if (TLI->has(F1) && TLI->has(F2))
1262 Optimizations[TLI->getName(F1)] = Opt;
1265 /// Optimizations - Populate the Optimizations map with all the optimizations
1267 void SimplifyLibCalls::InitOptimizations() {
1268 // String and Memory LibCall Optimizations
1269 Optimizations["strncpy"] = &StrNCpy;
1270 Optimizations["strlen"] = &StrLen;
1271 Optimizations["strpbrk"] = &StrPBrk;
1272 Optimizations["strtol"] = &StrTo;
1273 Optimizations["strtod"] = &StrTo;
1274 Optimizations["strtof"] = &StrTo;
1275 Optimizations["strtoul"] = &StrTo;
1276 Optimizations["strtoll"] = &StrTo;
1277 Optimizations["strtold"] = &StrTo;
1278 Optimizations["strtoull"] = &StrTo;
1279 Optimizations["strspn"] = &StrSpn;
1280 Optimizations["strcspn"] = &StrCSpn;
1281 Optimizations["strstr"] = &StrStr;
1282 Optimizations["memcmp"] = &MemCmp;
1283 AddOpt(LibFunc::memcpy, &MemCpy);
1284 Optimizations["memmove"] = &MemMove;
1285 AddOpt(LibFunc::memset, &MemSet);
1287 // Math Library Optimizations
1288 Optimizations["cosf"] = &Cos;
1289 Optimizations["cos"] = &Cos;
1290 Optimizations["cosl"] = &Cos;
1291 Optimizations["powf"] = &Pow;
1292 Optimizations["pow"] = &Pow;
1293 Optimizations["powl"] = &Pow;
1294 Optimizations["llvm.pow.f32"] = &Pow;
1295 Optimizations["llvm.pow.f64"] = &Pow;
1296 Optimizations["llvm.pow.f80"] = &Pow;
1297 Optimizations["llvm.pow.f128"] = &Pow;
1298 Optimizations["llvm.pow.ppcf128"] = &Pow;
1299 Optimizations["exp2l"] = &Exp2;
1300 Optimizations["exp2"] = &Exp2;
1301 Optimizations["exp2f"] = &Exp2;
1302 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1303 Optimizations["llvm.exp2.f128"] = &Exp2;
1304 Optimizations["llvm.exp2.f80"] = &Exp2;
1305 Optimizations["llvm.exp2.f64"] = &Exp2;
1306 Optimizations["llvm.exp2.f32"] = &Exp2;
1308 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1309 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
1310 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1311 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1312 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1313 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1314 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
1316 if(UnsafeFPShrink) {
1317 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1318 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1319 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1320 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1321 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1322 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1323 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1324 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1325 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1326 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1327 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1328 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1329 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1330 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1331 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1332 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1333 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1334 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1335 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1336 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1337 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1340 // Integer Optimizations
1341 Optimizations["ffs"] = &FFS;
1342 Optimizations["ffsl"] = &FFS;
1343 Optimizations["ffsll"] = &FFS;
1344 Optimizations["abs"] = &Abs;
1345 Optimizations["labs"] = &Abs;
1346 Optimizations["llabs"] = &Abs;
1347 Optimizations["isdigit"] = &IsDigit;
1348 Optimizations["isascii"] = &IsAscii;
1349 Optimizations["toascii"] = &ToAscii;
1351 // Formatting and IO Optimizations
1352 Optimizations["sprintf"] = &SPrintF;
1353 Optimizations["printf"] = &PrintF;
1354 AddOpt(LibFunc::fwrite, &FWrite);
1355 AddOpt(LibFunc::fputs, &FPuts);
1356 Optimizations["fprintf"] = &FPrintF;
1357 Optimizations["puts"] = &Puts;
1361 /// runOnFunction - Top level algorithm.
1363 bool SimplifyLibCalls::runOnFunction(Function &F) {
1364 TLI = &getAnalysis<TargetLibraryInfo>();
1366 if (Optimizations.empty())
1367 InitOptimizations();
1369 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
1371 IRBuilder<> Builder(F.getContext());
1373 bool Changed = false;
1374 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1375 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1376 // Ignore non-calls.
1377 CallInst *CI = dyn_cast<CallInst>(I++);
1380 // Ignore indirect calls and calls to non-external functions.
1381 Function *Callee = CI->getCalledFunction();
1382 if (Callee == 0 || !Callee->isDeclaration() ||
1383 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1386 // Ignore unknown calls.
1387 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1390 // Set the builder to the instruction after the call.
1391 Builder.SetInsertPoint(BB, I);
1393 // Use debug location of CI for all new instructions.
1394 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1396 // Try to optimize this call.
1397 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1398 if (Result == 0) continue;
1400 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1401 dbgs() << " into: " << *Result << "\n");
1403 // Something changed!
1407 // Inspect the instruction after the call (which was potentially just
1411 if (CI != Result && !CI->use_empty()) {
1412 CI->replaceAllUsesWith(Result);
1413 if (!Result->hasName())
1414 Result->takeName(CI);
1416 CI->eraseFromParent();
1422 // Utility methods for doInitialization.
1424 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1425 if (!F.doesNotAccessMemory()) {
1426 F.setDoesNotAccessMemory();
1431 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1432 if (!F.onlyReadsMemory()) {
1433 F.setOnlyReadsMemory();
1438 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1439 if (!F.doesNotThrow()) {
1440 F.setDoesNotThrow();
1445 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1446 if (!F.doesNotCapture(n)) {
1447 F.setDoesNotCapture(n);
1452 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1453 if (!F.doesNotAlias(n)) {
1454 F.setDoesNotAlias(n);
1461 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1462 FunctionType *FTy = F.getFunctionType();
1464 StringRef Name = F.getName();
1467 if (Name == "strlen") {
1468 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1470 setOnlyReadsMemory(F);
1472 setDoesNotCapture(F, 1);
1473 } else if (Name == "strchr" ||
1474 Name == "strrchr") {
1475 if (FTy->getNumParams() != 2 ||
1476 !FTy->getParamType(0)->isPointerTy() ||
1477 !FTy->getParamType(1)->isIntegerTy())
1479 setOnlyReadsMemory(F);
1481 } else if (Name == "strcpy" ||
1487 Name == "strtoul" ||
1488 Name == "strtoll" ||
1489 Name == "strtold" ||
1490 Name == "strncat" ||
1491 Name == "strncpy" ||
1492 Name == "stpncpy" ||
1493 Name == "strtoull") {
1494 if (FTy->getNumParams() < 2 ||
1495 !FTy->getParamType(1)->isPointerTy())
1498 setDoesNotCapture(F, 2);
1499 } else if (Name == "strxfrm") {
1500 if (FTy->getNumParams() != 3 ||
1501 !FTy->getParamType(0)->isPointerTy() ||
1502 !FTy->getParamType(1)->isPointerTy())
1505 setDoesNotCapture(F, 1);
1506 setDoesNotCapture(F, 2);
1507 } else if (Name == "strcmp" ||
1509 Name == "strncmp" ||
1510 Name == "strcspn" ||
1511 Name == "strcoll" ||
1512 Name == "strcasecmp" ||
1513 Name == "strncasecmp") {
1514 if (FTy->getNumParams() < 2 ||
1515 !FTy->getParamType(0)->isPointerTy() ||
1516 !FTy->getParamType(1)->isPointerTy())
1518 setOnlyReadsMemory(F);
1520 setDoesNotCapture(F, 1);
1521 setDoesNotCapture(F, 2);
1522 } else if (Name == "strstr" ||
1523 Name == "strpbrk") {
1524 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1526 setOnlyReadsMemory(F);
1528 setDoesNotCapture(F, 2);
1529 } else if (Name == "strtok" ||
1530 Name == "strtok_r") {
1531 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1534 setDoesNotCapture(F, 2);
1535 } else if (Name == "scanf" ||
1537 Name == "setvbuf") {
1538 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1541 setDoesNotCapture(F, 1);
1542 } else if (Name == "strdup" ||
1543 Name == "strndup") {
1544 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1545 !FTy->getParamType(0)->isPointerTy())
1548 setDoesNotAlias(F, 0);
1549 setDoesNotCapture(F, 1);
1550 } else if (Name == "stat" ||
1552 Name == "sprintf" ||
1553 Name == "statvfs") {
1554 if (FTy->getNumParams() < 2 ||
1555 !FTy->getParamType(0)->isPointerTy() ||
1556 !FTy->getParamType(1)->isPointerTy())
1559 setDoesNotCapture(F, 1);
1560 setDoesNotCapture(F, 2);
1561 } else if (Name == "snprintf") {
1562 if (FTy->getNumParams() != 3 ||
1563 !FTy->getParamType(0)->isPointerTy() ||
1564 !FTy->getParamType(2)->isPointerTy())
1567 setDoesNotCapture(F, 1);
1568 setDoesNotCapture(F, 3);
1569 } else if (Name == "setitimer") {
1570 if (FTy->getNumParams() != 3 ||
1571 !FTy->getParamType(1)->isPointerTy() ||
1572 !FTy->getParamType(2)->isPointerTy())
1575 setDoesNotCapture(F, 2);
1576 setDoesNotCapture(F, 3);
1577 } else if (Name == "system") {
1578 if (FTy->getNumParams() != 1 ||
1579 !FTy->getParamType(0)->isPointerTy())
1581 // May throw; "system" is a valid pthread cancellation point.
1582 setDoesNotCapture(F, 1);
1586 if (Name == "malloc") {
1587 if (FTy->getNumParams() != 1 ||
1588 !FTy->getReturnType()->isPointerTy())
1591 setDoesNotAlias(F, 0);
1592 } else if (Name == "memcmp") {
1593 if (FTy->getNumParams() != 3 ||
1594 !FTy->getParamType(0)->isPointerTy() ||
1595 !FTy->getParamType(1)->isPointerTy())
1597 setOnlyReadsMemory(F);
1599 setDoesNotCapture(F, 1);
1600 setDoesNotCapture(F, 2);
1601 } else if (Name == "memchr" ||
1602 Name == "memrchr") {
1603 if (FTy->getNumParams() != 3)
1605 setOnlyReadsMemory(F);
1607 } else if (Name == "modf" ||
1611 Name == "memccpy" ||
1612 Name == "memmove") {
1613 if (FTy->getNumParams() < 2 ||
1614 !FTy->getParamType(1)->isPointerTy())
1617 setDoesNotCapture(F, 2);
1618 } else if (Name == "memalign") {
1619 if (!FTy->getReturnType()->isPointerTy())
1621 setDoesNotAlias(F, 0);
1622 } else if (Name == "mkdir" ||
1624 if (FTy->getNumParams() == 0 ||
1625 !FTy->getParamType(0)->isPointerTy())
1628 setDoesNotCapture(F, 1);
1632 if (Name == "realloc") {
1633 if (FTy->getNumParams() != 2 ||
1634 !FTy->getParamType(0)->isPointerTy() ||
1635 !FTy->getReturnType()->isPointerTy())
1638 setDoesNotAlias(F, 0);
1639 setDoesNotCapture(F, 1);
1640 } else if (Name == "read") {
1641 if (FTy->getNumParams() != 3 ||
1642 !FTy->getParamType(1)->isPointerTy())
1644 // May throw; "read" is a valid pthread cancellation point.
1645 setDoesNotCapture(F, 2);
1646 } else if (Name == "rmdir" ||
1649 Name == "realpath") {
1650 if (FTy->getNumParams() < 1 ||
1651 !FTy->getParamType(0)->isPointerTy())
1654 setDoesNotCapture(F, 1);
1655 } else if (Name == "rename" ||
1656 Name == "readlink") {
1657 if (FTy->getNumParams() < 2 ||
1658 !FTy->getParamType(0)->isPointerTy() ||
1659 !FTy->getParamType(1)->isPointerTy())
1662 setDoesNotCapture(F, 1);
1663 setDoesNotCapture(F, 2);
1667 if (Name == "write") {
1668 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1670 // May throw; "write" is a valid pthread cancellation point.
1671 setDoesNotCapture(F, 2);
1675 if (Name == "bcopy") {
1676 if (FTy->getNumParams() != 3 ||
1677 !FTy->getParamType(0)->isPointerTy() ||
1678 !FTy->getParamType(1)->isPointerTy())
1681 setDoesNotCapture(F, 1);
1682 setDoesNotCapture(F, 2);
1683 } else if (Name == "bcmp") {
1684 if (FTy->getNumParams() != 3 ||
1685 !FTy->getParamType(0)->isPointerTy() ||
1686 !FTy->getParamType(1)->isPointerTy())
1689 setOnlyReadsMemory(F);
1690 setDoesNotCapture(F, 1);
1691 setDoesNotCapture(F, 2);
1692 } else if (Name == "bzero") {
1693 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1696 setDoesNotCapture(F, 1);
1700 if (Name == "calloc") {
1701 if (FTy->getNumParams() != 2 ||
1702 !FTy->getReturnType()->isPointerTy())
1705 setDoesNotAlias(F, 0);
1706 } else if (Name == "chmod" ||
1708 Name == "ctermid" ||
1709 Name == "clearerr" ||
1710 Name == "closedir") {
1711 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1714 setDoesNotCapture(F, 1);
1718 if (Name == "atoi" ||
1722 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1725 setOnlyReadsMemory(F);
1726 setDoesNotCapture(F, 1);
1727 } else if (Name == "access") {
1728 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1731 setDoesNotCapture(F, 1);
1735 if (Name == "fopen") {
1736 if (FTy->getNumParams() != 2 ||
1737 !FTy->getReturnType()->isPointerTy() ||
1738 !FTy->getParamType(0)->isPointerTy() ||
1739 !FTy->getParamType(1)->isPointerTy())
1742 setDoesNotAlias(F, 0);
1743 setDoesNotCapture(F, 1);
1744 setDoesNotCapture(F, 2);
1745 } else if (Name == "fdopen") {
1746 if (FTy->getNumParams() != 2 ||
1747 !FTy->getReturnType()->isPointerTy() ||
1748 !FTy->getParamType(1)->isPointerTy())
1751 setDoesNotAlias(F, 0);
1752 setDoesNotCapture(F, 2);
1753 } else if (Name == "feof" ||
1763 Name == "fsetpos" ||
1764 Name == "flockfile" ||
1765 Name == "funlockfile" ||
1766 Name == "ftrylockfile") {
1767 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1770 setDoesNotCapture(F, 1);
1771 } else if (Name == "ferror") {
1772 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1775 setDoesNotCapture(F, 1);
1776 setOnlyReadsMemory(F);
1777 } else if (Name == "fputc" ||
1782 Name == "fstatvfs") {
1783 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1786 setDoesNotCapture(F, 2);
1787 } else if (Name == "fgets") {
1788 if (FTy->getNumParams() != 3 ||
1789 !FTy->getParamType(0)->isPointerTy() ||
1790 !FTy->getParamType(2)->isPointerTy())
1793 setDoesNotCapture(F, 3);
1794 } else if (Name == "fread" ||
1796 if (FTy->getNumParams() != 4 ||
1797 !FTy->getParamType(0)->isPointerTy() ||
1798 !FTy->getParamType(3)->isPointerTy())
1801 setDoesNotCapture(F, 1);
1802 setDoesNotCapture(F, 4);
1803 } else if (Name == "fputs" ||
1805 Name == "fprintf" ||
1806 Name == "fgetpos") {
1807 if (FTy->getNumParams() < 2 ||
1808 !FTy->getParamType(0)->isPointerTy() ||
1809 !FTy->getParamType(1)->isPointerTy())
1812 setDoesNotCapture(F, 1);
1813 setDoesNotCapture(F, 2);
1817 if (Name == "getc" ||
1818 Name == "getlogin_r" ||
1819 Name == "getc_unlocked") {
1820 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1823 setDoesNotCapture(F, 1);
1824 } else if (Name == "getenv") {
1825 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1828 setOnlyReadsMemory(F);
1829 setDoesNotCapture(F, 1);
1830 } else if (Name == "gets" ||
1831 Name == "getchar") {
1833 } else if (Name == "getitimer") {
1834 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1837 setDoesNotCapture(F, 2);
1838 } else if (Name == "getpwnam") {
1839 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1842 setDoesNotCapture(F, 1);
1846 if (Name == "ungetc") {
1847 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1850 setDoesNotCapture(F, 2);
1851 } else if (Name == "uname" ||
1853 Name == "unsetenv") {
1854 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1857 setDoesNotCapture(F, 1);
1858 } else if (Name == "utime" ||
1860 if (FTy->getNumParams() != 2 ||
1861 !FTy->getParamType(0)->isPointerTy() ||
1862 !FTy->getParamType(1)->isPointerTy())
1865 setDoesNotCapture(F, 1);
1866 setDoesNotCapture(F, 2);
1870 if (Name == "putc") {
1871 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1874 setDoesNotCapture(F, 2);
1875 } else if (Name == "puts" ||
1878 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1881 setDoesNotCapture(F, 1);
1882 } else if (Name == "pread" ||
1884 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1886 // May throw; these are valid pthread cancellation points.
1887 setDoesNotCapture(F, 2);
1888 } else if (Name == "putchar") {
1890 } else if (Name == "popen") {
1891 if (FTy->getNumParams() != 2 ||
1892 !FTy->getReturnType()->isPointerTy() ||
1893 !FTy->getParamType(0)->isPointerTy() ||
1894 !FTy->getParamType(1)->isPointerTy())
1897 setDoesNotAlias(F, 0);
1898 setDoesNotCapture(F, 1);
1899 setDoesNotCapture(F, 2);
1900 } else if (Name == "pclose") {
1901 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1904 setDoesNotCapture(F, 1);
1908 if (Name == "vscanf") {
1909 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1912 setDoesNotCapture(F, 1);
1913 } else if (Name == "vsscanf" ||
1914 Name == "vfscanf") {
1915 if (FTy->getNumParams() != 3 ||
1916 !FTy->getParamType(1)->isPointerTy() ||
1917 !FTy->getParamType(2)->isPointerTy())
1920 setDoesNotCapture(F, 1);
1921 setDoesNotCapture(F, 2);
1922 } else if (Name == "valloc") {
1923 if (!FTy->getReturnType()->isPointerTy())
1926 setDoesNotAlias(F, 0);
1927 } else if (Name == "vprintf") {
1928 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1931 setDoesNotCapture(F, 1);
1932 } else if (Name == "vfprintf" ||
1933 Name == "vsprintf") {
1934 if (FTy->getNumParams() != 3 ||
1935 !FTy->getParamType(0)->isPointerTy() ||
1936 !FTy->getParamType(1)->isPointerTy())
1939 setDoesNotCapture(F, 1);
1940 setDoesNotCapture(F, 2);
1941 } else if (Name == "vsnprintf") {
1942 if (FTy->getNumParams() != 4 ||
1943 !FTy->getParamType(0)->isPointerTy() ||
1944 !FTy->getParamType(2)->isPointerTy())
1947 setDoesNotCapture(F, 1);
1948 setDoesNotCapture(F, 3);
1952 if (Name == "open") {
1953 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1955 // May throw; "open" is a valid pthread cancellation point.
1956 setDoesNotCapture(F, 1);
1957 } else if (Name == "opendir") {
1958 if (FTy->getNumParams() != 1 ||
1959 !FTy->getReturnType()->isPointerTy() ||
1960 !FTy->getParamType(0)->isPointerTy())
1963 setDoesNotAlias(F, 0);
1964 setDoesNotCapture(F, 1);
1968 if (Name == "tmpfile") {
1969 if (!FTy->getReturnType()->isPointerTy())
1972 setDoesNotAlias(F, 0);
1973 } else if (Name == "times") {
1974 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1977 setDoesNotCapture(F, 1);
1981 if (Name == "htonl" ||
1984 setDoesNotAccessMemory(F);
1988 if (Name == "ntohl" ||
1991 setDoesNotAccessMemory(F);
1995 if (Name == "lstat") {
1996 if (FTy->getNumParams() != 2 ||
1997 !FTy->getParamType(0)->isPointerTy() ||
1998 !FTy->getParamType(1)->isPointerTy())
2001 setDoesNotCapture(F, 1);
2002 setDoesNotCapture(F, 2);
2003 } else if (Name == "lchown") {
2004 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2007 setDoesNotCapture(F, 1);
2011 if (Name == "qsort") {
2012 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2014 // May throw; places call through function pointer.
2015 setDoesNotCapture(F, 4);
2019 if (Name == "__strdup" ||
2020 Name == "__strndup") {
2021 if (FTy->getNumParams() < 1 ||
2022 !FTy->getReturnType()->isPointerTy() ||
2023 !FTy->getParamType(0)->isPointerTy())
2026 setDoesNotAlias(F, 0);
2027 setDoesNotCapture(F, 1);
2028 } else if (Name == "__strtok_r") {
2029 if (FTy->getNumParams() != 3 ||
2030 !FTy->getParamType(1)->isPointerTy())
2033 setDoesNotCapture(F, 2);
2034 } else if (Name == "_IO_getc") {
2035 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2038 setDoesNotCapture(F, 1);
2039 } else if (Name == "_IO_putc") {
2040 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2043 setDoesNotCapture(F, 2);
2047 if (Name == "\1__isoc99_scanf") {
2048 if (FTy->getNumParams() < 1 ||
2049 !FTy->getParamType(0)->isPointerTy())
2052 setDoesNotCapture(F, 1);
2053 } else if (Name == "\1stat64" ||
2054 Name == "\1lstat64" ||
2055 Name == "\1statvfs64" ||
2056 Name == "\1__isoc99_sscanf") {
2057 if (FTy->getNumParams() < 1 ||
2058 !FTy->getParamType(0)->isPointerTy() ||
2059 !FTy->getParamType(1)->isPointerTy())
2062 setDoesNotCapture(F, 1);
2063 setDoesNotCapture(F, 2);
2064 } else if (Name == "\1fopen64") {
2065 if (FTy->getNumParams() != 2 ||
2066 !FTy->getReturnType()->isPointerTy() ||
2067 !FTy->getParamType(0)->isPointerTy() ||
2068 !FTy->getParamType(1)->isPointerTy())
2071 setDoesNotAlias(F, 0);
2072 setDoesNotCapture(F, 1);
2073 setDoesNotCapture(F, 2);
2074 } else if (Name == "\1fseeko64" ||
2075 Name == "\1ftello64") {
2076 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2079 setDoesNotCapture(F, 1);
2080 } else if (Name == "\1tmpfile64") {
2081 if (!FTy->getReturnType()->isPointerTy())
2084 setDoesNotAlias(F, 0);
2085 } else if (Name == "\1fstat64" ||
2086 Name == "\1fstatvfs64") {
2087 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2090 setDoesNotCapture(F, 2);
2091 } else if (Name == "\1open64") {
2092 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2094 // May throw; "open" is a valid pthread cancellation point.
2095 setDoesNotCapture(F, 1);
2101 /// doInitialization - Add attributes to well-known functions.
2103 bool SimplifyLibCalls::doInitialization(Module &M) {
2105 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2107 if (F.isDeclaration() && F.hasName())
2108 inferPrototypeAttributes(F);
2114 // Additional cases that we need to add to this file:
2117 // * cbrt(expN(X)) -> expN(x/3)
2118 // * cbrt(sqrt(x)) -> pow(x,1/6)
2119 // * cbrt(sqrt(x)) -> pow(x,1/9)
2122 // * exp(log(x)) -> x
2125 // * log(exp(x)) -> x
2126 // * log(x**y) -> y*log(x)
2127 // * log(exp(y)) -> y*log(e)
2128 // * log(exp2(y)) -> y*log(2)
2129 // * log(exp10(y)) -> y*log(10)
2130 // * log(sqrt(x)) -> 0.5*log(x)
2131 // * log(pow(x,y)) -> y*log(x)
2133 // lround, lroundf, lroundl:
2134 // * lround(cnst) -> cnst'
2137 // * pow(exp(x),y) -> exp(x*y)
2138 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2139 // * pow(pow(x,y),z)-> pow(x,y*z)
2141 // round, roundf, roundl:
2142 // * round(cnst) -> cnst'
2145 // * signbit(cnst) -> cnst'
2146 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2148 // sqrt, sqrtf, sqrtl:
2149 // * sqrt(expN(x)) -> expN(x*0.5)
2150 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2151 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2154 // * strchr(p, 0) -> strlen(p)
2156 // * tan(atan(x)) -> x
2158 // trunc, truncf, truncl:
2159 // * trunc(cnst) -> cnst'