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/Target/TargetLibraryInfo.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
48 class LibCallOptimization {
52 const TargetLibraryInfo *TLI;
55 LibCallOptimization() { }
56 virtual ~LibCallOptimization() {}
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
63 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
66 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
68 Caller = CI->getParent()->getParent();
71 if (CI->getCalledFunction())
72 Context = &CI->getCalledFunction()->getContext();
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
78 return CallOptimizer(CI->getCalledFunction(), CI, B);
81 } // End anonymous namespace.
84 //===----------------------------------------------------------------------===//
86 //===----------------------------------------------------------------------===//
88 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
89 /// value is equal or not-equal to zero.
90 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
98 // Unknown instruction.
104 static bool CallHasFloatingPointArgument(const CallInst *CI) {
105 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
107 if ((*it)->getType()->isFloatingPointTy())
113 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
114 /// comparisons with With.
115 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
116 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
118 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
119 if (IC->isEquality() && IC->getOperand(1) == With)
121 // Unknown instruction.
127 //===----------------------------------------------------------------------===//
128 // String and Memory LibCall Optimizations
129 //===----------------------------------------------------------------------===//
131 //===---------------------------------------===//
132 // 'strcat' Optimizations
134 struct StrCatOpt : public LibCallOptimization {
135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
136 // Verify the "strcat" function prototype.
137 FunctionType *FT = Callee->getFunctionType();
138 if (FT->getNumParams() != 2 ||
139 FT->getReturnType() != B.getInt8PtrTy() ||
140 FT->getParamType(0) != FT->getReturnType() ||
141 FT->getParamType(1) != FT->getReturnType())
144 // Extract some information from the instruction
145 Value *Dst = CI->getArgOperand(0);
146 Value *Src = CI->getArgOperand(1);
148 // See if we can get the length of the input string.
149 uint64_t Len = GetStringLength(Src);
150 if (Len == 0) return 0;
151 --Len; // Unbias length.
153 // Handle the simple, do-nothing case: strcat(x, "") -> x
157 // These optimizations require TargetData.
160 EmitStrLenMemCpy(Src, Dst, Len, B);
164 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
165 // We need to find the end of the destination string. That's where the
166 // memory is to be moved to. We just generate a call to strlen.
167 Value *DstLen = EmitStrLen(Dst, B, TD);
169 // Now that we have the destination's length, we must index into the
170 // destination's pointer to get the actual memcpy destination (end of
171 // the string .. we're concatenating).
172 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
174 // We have enough information to now generate the memcpy call to do the
175 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
176 B.CreateMemCpy(CpyDst, Src,
177 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
181 //===---------------------------------------===//
182 // 'strncat' Optimizations
184 struct StrNCatOpt : public StrCatOpt {
185 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
186 // Verify the "strncat" function prototype.
187 FunctionType *FT = Callee->getFunctionType();
188 if (FT->getNumParams() != 3 ||
189 FT->getReturnType() != B.getInt8PtrTy() ||
190 FT->getParamType(0) != FT->getReturnType() ||
191 FT->getParamType(1) != FT->getReturnType() ||
192 !FT->getParamType(2)->isIntegerTy())
195 // Extract some information from the instruction
196 Value *Dst = CI->getArgOperand(0);
197 Value *Src = CI->getArgOperand(1);
200 // We don't do anything if length is not constant
201 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
202 Len = LengthArg->getZExtValue();
206 // See if we can get the length of the input string.
207 uint64_t SrcLen = GetStringLength(Src);
208 if (SrcLen == 0) return 0;
209 --SrcLen; // Unbias length.
211 // Handle the simple, do-nothing cases:
212 // strncat(x, "", c) -> x
213 // strncat(x, c, 0) -> x
214 if (SrcLen == 0 || Len == 0) return Dst;
216 // These optimizations require TargetData.
219 // We don't optimize this case
220 if (Len < SrcLen) return 0;
222 // strncat(x, s, c) -> strcat(x, s)
223 // s is constant so the strcat can be optimized further
224 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
229 //===---------------------------------------===//
230 // 'strchr' Optimizations
232 struct StrChrOpt : public LibCallOptimization {
233 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
234 // Verify the "strchr" function prototype.
235 FunctionType *FT = Callee->getFunctionType();
236 if (FT->getNumParams() != 2 ||
237 FT->getReturnType() != B.getInt8PtrTy() ||
238 FT->getParamType(0) != FT->getReturnType() ||
239 !FT->getParamType(1)->isIntegerTy(32))
242 Value *SrcStr = CI->getArgOperand(0);
244 // If the second operand is non-constant, see if we can compute the length
245 // of the input string and turn this into memchr.
246 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
248 // These optimizations require TargetData.
251 uint64_t Len = GetStringLength(SrcStr);
252 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
255 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
256 ConstantInt::get(TD->getIntPtrType(*Context), Len),
260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
263 if (!GetConstantStringInfo(SrcStr, Str))
266 // strchr can find the nul character.
269 // Compute the offset.
270 size_t I = Str.find(CharC->getSExtValue());
271 if (I == std::string::npos) // Didn't find the char. strchr returns null.
272 return Constant::getNullValue(CI->getType());
274 // strchr(s+n,c) -> gep(s+n+i,c)
275 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
279 //===---------------------------------------===//
280 // 'strrchr' Optimizations
282 struct StrRChrOpt : public LibCallOptimization {
283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
284 // Verify the "strrchr" function prototype.
285 FunctionType *FT = Callee->getFunctionType();
286 if (FT->getNumParams() != 2 ||
287 FT->getReturnType() != B.getInt8PtrTy() ||
288 FT->getParamType(0) != FT->getReturnType() ||
289 !FT->getParamType(1)->isIntegerTy(32))
292 Value *SrcStr = CI->getArgOperand(0);
293 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
295 // Cannot fold anything if we're not looking for a constant.
300 if (!GetConstantStringInfo(SrcStr, Str)) {
301 // strrchr(s, 0) -> strchr(s, 0)
302 if (TD && CharC->isZero())
303 return EmitStrChr(SrcStr, '\0', B, TD);
307 // strrchr can find the nul character.
310 // Compute the offset.
311 size_t I = Str.rfind(CharC->getSExtValue());
312 if (I == std::string::npos) // Didn't find the char. Return null.
313 return Constant::getNullValue(CI->getType());
315 // strrchr(s+n,c) -> gep(s+n+i,c)
316 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
320 //===---------------------------------------===//
321 // 'strcmp' Optimizations
323 struct StrCmpOpt : public LibCallOptimization {
324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
325 // Verify the "strcmp" function prototype.
326 FunctionType *FT = Callee->getFunctionType();
327 if (FT->getNumParams() != 2 ||
328 !FT->getReturnType()->isIntegerTy(32) ||
329 FT->getParamType(0) != FT->getParamType(1) ||
330 FT->getParamType(0) != B.getInt8PtrTy())
333 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
334 if (Str1P == Str2P) // strcmp(x,x) -> 0
335 return ConstantInt::get(CI->getType(), 0);
337 std::string Str1, Str2;
338 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
339 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
341 // strcmp(x, y) -> cnst (if both x and y are constant strings)
342 if (HasStr1 && HasStr2)
343 return ConstantInt::get(CI->getType(),
344 StringRef(Str1).compare(Str2));
346 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
347 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
350 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
351 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
353 // strcmp(P, "x") -> memcmp(P, "x", 2)
354 uint64_t Len1 = GetStringLength(Str1P);
355 uint64_t Len2 = GetStringLength(Str2P);
357 // These optimizations require TargetData.
360 return EmitMemCmp(Str1P, Str2P,
361 ConstantInt::get(TD->getIntPtrType(*Context),
362 std::min(Len1, Len2)), B, TD);
369 //===---------------------------------------===//
370 // 'strncmp' Optimizations
372 struct StrNCmpOpt : public LibCallOptimization {
373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
374 // Verify the "strncmp" function prototype.
375 FunctionType *FT = Callee->getFunctionType();
376 if (FT->getNumParams() != 3 ||
377 !FT->getReturnType()->isIntegerTy(32) ||
378 FT->getParamType(0) != FT->getParamType(1) ||
379 FT->getParamType(0) != B.getInt8PtrTy() ||
380 !FT->getParamType(2)->isIntegerTy())
383 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
384 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
385 return ConstantInt::get(CI->getType(), 0);
387 // Get the length argument if it is constant.
389 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
390 Length = LengthArg->getZExtValue();
394 if (Length == 0) // strncmp(x,y,0) -> 0
395 return ConstantInt::get(CI->getType(), 0);
397 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
398 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
400 std::string Str1, Str2;
401 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
402 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
404 // strncmp(x, y) -> cnst (if both x and y are constant strings)
405 if (HasStr1 && HasStr2) {
406 StringRef SubStr1 = StringRef(Str1).substr(0, Length);
407 StringRef SubStr2 = StringRef(Str2).substr(0, Length);
408 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
411 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
412 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
415 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
416 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
423 //===---------------------------------------===//
424 // 'strcpy' Optimizations
426 struct StrCpyOpt : public LibCallOptimization {
427 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
429 StrCpyOpt(bool c) : OptChkCall(c) {}
431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
432 // Verify the "strcpy" function prototype.
433 unsigned NumParams = OptChkCall ? 3 : 2;
434 FunctionType *FT = Callee->getFunctionType();
435 if (FT->getNumParams() != NumParams ||
436 FT->getReturnType() != FT->getParamType(0) ||
437 FT->getParamType(0) != FT->getParamType(1) ||
438 FT->getParamType(0) != B.getInt8PtrTy())
441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442 if (Dst == Src) // strcpy(x,x) -> x
445 // These optimizations require TargetData.
448 // See if we can get the length of the input string.
449 uint64_t Len = GetStringLength(Src);
450 if (Len == 0) return 0;
452 // We have enough information to now generate the memcpy call to do the
453 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
455 EmitMemCpyChk(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len),
457 CI->getArgOperand(2), B, TD);
459 B.CreateMemCpy(Dst, Src,
460 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
465 //===---------------------------------------===//
466 // 'strncpy' Optimizations
468 struct StrNCpyOpt : public LibCallOptimization {
469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
470 FunctionType *FT = Callee->getFunctionType();
471 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
472 FT->getParamType(0) != FT->getParamType(1) ||
473 FT->getParamType(0) != B.getInt8PtrTy() ||
474 !FT->getParamType(2)->isIntegerTy())
477 Value *Dst = CI->getArgOperand(0);
478 Value *Src = CI->getArgOperand(1);
479 Value *LenOp = CI->getArgOperand(2);
481 // See if we can get the length of the input string.
482 uint64_t SrcLen = GetStringLength(Src);
483 if (SrcLen == 0) return 0;
487 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
488 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
493 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
494 Len = LengthArg->getZExtValue();
498 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
500 // These optimizations require TargetData.
503 // Let strncpy handle the zero padding
504 if (Len > SrcLen+1) return 0;
506 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
507 B.CreateMemCpy(Dst, Src,
508 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
514 //===---------------------------------------===//
515 // 'strlen' Optimizations
517 struct StrLenOpt : public LibCallOptimization {
518 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
519 FunctionType *FT = Callee->getFunctionType();
520 if (FT->getNumParams() != 1 ||
521 FT->getParamType(0) != B.getInt8PtrTy() ||
522 !FT->getReturnType()->isIntegerTy())
525 Value *Src = CI->getArgOperand(0);
527 // Constant folding: strlen("xyz") -> 3
528 if (uint64_t Len = GetStringLength(Src))
529 return ConstantInt::get(CI->getType(), Len-1);
531 // strlen(x) != 0 --> *x != 0
532 // strlen(x) == 0 --> *x == 0
533 if (IsOnlyUsedInZeroEqualityComparison(CI))
534 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
540 //===---------------------------------------===//
541 // 'strpbrk' Optimizations
543 struct StrPBrkOpt : public LibCallOptimization {
544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
545 FunctionType *FT = Callee->getFunctionType();
546 if (FT->getNumParams() != 2 ||
547 FT->getParamType(0) != B.getInt8PtrTy() ||
548 FT->getParamType(1) != FT->getParamType(0) ||
549 FT->getReturnType() != FT->getParamType(0))
553 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
554 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
556 // strpbrk(s, "") -> NULL
557 // strpbrk("", s) -> NULL
558 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
559 return Constant::getNullValue(CI->getType());
562 if (HasS1 && HasS2) {
563 size_t I = S1.find_first_of(S2);
564 if (I == std::string::npos) // No match.
565 return Constant::getNullValue(CI->getType());
567 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
570 // strpbrk(s, "a") -> strchr(s, 'a')
571 if (TD && HasS2 && S2.size() == 1)
572 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
578 //===---------------------------------------===//
579 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
581 struct StrToOpt : public LibCallOptimization {
582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
583 FunctionType *FT = Callee->getFunctionType();
584 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
585 !FT->getParamType(0)->isPointerTy() ||
586 !FT->getParamType(1)->isPointerTy())
589 Value *EndPtr = CI->getArgOperand(1);
590 if (isa<ConstantPointerNull>(EndPtr)) {
591 // With a null EndPtr, this function won't capture the main argument.
592 // It would be readonly too, except that it still may write to errno.
593 CI->addAttribute(1, Attribute::NoCapture);
600 //===---------------------------------------===//
601 // 'strspn' Optimizations
603 struct StrSpnOpt : public LibCallOptimization {
604 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
605 FunctionType *FT = Callee->getFunctionType();
606 if (FT->getNumParams() != 2 ||
607 FT->getParamType(0) != B.getInt8PtrTy() ||
608 FT->getParamType(1) != FT->getParamType(0) ||
609 !FT->getReturnType()->isIntegerTy())
613 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
614 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
616 // strspn(s, "") -> 0
617 // strspn("", s) -> 0
618 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
619 return Constant::getNullValue(CI->getType());
623 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
629 //===---------------------------------------===//
630 // 'strcspn' Optimizations
632 struct StrCSpnOpt : public LibCallOptimization {
633 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
634 FunctionType *FT = Callee->getFunctionType();
635 if (FT->getNumParams() != 2 ||
636 FT->getParamType(0) != B.getInt8PtrTy() ||
637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
642 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
645 // strcspn("", s) -> 0
646 if (HasS1 && S1.empty())
647 return Constant::getNullValue(CI->getType());
651 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
653 // strcspn(s, "") -> strlen(s)
654 if (TD && HasS2 && S2.empty())
655 return EmitStrLen(CI->getArgOperand(0), B, TD);
661 //===---------------------------------------===//
662 // 'strstr' Optimizations
664 struct StrStrOpt : public LibCallOptimization {
665 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
666 FunctionType *FT = Callee->getFunctionType();
667 if (FT->getNumParams() != 2 ||
668 !FT->getParamType(0)->isPointerTy() ||
669 !FT->getParamType(1)->isPointerTy() ||
670 !FT->getReturnType()->isPointerTy())
673 // fold strstr(x, x) -> x.
674 if (CI->getArgOperand(0) == CI->getArgOperand(1))
675 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
677 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
678 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
679 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
680 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
682 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
684 ICmpInst *Old = cast<ICmpInst>(*UI++);
685 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
686 ConstantInt::getNullValue(StrNCmp->getType()),
688 Old->replaceAllUsesWith(Cmp);
689 Old->eraseFromParent();
694 // See if either input string is a constant string.
695 std::string SearchStr, ToFindStr;
696 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
697 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
699 // fold strstr(x, "") -> x.
700 if (HasStr2 && ToFindStr.empty())
701 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
703 // If both strings are known, constant fold it.
704 if (HasStr1 && HasStr2) {
705 std::string::size_type Offset = SearchStr.find(ToFindStr);
707 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
708 return Constant::getNullValue(CI->getType());
710 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
711 Value *Result = CastToCStr(CI->getArgOperand(0), B);
712 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
713 return B.CreateBitCast(Result, CI->getType());
716 // fold strstr(x, "y") -> strchr(x, 'y').
717 if (HasStr2 && ToFindStr.size() == 1)
718 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
719 ToFindStr[0], B, TD), CI->getType());
725 //===---------------------------------------===//
726 // 'memcmp' Optimizations
728 struct MemCmpOpt : public LibCallOptimization {
729 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
730 FunctionType *FT = Callee->getFunctionType();
731 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
732 !FT->getParamType(1)->isPointerTy() ||
733 !FT->getReturnType()->isIntegerTy(32))
736 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
738 if (LHS == RHS) // memcmp(s,s,x) -> 0
739 return Constant::getNullValue(CI->getType());
741 // Make sure we have a constant length.
742 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
744 uint64_t Len = LenC->getZExtValue();
746 if (Len == 0) // memcmp(s1,s2,0) -> 0
747 return Constant::getNullValue(CI->getType());
749 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
751 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
752 CI->getType(), "lhsv");
753 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
754 CI->getType(), "rhsv");
755 return B.CreateSub(LHSV, RHSV, "chardiff");
758 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
759 std::string LHSStr, RHSStr;
760 if (GetConstantStringInfo(LHS, LHSStr) &&
761 GetConstantStringInfo(RHS, RHSStr)) {
762 // Make sure we're not reading out-of-bounds memory.
763 if (Len > LHSStr.length() || Len > RHSStr.length())
765 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
766 return ConstantInt::get(CI->getType(), Ret);
773 //===---------------------------------------===//
774 // 'memcpy' Optimizations
776 struct MemCpyOpt : public LibCallOptimization {
777 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
778 // These optimizations require TargetData.
781 FunctionType *FT = Callee->getFunctionType();
782 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
783 !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
785 FT->getParamType(2) != TD->getIntPtrType(*Context))
788 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
789 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
790 CI->getArgOperand(2), 1);
791 return CI->getArgOperand(0);
795 //===---------------------------------------===//
796 // 'memmove' Optimizations
798 struct MemMoveOpt : public LibCallOptimization {
799 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
800 // These optimizations require TargetData.
803 FunctionType *FT = Callee->getFunctionType();
804 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
805 !FT->getParamType(0)->isPointerTy() ||
806 !FT->getParamType(1)->isPointerTy() ||
807 FT->getParamType(2) != TD->getIntPtrType(*Context))
810 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
811 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
812 CI->getArgOperand(2), 1);
813 return CI->getArgOperand(0);
817 //===---------------------------------------===//
818 // 'memset' Optimizations
820 struct MemSetOpt : public LibCallOptimization {
821 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
822 // These optimizations require TargetData.
825 FunctionType *FT = Callee->getFunctionType();
826 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
827 !FT->getParamType(0)->isPointerTy() ||
828 !FT->getParamType(1)->isIntegerTy() ||
829 FT->getParamType(2) != TD->getIntPtrType(*Context))
832 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
833 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
834 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
835 return CI->getArgOperand(0);
839 //===----------------------------------------------------------------------===//
840 // Math Library Optimizations
841 //===----------------------------------------------------------------------===//
843 //===---------------------------------------===//
844 // 'cos*' Optimizations
846 struct CosOpt : public LibCallOptimization {
847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
848 FunctionType *FT = Callee->getFunctionType();
849 // Just make sure this has 1 argument of FP type, which matches the
851 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
852 !FT->getParamType(0)->isFloatingPointTy())
856 Value *Op1 = CI->getArgOperand(0);
857 if (BinaryOperator::isFNeg(Op1)) {
858 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
859 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
865 //===---------------------------------------===//
866 // 'pow*' Optimizations
868 struct PowOpt : public LibCallOptimization {
869 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
870 FunctionType *FT = Callee->getFunctionType();
871 // Just make sure this has 2 arguments of the same FP type, which match the
873 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
874 FT->getParamType(0) != FT->getParamType(1) ||
875 !FT->getParamType(0)->isFloatingPointTy())
878 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
879 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
880 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
882 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
883 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
886 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
887 if (Op2C == 0) return 0;
889 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
890 return ConstantFP::get(CI->getType(), 1.0);
892 if (Op2C->isExactlyValue(0.5)) {
893 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
894 // This is faster than calling pow, and still handles negative zero
895 // and negative infinity correctly.
896 // TODO: In fast-math mode, this could be just sqrt(x).
897 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
898 Value *Inf = ConstantFP::getInfinity(CI->getType());
899 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
900 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
901 Callee->getAttributes());
902 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
903 Callee->getAttributes());
904 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
905 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
909 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
911 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
912 return B.CreateFMul(Op1, Op1, "pow2");
913 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
914 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
920 //===---------------------------------------===//
921 // 'exp2' Optimizations
923 struct Exp2Opt : public LibCallOptimization {
924 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
925 FunctionType *FT = Callee->getFunctionType();
926 // Just make sure this has 1 argument of FP type, which matches the
928 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
929 !FT->getParamType(0)->isFloatingPointTy())
932 Value *Op = CI->getArgOperand(0);
933 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
934 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
936 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
937 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
938 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
939 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
940 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
941 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
946 if (Op->getType()->isFloatTy())
948 else if (Op->getType()->isDoubleTy())
953 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
954 if (!Op->getType()->isFloatTy())
955 One = ConstantExpr::getFPExtend(One, Op->getType());
957 Module *M = Caller->getParent();
958 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
960 B.getInt32Ty(), NULL);
961 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
962 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
963 CI->setCallingConv(F->getCallingConv());
971 //===---------------------------------------===//
972 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
974 struct UnaryDoubleFPOpt : public LibCallOptimization {
975 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
976 FunctionType *FT = Callee->getFunctionType();
977 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
978 !FT->getParamType(0)->isDoubleTy())
981 // If this is something like 'floor((double)floatval)', convert to floorf.
982 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
983 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
986 // floor((double)floatval) -> (double)floorf(floatval)
987 Value *V = Cast->getOperand(0);
988 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
989 return B.CreateFPExt(V, B.getDoubleTy());
993 //===----------------------------------------------------------------------===//
994 // Integer Optimizations
995 //===----------------------------------------------------------------------===//
997 //===---------------------------------------===//
998 // 'ffs*' Optimizations
1000 struct FFSOpt : public LibCallOptimization {
1001 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1002 FunctionType *FT = Callee->getFunctionType();
1003 // Just make sure this has 2 arguments of the same FP type, which match the
1005 if (FT->getNumParams() != 1 ||
1006 !FT->getReturnType()->isIntegerTy(32) ||
1007 !FT->getParamType(0)->isIntegerTy())
1010 Value *Op = CI->getArgOperand(0);
1013 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1014 if (CI->getValue() == 0) // ffs(0) -> 0.
1015 return Constant::getNullValue(CI->getType());
1016 // ffs(c) -> cttz(c)+1
1017 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1020 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1021 Type *ArgType = Op->getType();
1022 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1023 Intrinsic::cttz, ArgType);
1024 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1025 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1026 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1028 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1029 return B.CreateSelect(Cond, V, B.getInt32(0));
1033 //===---------------------------------------===//
1034 // 'isdigit' Optimizations
1036 struct IsDigitOpt : public LibCallOptimization {
1037 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1038 FunctionType *FT = Callee->getFunctionType();
1039 // We require integer(i32)
1040 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1041 !FT->getParamType(0)->isIntegerTy(32))
1044 // isdigit(c) -> (c-'0') <u 10
1045 Value *Op = CI->getArgOperand(0);
1046 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1047 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1048 return B.CreateZExt(Op, CI->getType());
1052 //===---------------------------------------===//
1053 // 'isascii' Optimizations
1055 struct IsAsciiOpt : public LibCallOptimization {
1056 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1057 FunctionType *FT = Callee->getFunctionType();
1058 // We require integer(i32)
1059 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1060 !FT->getParamType(0)->isIntegerTy(32))
1063 // isascii(c) -> c <u 128
1064 Value *Op = CI->getArgOperand(0);
1065 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1066 return B.CreateZExt(Op, CI->getType());
1070 //===---------------------------------------===//
1071 // 'abs', 'labs', 'llabs' Optimizations
1073 struct AbsOpt : public LibCallOptimization {
1074 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1075 FunctionType *FT = Callee->getFunctionType();
1076 // We require integer(integer) where the types agree.
1077 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1078 FT->getParamType(0) != FT->getReturnType())
1081 // abs(x) -> x >s -1 ? x : -x
1082 Value *Op = CI->getArgOperand(0);
1083 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1085 Value *Neg = B.CreateNeg(Op, "neg");
1086 return B.CreateSelect(Pos, Op, Neg);
1091 //===---------------------------------------===//
1092 // 'toascii' Optimizations
1094 struct ToAsciiOpt : public LibCallOptimization {
1095 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1096 FunctionType *FT = Callee->getFunctionType();
1097 // We require i32(i32)
1098 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1099 !FT->getParamType(0)->isIntegerTy(32))
1102 // isascii(c) -> c & 0x7f
1103 return B.CreateAnd(CI->getArgOperand(0),
1104 ConstantInt::get(CI->getType(),0x7F));
1108 //===----------------------------------------------------------------------===//
1109 // Formatting and IO Optimizations
1110 //===----------------------------------------------------------------------===//
1112 //===---------------------------------------===//
1113 // 'printf' Optimizations
1115 struct PrintFOpt : public LibCallOptimization {
1116 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1118 // Check for a fixed format string.
1119 std::string FormatStr;
1120 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
1123 // Empty format string -> noop.
1124 if (FormatStr.empty()) // Tolerate printf's declared void.
1125 return CI->use_empty() ? (Value*)CI :
1126 ConstantInt::get(CI->getType(), 0);
1128 // Do not do any of the following transformations if the printf return value
1129 // is used, in general the printf return value is not compatible with either
1130 // putchar() or puts().
1131 if (!CI->use_empty())
1134 // printf("x") -> putchar('x'), even for '%'.
1135 if (FormatStr.size() == 1) {
1136 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
1137 if (CI->use_empty()) return CI;
1138 return B.CreateIntCast(Res, CI->getType(), true);
1141 // printf("foo\n") --> puts("foo")
1142 if (FormatStr[FormatStr.size()-1] == '\n' &&
1143 FormatStr.find('%') == std::string::npos) { // no format characters.
1144 // Create a string literal with no \n on it. We expect the constant merge
1145 // pass to be run after this pass, to merge duplicate strings.
1146 FormatStr.erase(FormatStr.end()-1);
1147 Value *GV = B.CreateGlobalString(FormatStr, "str");
1148 EmitPutS(GV, B, TD);
1149 return CI->use_empty() ? (Value*)CI :
1150 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1153 // Optimize specific format strings.
1154 // printf("%c", chr) --> putchar(chr)
1155 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1156 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1157 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
1159 if (CI->use_empty()) return CI;
1160 return B.CreateIntCast(Res, CI->getType(), true);
1163 // printf("%s\n", str) --> puts(str)
1164 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1165 CI->getArgOperand(1)->getType()->isPointerTy()) {
1166 EmitPutS(CI->getArgOperand(1), B, TD);
1172 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1173 // Require one fixed pointer argument and an integer/void result.
1174 FunctionType *FT = Callee->getFunctionType();
1175 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1176 !(FT->getReturnType()->isIntegerTy() ||
1177 FT->getReturnType()->isVoidTy()))
1180 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1184 // printf(format, ...) -> iprintf(format, ...) if no floating point
1186 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1187 Module *M = B.GetInsertBlock()->getParent()->getParent();
1188 Constant *IPrintFFn =
1189 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1190 CallInst *New = cast<CallInst>(CI->clone());
1191 New->setCalledFunction(IPrintFFn);
1199 //===---------------------------------------===//
1200 // 'sprintf' Optimizations
1202 struct SPrintFOpt : public LibCallOptimization {
1203 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1205 // Check for a fixed format string.
1206 std::string FormatStr;
1207 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1210 // If we just have a format string (nothing else crazy) transform it.
1211 if (CI->getNumArgOperands() == 2) {
1212 // Make sure there's no % in the constant array. We could try to handle
1213 // %% -> % in the future if we cared.
1214 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1215 if (FormatStr[i] == '%')
1216 return 0; // we found a format specifier, bail out.
1218 // These optimizations require TargetData.
1221 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1222 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1223 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1224 FormatStr.size() + 1), 1); // nul byte.
1225 return ConstantInt::get(CI->getType(), FormatStr.size());
1228 // The remaining optimizations require the format string to be "%s" or "%c"
1229 // and have an extra operand.
1230 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1231 CI->getNumArgOperands() < 3)
1234 // Decode the second character of the format string.
1235 if (FormatStr[1] == 'c') {
1236 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1237 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1238 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1239 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1240 B.CreateStore(V, Ptr);
1241 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1242 B.CreateStore(B.getInt8(0), Ptr);
1244 return ConstantInt::get(CI->getType(), 1);
1247 if (FormatStr[1] == 's') {
1248 // These optimizations require TargetData.
1251 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1252 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1254 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
1255 Value *IncLen = B.CreateAdd(Len,
1256 ConstantInt::get(Len->getType(), 1),
1258 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1260 // The sprintf result is the unincremented number of bytes in the string.
1261 return B.CreateIntCast(Len, CI->getType(), false);
1266 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1267 // Require two fixed pointer arguments and an integer result.
1268 FunctionType *FT = Callee->getFunctionType();
1269 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1270 !FT->getParamType(1)->isPointerTy() ||
1271 !FT->getReturnType()->isIntegerTy())
1274 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1278 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1280 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1281 Module *M = B.GetInsertBlock()->getParent()->getParent();
1282 Constant *SIPrintFFn =
1283 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1284 CallInst *New = cast<CallInst>(CI->clone());
1285 New->setCalledFunction(SIPrintFFn);
1293 //===---------------------------------------===//
1294 // 'fwrite' Optimizations
1296 struct FWriteOpt : public LibCallOptimization {
1297 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1298 // Require a pointer, an integer, an integer, a pointer, returning integer.
1299 FunctionType *FT = Callee->getFunctionType();
1300 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1301 !FT->getParamType(1)->isIntegerTy() ||
1302 !FT->getParamType(2)->isIntegerTy() ||
1303 !FT->getParamType(3)->isPointerTy() ||
1304 !FT->getReturnType()->isIntegerTy())
1307 // Get the element size and count.
1308 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1309 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1310 if (!SizeC || !CountC) return 0;
1311 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1313 // If this is writing zero records, remove the call (it's a noop).
1315 return ConstantInt::get(CI->getType(), 0);
1317 // If this is writing one byte, turn it into fputc.
1318 // This optimisation is only valid, if the return value is unused.
1319 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1320 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1321 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
1322 return ConstantInt::get(CI->getType(), 1);
1329 //===---------------------------------------===//
1330 // 'fputs' Optimizations
1332 struct FPutsOpt : public LibCallOptimization {
1333 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1334 // These optimizations require TargetData.
1337 // Require two pointers. Also, we can't optimize if return value is used.
1338 FunctionType *FT = Callee->getFunctionType();
1339 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1340 !FT->getParamType(1)->isPointerTy() ||
1344 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1345 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1347 EmitFWrite(CI->getArgOperand(0),
1348 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1349 CI->getArgOperand(1), B, TD, TLI);
1350 return CI; // Known to have no uses (see above).
1354 //===---------------------------------------===//
1355 // 'fprintf' Optimizations
1357 struct FPrintFOpt : public LibCallOptimization {
1358 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1360 // All the optimizations depend on the format string.
1361 std::string FormatStr;
1362 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1365 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1366 if (CI->getNumArgOperands() == 2) {
1367 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1368 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1369 return 0; // We found a format specifier.
1371 // These optimizations require TargetData.
1374 EmitFWrite(CI->getArgOperand(1),
1375 ConstantInt::get(TD->getIntPtrType(*Context),
1377 CI->getArgOperand(0), B, TD, TLI);
1378 return ConstantInt::get(CI->getType(), FormatStr.size());
1381 // The remaining optimizations require the format string to be "%s" or "%c"
1382 // and have an extra operand.
1383 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1384 CI->getNumArgOperands() < 3)
1387 // Decode the second character of the format string.
1388 if (FormatStr[1] == 'c') {
1389 // fprintf(F, "%c", chr) --> fputc(chr, F)
1390 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1391 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1392 return ConstantInt::get(CI->getType(), 1);
1395 if (FormatStr[1] == 's') {
1396 // fprintf(F, "%s", str) --> fputs(str, F)
1397 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1399 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1405 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1406 // Require two fixed paramters as pointers and integer result.
1407 FunctionType *FT = Callee->getFunctionType();
1408 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1409 !FT->getParamType(1)->isPointerTy() ||
1410 !FT->getReturnType()->isIntegerTy())
1413 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1417 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1418 // floating point arguments.
1419 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1420 Module *M = B.GetInsertBlock()->getParent()->getParent();
1421 Constant *FIPrintFFn =
1422 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1423 CallInst *New = cast<CallInst>(CI->clone());
1424 New->setCalledFunction(FIPrintFFn);
1432 //===---------------------------------------===//
1433 // 'puts' Optimizations
1435 struct PutsOpt : public LibCallOptimization {
1436 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1437 // Require one fixed pointer argument and an integer/void result.
1438 FunctionType *FT = Callee->getFunctionType();
1439 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1440 !(FT->getReturnType()->isIntegerTy() ||
1441 FT->getReturnType()->isVoidTy()))
1444 // Check for a constant string.
1446 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1449 if (Str.empty() && CI->use_empty()) {
1450 // puts("") -> putchar('\n')
1451 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1452 if (CI->use_empty()) return CI;
1453 return B.CreateIntCast(Res, CI->getType(), true);
1460 } // end anonymous namespace.
1462 //===----------------------------------------------------------------------===//
1463 // SimplifyLibCalls Pass Implementation
1464 //===----------------------------------------------------------------------===//
1467 /// This pass optimizes well known library functions from libc and libm.
1469 class SimplifyLibCalls : public FunctionPass {
1470 TargetLibraryInfo *TLI;
1472 StringMap<LibCallOptimization*> Optimizations;
1473 // String and Memory LibCall Optimizations
1474 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1475 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1476 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1477 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1478 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1479 // Math Library Optimizations
1480 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1481 // Integer Optimizations
1482 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1484 // Formatting and IO Optimizations
1485 SPrintFOpt SPrintF; PrintFOpt PrintF;
1486 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1489 bool Modified; // This is only used by doInitialization.
1491 static char ID; // Pass identification
1492 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1493 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1495 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1496 void InitOptimizations();
1497 bool runOnFunction(Function &F);
1499 void setDoesNotAccessMemory(Function &F);
1500 void setOnlyReadsMemory(Function &F);
1501 void setDoesNotThrow(Function &F);
1502 void setDoesNotCapture(Function &F, unsigned n);
1503 void setDoesNotAlias(Function &F, unsigned n);
1504 bool doInitialization(Module &M);
1506 void inferPrototypeAttributes(Function &F);
1507 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1508 AU.addRequired<TargetLibraryInfo>();
1511 } // end anonymous namespace.
1513 char SimplifyLibCalls::ID = 0;
1515 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1516 "Simplify well-known library calls", false, false)
1517 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1518 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1519 "Simplify well-known library calls", false, false)
1521 // Public interface to the Simplify LibCalls pass.
1522 FunctionPass *llvm::createSimplifyLibCallsPass() {
1523 return new SimplifyLibCalls();
1526 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1528 Optimizations[TLI->getName(F)] = Opt;
1531 /// Optimizations - Populate the Optimizations map with all the optimizations
1533 void SimplifyLibCalls::InitOptimizations() {
1534 // String and Memory LibCall Optimizations
1535 Optimizations["strcat"] = &StrCat;
1536 Optimizations["strncat"] = &StrNCat;
1537 Optimizations["strchr"] = &StrChr;
1538 Optimizations["strrchr"] = &StrRChr;
1539 Optimizations["strcmp"] = &StrCmp;
1540 Optimizations["strncmp"] = &StrNCmp;
1541 Optimizations["strcpy"] = &StrCpy;
1542 Optimizations["strncpy"] = &StrNCpy;
1543 Optimizations["strlen"] = &StrLen;
1544 Optimizations["strpbrk"] = &StrPBrk;
1545 Optimizations["strtol"] = &StrTo;
1546 Optimizations["strtod"] = &StrTo;
1547 Optimizations["strtof"] = &StrTo;
1548 Optimizations["strtoul"] = &StrTo;
1549 Optimizations["strtoll"] = &StrTo;
1550 Optimizations["strtold"] = &StrTo;
1551 Optimizations["strtoull"] = &StrTo;
1552 Optimizations["strspn"] = &StrSpn;
1553 Optimizations["strcspn"] = &StrCSpn;
1554 Optimizations["strstr"] = &StrStr;
1555 Optimizations["memcmp"] = &MemCmp;
1556 AddOpt(LibFunc::memcpy, &MemCpy);
1557 Optimizations["memmove"] = &MemMove;
1558 AddOpt(LibFunc::memset, &MemSet);
1560 // _chk variants of String and Memory LibCall Optimizations.
1561 Optimizations["__strcpy_chk"] = &StrCpyChk;
1563 // Math Library Optimizations
1564 Optimizations["cosf"] = &Cos;
1565 Optimizations["cos"] = &Cos;
1566 Optimizations["cosl"] = &Cos;
1567 Optimizations["powf"] = &Pow;
1568 Optimizations["pow"] = &Pow;
1569 Optimizations["powl"] = &Pow;
1570 Optimizations["llvm.pow.f32"] = &Pow;
1571 Optimizations["llvm.pow.f64"] = &Pow;
1572 Optimizations["llvm.pow.f80"] = &Pow;
1573 Optimizations["llvm.pow.f128"] = &Pow;
1574 Optimizations["llvm.pow.ppcf128"] = &Pow;
1575 Optimizations["exp2l"] = &Exp2;
1576 Optimizations["exp2"] = &Exp2;
1577 Optimizations["exp2f"] = &Exp2;
1578 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1579 Optimizations["llvm.exp2.f128"] = &Exp2;
1580 Optimizations["llvm.exp2.f80"] = &Exp2;
1581 Optimizations["llvm.exp2.f64"] = &Exp2;
1582 Optimizations["llvm.exp2.f32"] = &Exp2;
1585 Optimizations["floor"] = &UnaryDoubleFP;
1588 Optimizations["ceil"] = &UnaryDoubleFP;
1591 Optimizations["round"] = &UnaryDoubleFP;
1594 Optimizations["rint"] = &UnaryDoubleFP;
1596 #ifdef HAVE_NEARBYINTF
1597 Optimizations["nearbyint"] = &UnaryDoubleFP;
1600 // Integer Optimizations
1601 Optimizations["ffs"] = &FFS;
1602 Optimizations["ffsl"] = &FFS;
1603 Optimizations["ffsll"] = &FFS;
1604 Optimizations["abs"] = &Abs;
1605 Optimizations["labs"] = &Abs;
1606 Optimizations["llabs"] = &Abs;
1607 Optimizations["isdigit"] = &IsDigit;
1608 Optimizations["isascii"] = &IsAscii;
1609 Optimizations["toascii"] = &ToAscii;
1611 // Formatting and IO Optimizations
1612 Optimizations["sprintf"] = &SPrintF;
1613 Optimizations["printf"] = &PrintF;
1614 AddOpt(LibFunc::fwrite, &FWrite);
1615 AddOpt(LibFunc::fputs, &FPuts);
1616 Optimizations["fprintf"] = &FPrintF;
1617 Optimizations["puts"] = &Puts;
1621 /// runOnFunction - Top level algorithm.
1623 bool SimplifyLibCalls::runOnFunction(Function &F) {
1624 TLI = &getAnalysis<TargetLibraryInfo>();
1626 if (Optimizations.empty())
1627 InitOptimizations();
1629 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1631 IRBuilder<> Builder(F.getContext());
1633 bool Changed = false;
1634 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1635 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1636 // Ignore non-calls.
1637 CallInst *CI = dyn_cast<CallInst>(I++);
1640 // Ignore indirect calls and calls to non-external functions.
1641 Function *Callee = CI->getCalledFunction();
1642 if (Callee == 0 || !Callee->isDeclaration() ||
1643 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1646 // Ignore unknown calls.
1647 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1650 // Set the builder to the instruction after the call.
1651 Builder.SetInsertPoint(BB, I);
1653 // Use debug location of CI for all new instructions.
1654 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1656 // Try to optimize this call.
1657 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1658 if (Result == 0) continue;
1660 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1661 dbgs() << " into: " << *Result << "\n");
1663 // Something changed!
1667 // Inspect the instruction after the call (which was potentially just
1671 if (CI != Result && !CI->use_empty()) {
1672 CI->replaceAllUsesWith(Result);
1673 if (!Result->hasName())
1674 Result->takeName(CI);
1676 CI->eraseFromParent();
1682 // Utility methods for doInitialization.
1684 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1685 if (!F.doesNotAccessMemory()) {
1686 F.setDoesNotAccessMemory();
1691 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1692 if (!F.onlyReadsMemory()) {
1693 F.setOnlyReadsMemory();
1698 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1699 if (!F.doesNotThrow()) {
1700 F.setDoesNotThrow();
1705 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1706 if (!F.doesNotCapture(n)) {
1707 F.setDoesNotCapture(n);
1712 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1713 if (!F.doesNotAlias(n)) {
1714 F.setDoesNotAlias(n);
1721 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1722 FunctionType *FTy = F.getFunctionType();
1724 StringRef Name = F.getName();
1727 if (Name == "strlen") {
1728 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1730 setOnlyReadsMemory(F);
1732 setDoesNotCapture(F, 1);
1733 } else if (Name == "strchr" ||
1734 Name == "strrchr") {
1735 if (FTy->getNumParams() != 2 ||
1736 !FTy->getParamType(0)->isPointerTy() ||
1737 !FTy->getParamType(1)->isIntegerTy())
1739 setOnlyReadsMemory(F);
1741 } else if (Name == "strcpy" ||
1747 Name == "strtoul" ||
1748 Name == "strtoll" ||
1749 Name == "strtold" ||
1750 Name == "strncat" ||
1751 Name == "strncpy" ||
1752 Name == "strtoull") {
1753 if (FTy->getNumParams() < 2 ||
1754 !FTy->getParamType(1)->isPointerTy())
1757 setDoesNotCapture(F, 2);
1758 } else if (Name == "strxfrm") {
1759 if (FTy->getNumParams() != 3 ||
1760 !FTy->getParamType(0)->isPointerTy() ||
1761 !FTy->getParamType(1)->isPointerTy())
1764 setDoesNotCapture(F, 1);
1765 setDoesNotCapture(F, 2);
1766 } else if (Name == "strcmp" ||
1768 Name == "strncmp" ||
1769 Name == "strcspn" ||
1770 Name == "strcoll" ||
1771 Name == "strcasecmp" ||
1772 Name == "strncasecmp") {
1773 if (FTy->getNumParams() < 2 ||
1774 !FTy->getParamType(0)->isPointerTy() ||
1775 !FTy->getParamType(1)->isPointerTy())
1777 setOnlyReadsMemory(F);
1779 setDoesNotCapture(F, 1);
1780 setDoesNotCapture(F, 2);
1781 } else if (Name == "strstr" ||
1782 Name == "strpbrk") {
1783 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1785 setOnlyReadsMemory(F);
1787 setDoesNotCapture(F, 2);
1788 } else if (Name == "strtok" ||
1789 Name == "strtok_r") {
1790 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1793 setDoesNotCapture(F, 2);
1794 } else if (Name == "scanf" ||
1796 Name == "setvbuf") {
1797 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1800 setDoesNotCapture(F, 1);
1801 } else if (Name == "strdup" ||
1802 Name == "strndup") {
1803 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1804 !FTy->getParamType(0)->isPointerTy())
1807 setDoesNotAlias(F, 0);
1808 setDoesNotCapture(F, 1);
1809 } else if (Name == "stat" ||
1811 Name == "sprintf" ||
1812 Name == "statvfs") {
1813 if (FTy->getNumParams() < 2 ||
1814 !FTy->getParamType(0)->isPointerTy() ||
1815 !FTy->getParamType(1)->isPointerTy())
1818 setDoesNotCapture(F, 1);
1819 setDoesNotCapture(F, 2);
1820 } else if (Name == "snprintf") {
1821 if (FTy->getNumParams() != 3 ||
1822 !FTy->getParamType(0)->isPointerTy() ||
1823 !FTy->getParamType(2)->isPointerTy())
1826 setDoesNotCapture(F, 1);
1827 setDoesNotCapture(F, 3);
1828 } else if (Name == "setitimer") {
1829 if (FTy->getNumParams() != 3 ||
1830 !FTy->getParamType(1)->isPointerTy() ||
1831 !FTy->getParamType(2)->isPointerTy())
1834 setDoesNotCapture(F, 2);
1835 setDoesNotCapture(F, 3);
1836 } else if (Name == "system") {
1837 if (FTy->getNumParams() != 1 ||
1838 !FTy->getParamType(0)->isPointerTy())
1840 // May throw; "system" is a valid pthread cancellation point.
1841 setDoesNotCapture(F, 1);
1845 if (Name == "malloc") {
1846 if (FTy->getNumParams() != 1 ||
1847 !FTy->getReturnType()->isPointerTy())
1850 setDoesNotAlias(F, 0);
1851 } else if (Name == "memcmp") {
1852 if (FTy->getNumParams() != 3 ||
1853 !FTy->getParamType(0)->isPointerTy() ||
1854 !FTy->getParamType(1)->isPointerTy())
1856 setOnlyReadsMemory(F);
1858 setDoesNotCapture(F, 1);
1859 setDoesNotCapture(F, 2);
1860 } else if (Name == "memchr" ||
1861 Name == "memrchr") {
1862 if (FTy->getNumParams() != 3)
1864 setOnlyReadsMemory(F);
1866 } else if (Name == "modf" ||
1870 Name == "memccpy" ||
1871 Name == "memmove") {
1872 if (FTy->getNumParams() < 2 ||
1873 !FTy->getParamType(1)->isPointerTy())
1876 setDoesNotCapture(F, 2);
1877 } else if (Name == "memalign") {
1878 if (!FTy->getReturnType()->isPointerTy())
1880 setDoesNotAlias(F, 0);
1881 } else if (Name == "mkdir" ||
1883 if (FTy->getNumParams() == 0 ||
1884 !FTy->getParamType(0)->isPointerTy())
1887 setDoesNotCapture(F, 1);
1891 if (Name == "realloc") {
1892 if (FTy->getNumParams() != 2 ||
1893 !FTy->getParamType(0)->isPointerTy() ||
1894 !FTy->getReturnType()->isPointerTy())
1897 setDoesNotAlias(F, 0);
1898 setDoesNotCapture(F, 1);
1899 } else if (Name == "read") {
1900 if (FTy->getNumParams() != 3 ||
1901 !FTy->getParamType(1)->isPointerTy())
1903 // May throw; "read" is a valid pthread cancellation point.
1904 setDoesNotCapture(F, 2);
1905 } else if (Name == "rmdir" ||
1908 Name == "realpath") {
1909 if (FTy->getNumParams() < 1 ||
1910 !FTy->getParamType(0)->isPointerTy())
1913 setDoesNotCapture(F, 1);
1914 } else if (Name == "rename" ||
1915 Name == "readlink") {
1916 if (FTy->getNumParams() < 2 ||
1917 !FTy->getParamType(0)->isPointerTy() ||
1918 !FTy->getParamType(1)->isPointerTy())
1921 setDoesNotCapture(F, 1);
1922 setDoesNotCapture(F, 2);
1926 if (Name == "write") {
1927 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1929 // May throw; "write" is a valid pthread cancellation point.
1930 setDoesNotCapture(F, 2);
1934 if (Name == "bcopy") {
1935 if (FTy->getNumParams() != 3 ||
1936 !FTy->getParamType(0)->isPointerTy() ||
1937 !FTy->getParamType(1)->isPointerTy())
1940 setDoesNotCapture(F, 1);
1941 setDoesNotCapture(F, 2);
1942 } else if (Name == "bcmp") {
1943 if (FTy->getNumParams() != 3 ||
1944 !FTy->getParamType(0)->isPointerTy() ||
1945 !FTy->getParamType(1)->isPointerTy())
1948 setOnlyReadsMemory(F);
1949 setDoesNotCapture(F, 1);
1950 setDoesNotCapture(F, 2);
1951 } else if (Name == "bzero") {
1952 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1955 setDoesNotCapture(F, 1);
1959 if (Name == "calloc") {
1960 if (FTy->getNumParams() != 2 ||
1961 !FTy->getReturnType()->isPointerTy())
1964 setDoesNotAlias(F, 0);
1965 } else if (Name == "chmod" ||
1967 Name == "ctermid" ||
1968 Name == "clearerr" ||
1969 Name == "closedir") {
1970 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1973 setDoesNotCapture(F, 1);
1977 if (Name == "atoi" ||
1981 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1984 setOnlyReadsMemory(F);
1985 setDoesNotCapture(F, 1);
1986 } else if (Name == "access") {
1987 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1990 setDoesNotCapture(F, 1);
1994 if (Name == "fopen") {
1995 if (FTy->getNumParams() != 2 ||
1996 !FTy->getReturnType()->isPointerTy() ||
1997 !FTy->getParamType(0)->isPointerTy() ||
1998 !FTy->getParamType(1)->isPointerTy())
2001 setDoesNotAlias(F, 0);
2002 setDoesNotCapture(F, 1);
2003 setDoesNotCapture(F, 2);
2004 } else if (Name == "fdopen") {
2005 if (FTy->getNumParams() != 2 ||
2006 !FTy->getReturnType()->isPointerTy() ||
2007 !FTy->getParamType(1)->isPointerTy())
2010 setDoesNotAlias(F, 0);
2011 setDoesNotCapture(F, 2);
2012 } else if (Name == "feof" ||
2022 Name == "fsetpos" ||
2023 Name == "flockfile" ||
2024 Name == "funlockfile" ||
2025 Name == "ftrylockfile") {
2026 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2029 setDoesNotCapture(F, 1);
2030 } else if (Name == "ferror") {
2031 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2034 setDoesNotCapture(F, 1);
2035 setOnlyReadsMemory(F);
2036 } else if (Name == "fputc" ||
2041 Name == "fstatvfs") {
2042 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2045 setDoesNotCapture(F, 2);
2046 } else if (Name == "fgets") {
2047 if (FTy->getNumParams() != 3 ||
2048 !FTy->getParamType(0)->isPointerTy() ||
2049 !FTy->getParamType(2)->isPointerTy())
2052 setDoesNotCapture(F, 3);
2053 } else if (Name == "fread" ||
2055 if (FTy->getNumParams() != 4 ||
2056 !FTy->getParamType(0)->isPointerTy() ||
2057 !FTy->getParamType(3)->isPointerTy())
2060 setDoesNotCapture(F, 1);
2061 setDoesNotCapture(F, 4);
2062 } else if (Name == "fputs" ||
2064 Name == "fprintf" ||
2065 Name == "fgetpos") {
2066 if (FTy->getNumParams() < 2 ||
2067 !FTy->getParamType(0)->isPointerTy() ||
2068 !FTy->getParamType(1)->isPointerTy())
2071 setDoesNotCapture(F, 1);
2072 setDoesNotCapture(F, 2);
2076 if (Name == "getc" ||
2077 Name == "getlogin_r" ||
2078 Name == "getc_unlocked") {
2079 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2082 setDoesNotCapture(F, 1);
2083 } else if (Name == "getenv") {
2084 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2087 setOnlyReadsMemory(F);
2088 setDoesNotCapture(F, 1);
2089 } else if (Name == "gets" ||
2090 Name == "getchar") {
2092 } else if (Name == "getitimer") {
2093 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2096 setDoesNotCapture(F, 2);
2097 } else if (Name == "getpwnam") {
2098 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2101 setDoesNotCapture(F, 1);
2105 if (Name == "ungetc") {
2106 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2109 setDoesNotCapture(F, 2);
2110 } else if (Name == "uname" ||
2112 Name == "unsetenv") {
2113 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2116 setDoesNotCapture(F, 1);
2117 } else if (Name == "utime" ||
2119 if (FTy->getNumParams() != 2 ||
2120 !FTy->getParamType(0)->isPointerTy() ||
2121 !FTy->getParamType(1)->isPointerTy())
2124 setDoesNotCapture(F, 1);
2125 setDoesNotCapture(F, 2);
2129 if (Name == "putc") {
2130 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2133 setDoesNotCapture(F, 2);
2134 } else if (Name == "puts" ||
2137 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2140 setDoesNotCapture(F, 1);
2141 } else if (Name == "pread" ||
2143 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2145 // May throw; these are valid pthread cancellation points.
2146 setDoesNotCapture(F, 2);
2147 } else if (Name == "putchar") {
2149 } else if (Name == "popen") {
2150 if (FTy->getNumParams() != 2 ||
2151 !FTy->getReturnType()->isPointerTy() ||
2152 !FTy->getParamType(0)->isPointerTy() ||
2153 !FTy->getParamType(1)->isPointerTy())
2156 setDoesNotAlias(F, 0);
2157 setDoesNotCapture(F, 1);
2158 setDoesNotCapture(F, 2);
2159 } else if (Name == "pclose") {
2160 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2163 setDoesNotCapture(F, 1);
2167 if (Name == "vscanf") {
2168 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2171 setDoesNotCapture(F, 1);
2172 } else if (Name == "vsscanf" ||
2173 Name == "vfscanf") {
2174 if (FTy->getNumParams() != 3 ||
2175 !FTy->getParamType(1)->isPointerTy() ||
2176 !FTy->getParamType(2)->isPointerTy())
2179 setDoesNotCapture(F, 1);
2180 setDoesNotCapture(F, 2);
2181 } else if (Name == "valloc") {
2182 if (!FTy->getReturnType()->isPointerTy())
2185 setDoesNotAlias(F, 0);
2186 } else if (Name == "vprintf") {
2187 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2190 setDoesNotCapture(F, 1);
2191 } else if (Name == "vfprintf" ||
2192 Name == "vsprintf") {
2193 if (FTy->getNumParams() != 3 ||
2194 !FTy->getParamType(0)->isPointerTy() ||
2195 !FTy->getParamType(1)->isPointerTy())
2198 setDoesNotCapture(F, 1);
2199 setDoesNotCapture(F, 2);
2200 } else if (Name == "vsnprintf") {
2201 if (FTy->getNumParams() != 4 ||
2202 !FTy->getParamType(0)->isPointerTy() ||
2203 !FTy->getParamType(2)->isPointerTy())
2206 setDoesNotCapture(F, 1);
2207 setDoesNotCapture(F, 3);
2211 if (Name == "open") {
2212 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2214 // May throw; "open" is a valid pthread cancellation point.
2215 setDoesNotCapture(F, 1);
2216 } else if (Name == "opendir") {
2217 if (FTy->getNumParams() != 1 ||
2218 !FTy->getReturnType()->isPointerTy() ||
2219 !FTy->getParamType(0)->isPointerTy())
2222 setDoesNotAlias(F, 0);
2223 setDoesNotCapture(F, 1);
2227 if (Name == "tmpfile") {
2228 if (!FTy->getReturnType()->isPointerTy())
2231 setDoesNotAlias(F, 0);
2232 } else if (Name == "times") {
2233 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2236 setDoesNotCapture(F, 1);
2240 if (Name == "htonl" ||
2243 setDoesNotAccessMemory(F);
2247 if (Name == "ntohl" ||
2250 setDoesNotAccessMemory(F);
2254 if (Name == "lstat") {
2255 if (FTy->getNumParams() != 2 ||
2256 !FTy->getParamType(0)->isPointerTy() ||
2257 !FTy->getParamType(1)->isPointerTy())
2260 setDoesNotCapture(F, 1);
2261 setDoesNotCapture(F, 2);
2262 } else if (Name == "lchown") {
2263 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2266 setDoesNotCapture(F, 1);
2270 if (Name == "qsort") {
2271 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2273 // May throw; places call through function pointer.
2274 setDoesNotCapture(F, 4);
2278 if (Name == "__strdup" ||
2279 Name == "__strndup") {
2280 if (FTy->getNumParams() < 1 ||
2281 !FTy->getReturnType()->isPointerTy() ||
2282 !FTy->getParamType(0)->isPointerTy())
2285 setDoesNotAlias(F, 0);
2286 setDoesNotCapture(F, 1);
2287 } else if (Name == "__strtok_r") {
2288 if (FTy->getNumParams() != 3 ||
2289 !FTy->getParamType(1)->isPointerTy())
2292 setDoesNotCapture(F, 2);
2293 } else if (Name == "_IO_getc") {
2294 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2297 setDoesNotCapture(F, 1);
2298 } else if (Name == "_IO_putc") {
2299 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2302 setDoesNotCapture(F, 2);
2306 if (Name == "\1__isoc99_scanf") {
2307 if (FTy->getNumParams() < 1 ||
2308 !FTy->getParamType(0)->isPointerTy())
2311 setDoesNotCapture(F, 1);
2312 } else if (Name == "\1stat64" ||
2313 Name == "\1lstat64" ||
2314 Name == "\1statvfs64" ||
2315 Name == "\1__isoc99_sscanf") {
2316 if (FTy->getNumParams() < 1 ||
2317 !FTy->getParamType(0)->isPointerTy() ||
2318 !FTy->getParamType(1)->isPointerTy())
2321 setDoesNotCapture(F, 1);
2322 setDoesNotCapture(F, 2);
2323 } else if (Name == "\1fopen64") {
2324 if (FTy->getNumParams() != 2 ||
2325 !FTy->getReturnType()->isPointerTy() ||
2326 !FTy->getParamType(0)->isPointerTy() ||
2327 !FTy->getParamType(1)->isPointerTy())
2330 setDoesNotAlias(F, 0);
2331 setDoesNotCapture(F, 1);
2332 setDoesNotCapture(F, 2);
2333 } else if (Name == "\1fseeko64" ||
2334 Name == "\1ftello64") {
2335 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2338 setDoesNotCapture(F, 1);
2339 } else if (Name == "\1tmpfile64") {
2340 if (!FTy->getReturnType()->isPointerTy())
2343 setDoesNotAlias(F, 0);
2344 } else if (Name == "\1fstat64" ||
2345 Name == "\1fstatvfs64") {
2346 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2349 setDoesNotCapture(F, 2);
2350 } else if (Name == "\1open64") {
2351 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2353 // May throw; "open" is a valid pthread cancellation point.
2354 setDoesNotCapture(F, 1);
2360 /// doInitialization - Add attributes to well-known functions.
2362 bool SimplifyLibCalls::doInitialization(Module &M) {
2364 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2366 if (F.isDeclaration() && F.hasName())
2367 inferPrototypeAttributes(F);
2373 // Additional cases that we need to add to this file:
2376 // * cbrt(expN(X)) -> expN(x/3)
2377 // * cbrt(sqrt(x)) -> pow(x,1/6)
2378 // * cbrt(sqrt(x)) -> pow(x,1/9)
2381 // * exp(log(x)) -> x
2384 // * log(exp(x)) -> x
2385 // * log(x**y) -> y*log(x)
2386 // * log(exp(y)) -> y*log(e)
2387 // * log(exp2(y)) -> y*log(2)
2388 // * log(exp10(y)) -> y*log(10)
2389 // * log(sqrt(x)) -> 0.5*log(x)
2390 // * log(pow(x,y)) -> y*log(x)
2392 // lround, lroundf, lroundl:
2393 // * lround(cnst) -> cnst'
2396 // * pow(exp(x),y) -> exp(x*y)
2397 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2398 // * pow(pow(x,y),z)-> pow(x,y*z)
2400 // round, roundf, roundl:
2401 // * round(cnst) -> cnst'
2404 // * signbit(cnst) -> cnst'
2405 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2407 // sqrt, sqrtf, sqrtl:
2408 // * sqrt(expN(x)) -> expN(x*0.5)
2409 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2410 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2413 // * stpcpy(str, "literal") ->
2414 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2417 // * tan(atan(x)) -> x
2419 // trunc, truncf, truncl:
2420 // * trunc(cnst) -> cnst'