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/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetLibraryInfo.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 return EmitStrLenMemCpy(Src, Dst, Len, B);
163 Value *EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
164 // We need to find the end of the destination string. That's where the
165 // memory is to be moved to. We just generate a call to strlen.
166 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
170 // Now that we have the destination's length, we must index into the
171 // destination's pointer to get the actual memcpy destination (end of
172 // the string .. we're concatenating).
173 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
175 // We have enough information to now generate the memcpy call to do the
176 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
177 B.CreateMemCpy(CpyDst, Src,
178 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
183 //===---------------------------------------===//
184 // 'strncat' Optimizations
186 struct StrNCatOpt : public StrCatOpt {
187 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
188 // Verify the "strncat" function prototype.
189 FunctionType *FT = Callee->getFunctionType();
190 if (FT->getNumParams() != 3 ||
191 FT->getReturnType() != B.getInt8PtrTy() ||
192 FT->getParamType(0) != FT->getReturnType() ||
193 FT->getParamType(1) != FT->getReturnType() ||
194 !FT->getParamType(2)->isIntegerTy())
197 // Extract some information from the instruction
198 Value *Dst = CI->getArgOperand(0);
199 Value *Src = CI->getArgOperand(1);
202 // We don't do anything if length is not constant
203 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
204 Len = LengthArg->getZExtValue();
208 // See if we can get the length of the input string.
209 uint64_t SrcLen = GetStringLength(Src);
210 if (SrcLen == 0) return 0;
211 --SrcLen; // Unbias length.
213 // Handle the simple, do-nothing cases:
214 // strncat(x, "", c) -> x
215 // strncat(x, c, 0) -> x
216 if (SrcLen == 0 || Len == 0) return Dst;
218 // These optimizations require TargetData.
221 // We don't optimize this case
222 if (Len < SrcLen) return 0;
224 // strncat(x, s, c) -> strcat(x, s)
225 // s is constant so the strcat can be optimized further
226 return EmitStrLenMemCpy(Src, Dst, SrcLen, B);
230 //===---------------------------------------===//
231 // 'strchr' Optimizations
233 struct StrChrOpt : public LibCallOptimization {
234 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
235 // Verify the "strchr" function prototype.
236 FunctionType *FT = Callee->getFunctionType();
237 if (FT->getNumParams() != 2 ||
238 FT->getReturnType() != B.getInt8PtrTy() ||
239 FT->getParamType(0) != FT->getReturnType() ||
240 !FT->getParamType(1)->isIntegerTy(32))
243 Value *SrcStr = CI->getArgOperand(0);
245 // If the second operand is non-constant, see if we can compute the length
246 // of the input string and turn this into memchr.
247 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
249 // These optimizations require TargetData.
252 uint64_t Len = GetStringLength(SrcStr);
253 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
256 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
257 ConstantInt::get(TD->getIntPtrType(*Context), Len),
261 // Otherwise, the character is a constant, see if the first argument is
262 // a string literal. If so, we can constant fold.
264 if (!getConstantStringInfo(SrcStr, Str))
267 // Compute the offset, make sure to handle the case when we're searching for
268 // zero (a weird way to spell strlen).
269 size_t I = CharC->getSExtValue() == 0 ?
270 Str.size() : Str.find(CharC->getSExtValue());
271 if (I == StringRef::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, TLI);
307 // Compute the offset.
308 size_t I = CharC->getSExtValue() == 0 ?
309 Str.size() : Str.rfind(CharC->getSExtValue());
310 if (I == StringRef::npos) // Didn't find the char. Return null.
311 return Constant::getNullValue(CI->getType());
313 // strrchr(s+n,c) -> gep(s+n+i,c)
314 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
318 //===---------------------------------------===//
319 // 'strcmp' Optimizations
321 struct StrCmpOpt : public LibCallOptimization {
322 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
323 // Verify the "strcmp" function prototype.
324 FunctionType *FT = Callee->getFunctionType();
325 if (FT->getNumParams() != 2 ||
326 !FT->getReturnType()->isIntegerTy(32) ||
327 FT->getParamType(0) != FT->getParamType(1) ||
328 FT->getParamType(0) != B.getInt8PtrTy())
331 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
332 if (Str1P == Str2P) // strcmp(x,x) -> 0
333 return ConstantInt::get(CI->getType(), 0);
335 StringRef Str1, Str2;
336 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
337 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
339 // strcmp(x, y) -> cnst (if both x and y are constant strings)
340 if (HasStr1 && HasStr2)
341 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
343 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
344 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
347 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
348 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
350 // strcmp(P, "x") -> memcmp(P, "x", 2)
351 uint64_t Len1 = GetStringLength(Str1P);
352 uint64_t Len2 = GetStringLength(Str2P);
354 // These optimizations require TargetData.
357 return EmitMemCmp(Str1P, Str2P,
358 ConstantInt::get(TD->getIntPtrType(*Context),
359 std::min(Len1, Len2)), B, TD, TLI);
366 //===---------------------------------------===//
367 // 'strncmp' Optimizations
369 struct StrNCmpOpt : public LibCallOptimization {
370 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
371 // Verify the "strncmp" function prototype.
372 FunctionType *FT = Callee->getFunctionType();
373 if (FT->getNumParams() != 3 ||
374 !FT->getReturnType()->isIntegerTy(32) ||
375 FT->getParamType(0) != FT->getParamType(1) ||
376 FT->getParamType(0) != B.getInt8PtrTy() ||
377 !FT->getParamType(2)->isIntegerTy())
380 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
381 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
382 return ConstantInt::get(CI->getType(), 0);
384 // Get the length argument if it is constant.
386 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
387 Length = LengthArg->getZExtValue();
391 if (Length == 0) // strncmp(x,y,0) -> 0
392 return ConstantInt::get(CI->getType(), 0);
394 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
395 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
397 StringRef Str1, Str2;
398 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
399 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
401 // strncmp(x, y) -> cnst (if both x and y are constant strings)
402 if (HasStr1 && HasStr2) {
403 StringRef SubStr1 = Str1.substr(0, Length);
404 StringRef SubStr2 = Str2.substr(0, Length);
405 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
408 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
409 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
412 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
413 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
420 //===---------------------------------------===//
421 // 'strcpy' Optimizations
423 struct StrCpyOpt : public LibCallOptimization {
424 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
426 StrCpyOpt(bool c) : OptChkCall(c) {}
428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
429 // Verify the "strcpy" function prototype.
430 unsigned NumParams = OptChkCall ? 3 : 2;
431 FunctionType *FT = Callee->getFunctionType();
432 if (FT->getNumParams() != NumParams ||
433 FT->getReturnType() != FT->getParamType(0) ||
434 FT->getParamType(0) != FT->getParamType(1) ||
435 FT->getParamType(0) != B.getInt8PtrTy())
438 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
439 if (Dst == Src) // strcpy(x,x) -> x
442 // These optimizations require TargetData.
445 // See if we can get the length of the input string.
446 uint64_t Len = GetStringLength(Src);
447 if (Len == 0) return 0;
449 // We have enough information to now generate the memcpy call to do the
450 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
452 !EmitMemCpyChk(Dst, Src,
453 ConstantInt::get(TD->getIntPtrType(*Context), Len),
454 CI->getArgOperand(2), B, TD, TLI))
455 B.CreateMemCpy(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
461 //===---------------------------------------===//
462 // 'stpcpy' Optimizations
464 struct StpCpyOpt: public LibCallOptimization {
465 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
467 StpCpyOpt(bool c) : OptChkCall(c) {}
469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
470 // Verify the "stpcpy" function prototype.
471 unsigned NumParams = OptChkCall ? 3 : 2;
472 FunctionType *FT = Callee->getFunctionType();
473 if (FT->getNumParams() != NumParams ||
474 FT->getReturnType() != FT->getParamType(0) ||
475 FT->getParamType(0) != FT->getParamType(1) ||
476 FT->getParamType(0) != B.getInt8PtrTy())
479 // These optimizations require TargetData.
482 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
483 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
484 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
485 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
488 // See if we can get the length of the input string.
489 uint64_t Len = GetStringLength(Src);
490 if (Len == 0) return 0;
492 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
493 Value *DstEnd = B.CreateGEP(Dst,
494 ConstantInt::get(TD->getIntPtrType(*Context),
497 // We have enough information to now generate the memcpy call to do the
498 // copy for us. Make a memcpy to copy the nul byte with align = 1.
499 if (!OptChkCall || !EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B,
501 B.CreateMemCpy(Dst, Src, LenV, 1);
506 //===---------------------------------------===//
507 // 'strncpy' Optimizations
509 struct StrNCpyOpt : public LibCallOptimization {
510 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
511 FunctionType *FT = Callee->getFunctionType();
512 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
513 FT->getParamType(0) != FT->getParamType(1) ||
514 FT->getParamType(0) != B.getInt8PtrTy() ||
515 !FT->getParamType(2)->isIntegerTy())
518 Value *Dst = CI->getArgOperand(0);
519 Value *Src = CI->getArgOperand(1);
520 Value *LenOp = CI->getArgOperand(2);
522 // See if we can get the length of the input string.
523 uint64_t SrcLen = GetStringLength(Src);
524 if (SrcLen == 0) return 0;
528 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
529 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
534 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
535 Len = LengthArg->getZExtValue();
539 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
541 // These optimizations require TargetData.
544 // Let strncpy handle the zero padding
545 if (Len > SrcLen+1) return 0;
547 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
548 B.CreateMemCpy(Dst, Src,
549 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
555 //===---------------------------------------===//
556 // 'strlen' Optimizations
558 struct StrLenOpt : public LibCallOptimization {
559 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
560 FunctionType *FT = Callee->getFunctionType();
561 if (FT->getNumParams() != 1 ||
562 FT->getParamType(0) != B.getInt8PtrTy() ||
563 !FT->getReturnType()->isIntegerTy())
566 Value *Src = CI->getArgOperand(0);
568 // Constant folding: strlen("xyz") -> 3
569 if (uint64_t Len = GetStringLength(Src))
570 return ConstantInt::get(CI->getType(), Len-1);
572 // strlen(x) != 0 --> *x != 0
573 // strlen(x) == 0 --> *x == 0
574 if (IsOnlyUsedInZeroEqualityComparison(CI))
575 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
581 //===---------------------------------------===//
582 // 'strpbrk' Optimizations
584 struct StrPBrkOpt : public LibCallOptimization {
585 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
586 FunctionType *FT = Callee->getFunctionType();
587 if (FT->getNumParams() != 2 ||
588 FT->getParamType(0) != B.getInt8PtrTy() ||
589 FT->getParamType(1) != FT->getParamType(0) ||
590 FT->getReturnType() != FT->getParamType(0))
594 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
595 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
597 // strpbrk(s, "") -> NULL
598 // strpbrk("", s) -> NULL
599 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
600 return Constant::getNullValue(CI->getType());
603 if (HasS1 && HasS2) {
604 size_t I = S1.find_first_of(S2);
605 if (I == std::string::npos) // No match.
606 return Constant::getNullValue(CI->getType());
608 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
611 // strpbrk(s, "a") -> strchr(s, 'a')
612 if (TD && HasS2 && S2.size() == 1)
613 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
619 //===---------------------------------------===//
620 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
622 struct StrToOpt : public LibCallOptimization {
623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
624 FunctionType *FT = Callee->getFunctionType();
625 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
626 !FT->getParamType(0)->isPointerTy() ||
627 !FT->getParamType(1)->isPointerTy())
630 Value *EndPtr = CI->getArgOperand(1);
631 if (isa<ConstantPointerNull>(EndPtr)) {
632 // With a null EndPtr, this function won't capture the main argument.
633 // It would be readonly too, except that it still may write to errno.
634 CI->addAttribute(1, Attribute::NoCapture);
641 //===---------------------------------------===//
642 // 'strspn' Optimizations
644 struct StrSpnOpt : public LibCallOptimization {
645 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
646 FunctionType *FT = Callee->getFunctionType();
647 if (FT->getNumParams() != 2 ||
648 FT->getParamType(0) != B.getInt8PtrTy() ||
649 FT->getParamType(1) != FT->getParamType(0) ||
650 !FT->getReturnType()->isIntegerTy())
654 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
655 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
657 // strspn(s, "") -> 0
658 // strspn("", s) -> 0
659 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
660 return Constant::getNullValue(CI->getType());
663 if (HasS1 && HasS2) {
664 size_t Pos = S1.find_first_not_of(S2);
665 if (Pos == StringRef::npos) Pos = S1.size();
666 return ConstantInt::get(CI->getType(), Pos);
673 //===---------------------------------------===//
674 // 'strcspn' Optimizations
676 struct StrCSpnOpt : public LibCallOptimization {
677 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
678 FunctionType *FT = Callee->getFunctionType();
679 if (FT->getNumParams() != 2 ||
680 FT->getParamType(0) != B.getInt8PtrTy() ||
681 FT->getParamType(1) != FT->getParamType(0) ||
682 !FT->getReturnType()->isIntegerTy())
686 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
687 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
689 // strcspn("", s) -> 0
690 if (HasS1 && S1.empty())
691 return Constant::getNullValue(CI->getType());
694 if (HasS1 && HasS2) {
695 size_t Pos = S1.find_first_of(S2);
696 if (Pos == StringRef::npos) Pos = S1.size();
697 return ConstantInt::get(CI->getType(), Pos);
700 // strcspn(s, "") -> strlen(s)
701 if (TD && HasS2 && S2.empty())
702 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
708 //===---------------------------------------===//
709 // 'strstr' Optimizations
711 struct StrStrOpt : public LibCallOptimization {
712 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
713 FunctionType *FT = Callee->getFunctionType();
714 if (FT->getNumParams() != 2 ||
715 !FT->getParamType(0)->isPointerTy() ||
716 !FT->getParamType(1)->isPointerTy() ||
717 !FT->getReturnType()->isPointerTy())
720 // fold strstr(x, x) -> x.
721 if (CI->getArgOperand(0) == CI->getArgOperand(1))
722 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
724 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
725 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
726 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
729 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
733 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
735 ICmpInst *Old = cast<ICmpInst>(*UI++);
736 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
737 ConstantInt::getNullValue(StrNCmp->getType()),
739 Old->replaceAllUsesWith(Cmp);
740 Old->eraseFromParent();
745 // See if either input string is a constant string.
746 StringRef SearchStr, ToFindStr;
747 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
748 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
750 // fold strstr(x, "") -> x.
751 if (HasStr2 && ToFindStr.empty())
752 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
754 // If both strings are known, constant fold it.
755 if (HasStr1 && HasStr2) {
756 std::string::size_type Offset = SearchStr.find(ToFindStr);
758 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
759 return Constant::getNullValue(CI->getType());
761 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
762 Value *Result = CastToCStr(CI->getArgOperand(0), B);
763 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
764 return B.CreateBitCast(Result, CI->getType());
767 // fold strstr(x, "y") -> strchr(x, 'y').
768 if (HasStr2 && ToFindStr.size() == 1) {
769 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
770 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
777 //===---------------------------------------===//
778 // 'memcmp' Optimizations
780 struct MemCmpOpt : public LibCallOptimization {
781 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
782 FunctionType *FT = Callee->getFunctionType();
783 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
785 !FT->getReturnType()->isIntegerTy(32))
788 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
790 if (LHS == RHS) // memcmp(s,s,x) -> 0
791 return Constant::getNullValue(CI->getType());
793 // Make sure we have a constant length.
794 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
796 uint64_t Len = LenC->getZExtValue();
798 if (Len == 0) // memcmp(s1,s2,0) -> 0
799 return Constant::getNullValue(CI->getType());
801 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
803 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
804 CI->getType(), "lhsv");
805 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
806 CI->getType(), "rhsv");
807 return B.CreateSub(LHSV, RHSV, "chardiff");
810 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
811 StringRef LHSStr, RHSStr;
812 if (getConstantStringInfo(LHS, LHSStr) &&
813 getConstantStringInfo(RHS, RHSStr)) {
814 // Make sure we're not reading out-of-bounds memory.
815 if (Len > LHSStr.size() || Len > RHSStr.size())
817 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
818 return ConstantInt::get(CI->getType(), Ret);
825 //===---------------------------------------===//
826 // 'memcpy' Optimizations
828 struct MemCpyOpt : public LibCallOptimization {
829 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
830 // These optimizations require TargetData.
833 FunctionType *FT = Callee->getFunctionType();
834 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
835 !FT->getParamType(0)->isPointerTy() ||
836 !FT->getParamType(1)->isPointerTy() ||
837 FT->getParamType(2) != TD->getIntPtrType(*Context))
840 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
841 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
842 CI->getArgOperand(2), 1);
843 return CI->getArgOperand(0);
847 //===---------------------------------------===//
848 // 'memmove' Optimizations
850 struct MemMoveOpt : public LibCallOptimization {
851 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
852 // These optimizations require TargetData.
855 FunctionType *FT = Callee->getFunctionType();
856 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
857 !FT->getParamType(0)->isPointerTy() ||
858 !FT->getParamType(1)->isPointerTy() ||
859 FT->getParamType(2) != TD->getIntPtrType(*Context))
862 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
863 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
864 CI->getArgOperand(2), 1);
865 return CI->getArgOperand(0);
869 //===---------------------------------------===//
870 // 'memset' Optimizations
872 struct MemSetOpt : public LibCallOptimization {
873 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
874 // These optimizations require TargetData.
877 FunctionType *FT = Callee->getFunctionType();
878 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
879 !FT->getParamType(0)->isPointerTy() ||
880 !FT->getParamType(1)->isIntegerTy() ||
881 FT->getParamType(2) != TD->getIntPtrType(*Context))
884 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
885 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
886 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
887 return CI->getArgOperand(0);
891 //===----------------------------------------------------------------------===//
892 // Math Library Optimizations
893 //===----------------------------------------------------------------------===//
895 //===---------------------------------------===//
896 // 'cos*' Optimizations
898 struct CosOpt : public LibCallOptimization {
899 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
900 FunctionType *FT = Callee->getFunctionType();
901 // Just make sure this has 1 argument of FP type, which matches the
903 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
904 !FT->getParamType(0)->isFloatingPointTy())
908 Value *Op1 = CI->getArgOperand(0);
909 if (BinaryOperator::isFNeg(Op1)) {
910 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
911 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
917 //===---------------------------------------===//
918 // 'pow*' Optimizations
920 struct PowOpt : public LibCallOptimization {
921 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
922 FunctionType *FT = Callee->getFunctionType();
923 // Just make sure this has 2 arguments of the same FP type, which match the
925 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
926 FT->getParamType(0) != FT->getParamType(1) ||
927 !FT->getParamType(0)->isFloatingPointTy())
930 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
931 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
932 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
934 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
935 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
938 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
939 if (Op2C == 0) return 0;
941 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
942 return ConstantFP::get(CI->getType(), 1.0);
944 if (Op2C->isExactlyValue(0.5)) {
945 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
946 // This is faster than calling pow, and still handles negative zero
947 // and negative infinity correctly.
948 // TODO: In fast-math mode, this could be just sqrt(x).
949 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
950 Value *Inf = ConstantFP::getInfinity(CI->getType());
951 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
952 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
953 Callee->getAttributes());
954 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
955 Callee->getAttributes());
956 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
957 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
961 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
963 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
964 return B.CreateFMul(Op1, Op1, "pow2");
965 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
966 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
972 //===---------------------------------------===//
973 // 'exp2' Optimizations
975 struct Exp2Opt : public LibCallOptimization {
976 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
977 FunctionType *FT = Callee->getFunctionType();
978 // Just make sure this has 1 argument of FP type, which matches the
980 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
981 !FT->getParamType(0)->isFloatingPointTy())
984 Value *Op = CI->getArgOperand(0);
985 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
986 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
988 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
989 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
990 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
991 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
992 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
993 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
998 if (Op->getType()->isFloatTy())
1000 else if (Op->getType()->isDoubleTy())
1005 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1006 if (!Op->getType()->isFloatTy())
1007 One = ConstantExpr::getFPExtend(One, Op->getType());
1009 Module *M = Caller->getParent();
1010 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1012 B.getInt32Ty(), NULL);
1013 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1014 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1015 CI->setCallingConv(F->getCallingConv());
1023 //===---------------------------------------===//
1024 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1026 struct UnaryDoubleFPOpt : public LibCallOptimization {
1027 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1028 FunctionType *FT = Callee->getFunctionType();
1029 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1030 !FT->getParamType(0)->isDoubleTy())
1033 // If this is something like 'floor((double)floatval)', convert to floorf.
1034 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1035 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1038 // floor((double)floatval) -> (double)floorf(floatval)
1039 Value *V = Cast->getOperand(0);
1040 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1041 return B.CreateFPExt(V, B.getDoubleTy());
1045 //===----------------------------------------------------------------------===//
1046 // Integer Optimizations
1047 //===----------------------------------------------------------------------===//
1049 //===---------------------------------------===//
1050 // 'ffs*' Optimizations
1052 struct FFSOpt : public LibCallOptimization {
1053 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1054 FunctionType *FT = Callee->getFunctionType();
1055 // Just make sure this has 2 arguments of the same FP type, which match the
1057 if (FT->getNumParams() != 1 ||
1058 !FT->getReturnType()->isIntegerTy(32) ||
1059 !FT->getParamType(0)->isIntegerTy())
1062 Value *Op = CI->getArgOperand(0);
1065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1066 if (CI->getValue() == 0) // ffs(0) -> 0.
1067 return Constant::getNullValue(CI->getType());
1068 // ffs(c) -> cttz(c)+1
1069 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1072 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1073 Type *ArgType = Op->getType();
1074 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1075 Intrinsic::cttz, ArgType);
1076 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1077 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1078 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1080 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1081 return B.CreateSelect(Cond, V, B.getInt32(0));
1085 //===---------------------------------------===//
1086 // 'isdigit' Optimizations
1088 struct IsDigitOpt : public LibCallOptimization {
1089 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1090 FunctionType *FT = Callee->getFunctionType();
1091 // We require integer(i32)
1092 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1093 !FT->getParamType(0)->isIntegerTy(32))
1096 // isdigit(c) -> (c-'0') <u 10
1097 Value *Op = CI->getArgOperand(0);
1098 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1099 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1100 return B.CreateZExt(Op, CI->getType());
1104 //===---------------------------------------===//
1105 // 'isascii' Optimizations
1107 struct IsAsciiOpt : public LibCallOptimization {
1108 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1109 FunctionType *FT = Callee->getFunctionType();
1110 // We require integer(i32)
1111 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1112 !FT->getParamType(0)->isIntegerTy(32))
1115 // isascii(c) -> c <u 128
1116 Value *Op = CI->getArgOperand(0);
1117 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1118 return B.CreateZExt(Op, CI->getType());
1122 //===---------------------------------------===//
1123 // 'abs', 'labs', 'llabs' Optimizations
1125 struct AbsOpt : public LibCallOptimization {
1126 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1127 FunctionType *FT = Callee->getFunctionType();
1128 // We require integer(integer) where the types agree.
1129 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1130 FT->getParamType(0) != FT->getReturnType())
1133 // abs(x) -> x >s -1 ? x : -x
1134 Value *Op = CI->getArgOperand(0);
1135 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1137 Value *Neg = B.CreateNeg(Op, "neg");
1138 return B.CreateSelect(Pos, Op, Neg);
1143 //===---------------------------------------===//
1144 // 'toascii' Optimizations
1146 struct ToAsciiOpt : public LibCallOptimization {
1147 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1148 FunctionType *FT = Callee->getFunctionType();
1149 // We require i32(i32)
1150 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1151 !FT->getParamType(0)->isIntegerTy(32))
1154 // isascii(c) -> c & 0x7f
1155 return B.CreateAnd(CI->getArgOperand(0),
1156 ConstantInt::get(CI->getType(),0x7F));
1160 //===----------------------------------------------------------------------===//
1161 // Formatting and IO Optimizations
1162 //===----------------------------------------------------------------------===//
1164 //===---------------------------------------===//
1165 // 'printf' Optimizations
1167 struct PrintFOpt : public LibCallOptimization {
1168 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1170 // Check for a fixed format string.
1171 StringRef FormatStr;
1172 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1175 // Empty format string -> noop.
1176 if (FormatStr.empty()) // Tolerate printf's declared void.
1177 return CI->use_empty() ? (Value*)CI :
1178 ConstantInt::get(CI->getType(), 0);
1180 // Do not do any of the following transformations if the printf return value
1181 // is used, in general the printf return value is not compatible with either
1182 // putchar() or puts().
1183 if (!CI->use_empty())
1186 // printf("x") -> putchar('x'), even for '%'.
1187 if (FormatStr.size() == 1) {
1188 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1189 if (CI->use_empty() || !Res) return Res;
1190 return B.CreateIntCast(Res, CI->getType(), true);
1193 // printf("foo\n") --> puts("foo")
1194 if (FormatStr[FormatStr.size()-1] == '\n' &&
1195 FormatStr.find('%') == std::string::npos) { // no format characters.
1196 // Create a string literal with no \n on it. We expect the constant merge
1197 // pass to be run after this pass, to merge duplicate strings.
1198 FormatStr = FormatStr.drop_back();
1199 Value *GV = B.CreateGlobalString(FormatStr, "str");
1200 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1201 return (CI->use_empty() || !NewCI) ?
1203 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1206 // Optimize specific format strings.
1207 // printf("%c", chr) --> putchar(chr)
1208 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1209 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1210 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1212 if (CI->use_empty() || !Res) return Res;
1213 return B.CreateIntCast(Res, CI->getType(), true);
1216 // printf("%s\n", str) --> puts(str)
1217 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1218 CI->getArgOperand(1)->getType()->isPointerTy()) {
1219 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1224 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1225 // Require one fixed pointer argument and an integer/void result.
1226 FunctionType *FT = Callee->getFunctionType();
1227 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1228 !(FT->getReturnType()->isIntegerTy() ||
1229 FT->getReturnType()->isVoidTy()))
1232 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1236 // printf(format, ...) -> iprintf(format, ...) if no floating point
1238 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1239 Module *M = B.GetInsertBlock()->getParent()->getParent();
1240 Constant *IPrintFFn =
1241 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1242 CallInst *New = cast<CallInst>(CI->clone());
1243 New->setCalledFunction(IPrintFFn);
1251 //===---------------------------------------===//
1252 // 'sprintf' Optimizations
1254 struct SPrintFOpt : public LibCallOptimization {
1255 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1257 // Check for a fixed format string.
1258 StringRef FormatStr;
1259 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1262 // If we just have a format string (nothing else crazy) transform it.
1263 if (CI->getNumArgOperands() == 2) {
1264 // Make sure there's no % in the constant array. We could try to handle
1265 // %% -> % in the future if we cared.
1266 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1267 if (FormatStr[i] == '%')
1268 return 0; // we found a format specifier, bail out.
1270 // These optimizations require TargetData.
1273 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1274 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1275 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1276 FormatStr.size() + 1), 1); // nul byte.
1277 return ConstantInt::get(CI->getType(), FormatStr.size());
1280 // The remaining optimizations require the format string to be "%s" or "%c"
1281 // and have an extra operand.
1282 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1283 CI->getNumArgOperands() < 3)
1286 // Decode the second character of the format string.
1287 if (FormatStr[1] == 'c') {
1288 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1289 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1290 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1291 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1292 B.CreateStore(V, Ptr);
1293 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1294 B.CreateStore(B.getInt8(0), Ptr);
1296 return ConstantInt::get(CI->getType(), 1);
1299 if (FormatStr[1] == 's') {
1300 // These optimizations require TargetData.
1303 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1304 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1306 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1309 Value *IncLen = B.CreateAdd(Len,
1310 ConstantInt::get(Len->getType(), 1),
1312 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1314 // The sprintf result is the unincremented number of bytes in the string.
1315 return B.CreateIntCast(Len, CI->getType(), false);
1320 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1321 // Require two fixed pointer arguments and an integer result.
1322 FunctionType *FT = Callee->getFunctionType();
1323 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1324 !FT->getParamType(1)->isPointerTy() ||
1325 !FT->getReturnType()->isIntegerTy())
1328 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1332 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1334 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1335 Module *M = B.GetInsertBlock()->getParent()->getParent();
1336 Constant *SIPrintFFn =
1337 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1338 CallInst *New = cast<CallInst>(CI->clone());
1339 New->setCalledFunction(SIPrintFFn);
1347 //===---------------------------------------===//
1348 // 'fwrite' Optimizations
1350 struct FWriteOpt : public LibCallOptimization {
1351 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1352 // Require a pointer, an integer, an integer, a pointer, returning integer.
1353 FunctionType *FT = Callee->getFunctionType();
1354 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1355 !FT->getParamType(1)->isIntegerTy() ||
1356 !FT->getParamType(2)->isIntegerTy() ||
1357 !FT->getParamType(3)->isPointerTy() ||
1358 !FT->getReturnType()->isIntegerTy())
1361 // Get the element size and count.
1362 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1363 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1364 if (!SizeC || !CountC) return 0;
1365 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1367 // If this is writing zero records, remove the call (it's a noop).
1369 return ConstantInt::get(CI->getType(), 0);
1371 // If this is writing one byte, turn it into fputc.
1372 // This optimisation is only valid, if the return value is unused.
1373 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1374 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1375 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1376 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1383 //===---------------------------------------===//
1384 // 'fputs' Optimizations
1386 struct FPutsOpt : public LibCallOptimization {
1387 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1388 // These optimizations require TargetData.
1391 // Require two pointers. Also, we can't optimize if return value is used.
1392 FunctionType *FT = Callee->getFunctionType();
1393 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1394 !FT->getParamType(1)->isPointerTy() ||
1398 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1399 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1401 // Known to have no uses (see above).
1402 return EmitFWrite(CI->getArgOperand(0),
1403 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1404 CI->getArgOperand(1), B, TD, TLI);
1408 //===---------------------------------------===//
1409 // 'fprintf' Optimizations
1411 struct FPrintFOpt : public LibCallOptimization {
1412 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1414 // All the optimizations depend on the format string.
1415 StringRef FormatStr;
1416 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1419 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1420 if (CI->getNumArgOperands() == 2) {
1421 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1422 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1423 return 0; // We found a format specifier.
1425 // These optimizations require TargetData.
1428 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1429 ConstantInt::get(TD->getIntPtrType(*Context),
1431 CI->getArgOperand(0), B, TD, TLI);
1432 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
1435 // The remaining optimizations require the format string to be "%s" or "%c"
1436 // and have an extra operand.
1437 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1438 CI->getNumArgOperands() < 3)
1441 // Decode the second character of the format string.
1442 if (FormatStr[1] == 'c') {
1443 // fprintf(F, "%c", chr) --> fputc(chr, F)
1444 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1445 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1447 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1450 if (FormatStr[1] == 's') {
1451 // fprintf(F, "%s", str) --> fputs(str, F)
1452 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1454 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1459 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1460 // Require two fixed paramters as pointers and integer result.
1461 FunctionType *FT = Callee->getFunctionType();
1462 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1463 !FT->getParamType(1)->isPointerTy() ||
1464 !FT->getReturnType()->isIntegerTy())
1467 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1471 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1472 // floating point arguments.
1473 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1474 Module *M = B.GetInsertBlock()->getParent()->getParent();
1475 Constant *FIPrintFFn =
1476 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1477 CallInst *New = cast<CallInst>(CI->clone());
1478 New->setCalledFunction(FIPrintFFn);
1486 //===---------------------------------------===//
1487 // 'puts' Optimizations
1489 struct PutsOpt : public LibCallOptimization {
1490 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1491 // Require one fixed pointer argument and an integer/void result.
1492 FunctionType *FT = Callee->getFunctionType();
1493 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1494 !(FT->getReturnType()->isIntegerTy() ||
1495 FT->getReturnType()->isVoidTy()))
1498 // Check for a constant string.
1500 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1503 if (Str.empty() && CI->use_empty()) {
1504 // puts("") -> putchar('\n')
1505 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1506 if (CI->use_empty() || !Res) return Res;
1507 return B.CreateIntCast(Res, CI->getType(), true);
1514 } // end anonymous namespace.
1516 //===----------------------------------------------------------------------===//
1517 // SimplifyLibCalls Pass Implementation
1518 //===----------------------------------------------------------------------===//
1521 /// This pass optimizes well known library functions from libc and libm.
1523 class SimplifyLibCalls : public FunctionPass {
1524 TargetLibraryInfo *TLI;
1526 StringMap<LibCallOptimization*> Optimizations;
1527 // String and Memory LibCall Optimizations
1528 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1529 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1530 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1531 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1533 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
1534 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
1535 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1536 // Math Library Optimizations
1537 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1538 // Integer Optimizations
1539 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1541 // Formatting and IO Optimizations
1542 SPrintFOpt SPrintF; PrintFOpt PrintF;
1543 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1546 bool Modified; // This is only used by doInitialization.
1548 static char ID; // Pass identification
1549 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
1550 StpCpy(false), StpCpyChk(true) {
1551 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1553 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
1554 void InitOptimizations();
1555 bool runOnFunction(Function &F);
1557 void setDoesNotAccessMemory(Function &F);
1558 void setOnlyReadsMemory(Function &F);
1559 void setDoesNotThrow(Function &F);
1560 void setDoesNotCapture(Function &F, unsigned n);
1561 void setDoesNotAlias(Function &F, unsigned n);
1562 bool doInitialization(Module &M);
1564 void inferPrototypeAttributes(Function &F);
1565 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1566 AU.addRequired<TargetLibraryInfo>();
1569 } // end anonymous namespace.
1571 char SimplifyLibCalls::ID = 0;
1573 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1574 "Simplify well-known library calls", false, false)
1575 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1576 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1577 "Simplify well-known library calls", false, false)
1579 // Public interface to the Simplify LibCalls pass.
1580 FunctionPass *llvm::createSimplifyLibCallsPass() {
1581 return new SimplifyLibCalls();
1584 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1586 Optimizations[TLI->getName(F)] = Opt;
1589 /// Optimizations - Populate the Optimizations map with all the optimizations
1591 void SimplifyLibCalls::InitOptimizations() {
1592 // String and Memory LibCall Optimizations
1593 Optimizations["strcat"] = &StrCat;
1594 Optimizations["strncat"] = &StrNCat;
1595 Optimizations["strchr"] = &StrChr;
1596 Optimizations["strrchr"] = &StrRChr;
1597 Optimizations["strcmp"] = &StrCmp;
1598 Optimizations["strncmp"] = &StrNCmp;
1599 Optimizations["strcpy"] = &StrCpy;
1600 Optimizations["strncpy"] = &StrNCpy;
1601 Optimizations["stpcpy"] = &StpCpy;
1602 Optimizations["strlen"] = &StrLen;
1603 Optimizations["strpbrk"] = &StrPBrk;
1604 Optimizations["strtol"] = &StrTo;
1605 Optimizations["strtod"] = &StrTo;
1606 Optimizations["strtof"] = &StrTo;
1607 Optimizations["strtoul"] = &StrTo;
1608 Optimizations["strtoll"] = &StrTo;
1609 Optimizations["strtold"] = &StrTo;
1610 Optimizations["strtoull"] = &StrTo;
1611 Optimizations["strspn"] = &StrSpn;
1612 Optimizations["strcspn"] = &StrCSpn;
1613 Optimizations["strstr"] = &StrStr;
1614 Optimizations["memcmp"] = &MemCmp;
1615 AddOpt(LibFunc::memcpy, &MemCpy);
1616 Optimizations["memmove"] = &MemMove;
1617 AddOpt(LibFunc::memset, &MemSet);
1619 // _chk variants of String and Memory LibCall Optimizations.
1620 Optimizations["__strcpy_chk"] = &StrCpyChk;
1621 Optimizations["__stpcpy_chk"] = &StpCpyChk;
1623 // Math Library Optimizations
1624 Optimizations["cosf"] = &Cos;
1625 Optimizations["cos"] = &Cos;
1626 Optimizations["cosl"] = &Cos;
1627 Optimizations["powf"] = &Pow;
1628 Optimizations["pow"] = &Pow;
1629 Optimizations["powl"] = &Pow;
1630 Optimizations["llvm.pow.f32"] = &Pow;
1631 Optimizations["llvm.pow.f64"] = &Pow;
1632 Optimizations["llvm.pow.f80"] = &Pow;
1633 Optimizations["llvm.pow.f128"] = &Pow;
1634 Optimizations["llvm.pow.ppcf128"] = &Pow;
1635 Optimizations["exp2l"] = &Exp2;
1636 Optimizations["exp2"] = &Exp2;
1637 Optimizations["exp2f"] = &Exp2;
1638 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1639 Optimizations["llvm.exp2.f128"] = &Exp2;
1640 Optimizations["llvm.exp2.f80"] = &Exp2;
1641 Optimizations["llvm.exp2.f64"] = &Exp2;
1642 Optimizations["llvm.exp2.f32"] = &Exp2;
1644 if (TLI->has(LibFunc::fabs) && TLI->has(LibFunc::fabsf))
1645 Optimizations["fabs"] = &UnaryDoubleFP;
1646 if (TLI->has(LibFunc::floor) && TLI->has(LibFunc::floorf))
1647 Optimizations["floor"] = &UnaryDoubleFP;
1648 if (TLI->has(LibFunc::ceil) && TLI->has(LibFunc::ceilf))
1649 Optimizations["ceil"] = &UnaryDoubleFP;
1650 if (TLI->has(LibFunc::round) && TLI->has(LibFunc::roundf))
1651 Optimizations["round"] = &UnaryDoubleFP;
1652 if (TLI->has(LibFunc::rint) && TLI->has(LibFunc::rintf))
1653 Optimizations["rint"] = &UnaryDoubleFP;
1654 if (TLI->has(LibFunc::nearbyint) && TLI->has(LibFunc::nearbyintf))
1655 Optimizations["nearbyint"] = &UnaryDoubleFP;
1656 if (TLI->has(LibFunc::trunc) && TLI->has(LibFunc::truncf))
1657 Optimizations["trunc"] = &UnaryDoubleFP;
1659 // Integer Optimizations
1660 Optimizations["ffs"] = &FFS;
1661 Optimizations["ffsl"] = &FFS;
1662 Optimizations["ffsll"] = &FFS;
1663 Optimizations["abs"] = &Abs;
1664 Optimizations["labs"] = &Abs;
1665 Optimizations["llabs"] = &Abs;
1666 Optimizations["isdigit"] = &IsDigit;
1667 Optimizations["isascii"] = &IsAscii;
1668 Optimizations["toascii"] = &ToAscii;
1670 // Formatting and IO Optimizations
1671 Optimizations["sprintf"] = &SPrintF;
1672 Optimizations["printf"] = &PrintF;
1673 AddOpt(LibFunc::fwrite, &FWrite);
1674 AddOpt(LibFunc::fputs, &FPuts);
1675 Optimizations["fprintf"] = &FPrintF;
1676 Optimizations["puts"] = &Puts;
1680 /// runOnFunction - Top level algorithm.
1682 bool SimplifyLibCalls::runOnFunction(Function &F) {
1683 TLI = &getAnalysis<TargetLibraryInfo>();
1685 if (Optimizations.empty())
1686 InitOptimizations();
1688 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1690 IRBuilder<> Builder(F.getContext());
1692 bool Changed = false;
1693 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1694 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1695 // Ignore non-calls.
1696 CallInst *CI = dyn_cast<CallInst>(I++);
1699 // Ignore indirect calls and calls to non-external functions.
1700 Function *Callee = CI->getCalledFunction();
1701 if (Callee == 0 || !Callee->isDeclaration() ||
1702 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1705 // Ignore unknown calls.
1706 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1709 // Set the builder to the instruction after the call.
1710 Builder.SetInsertPoint(BB, I);
1712 // Use debug location of CI for all new instructions.
1713 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1715 // Try to optimize this call.
1716 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
1717 if (Result == 0) continue;
1719 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1720 dbgs() << " into: " << *Result << "\n");
1722 // Something changed!
1726 // Inspect the instruction after the call (which was potentially just
1730 if (CI != Result && !CI->use_empty()) {
1731 CI->replaceAllUsesWith(Result);
1732 if (!Result->hasName())
1733 Result->takeName(CI);
1735 CI->eraseFromParent();
1741 // Utility methods for doInitialization.
1743 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1744 if (!F.doesNotAccessMemory()) {
1745 F.setDoesNotAccessMemory();
1750 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1751 if (!F.onlyReadsMemory()) {
1752 F.setOnlyReadsMemory();
1757 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1758 if (!F.doesNotThrow()) {
1759 F.setDoesNotThrow();
1764 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1765 if (!F.doesNotCapture(n)) {
1766 F.setDoesNotCapture(n);
1771 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1772 if (!F.doesNotAlias(n)) {
1773 F.setDoesNotAlias(n);
1780 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1781 FunctionType *FTy = F.getFunctionType();
1783 StringRef Name = F.getName();
1786 if (Name == "strlen") {
1787 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1789 setOnlyReadsMemory(F);
1791 setDoesNotCapture(F, 1);
1792 } else if (Name == "strchr" ||
1793 Name == "strrchr") {
1794 if (FTy->getNumParams() != 2 ||
1795 !FTy->getParamType(0)->isPointerTy() ||
1796 !FTy->getParamType(1)->isIntegerTy())
1798 setOnlyReadsMemory(F);
1800 } else if (Name == "strcpy" ||
1806 Name == "strtoul" ||
1807 Name == "strtoll" ||
1808 Name == "strtold" ||
1809 Name == "strncat" ||
1810 Name == "strncpy" ||
1811 Name == "stpncpy" ||
1812 Name == "strtoull") {
1813 if (FTy->getNumParams() < 2 ||
1814 !FTy->getParamType(1)->isPointerTy())
1817 setDoesNotCapture(F, 2);
1818 } else if (Name == "strxfrm") {
1819 if (FTy->getNumParams() != 3 ||
1820 !FTy->getParamType(0)->isPointerTy() ||
1821 !FTy->getParamType(1)->isPointerTy())
1824 setDoesNotCapture(F, 1);
1825 setDoesNotCapture(F, 2);
1826 } else if (Name == "strcmp" ||
1828 Name == "strncmp" ||
1829 Name == "strcspn" ||
1830 Name == "strcoll" ||
1831 Name == "strcasecmp" ||
1832 Name == "strncasecmp") {
1833 if (FTy->getNumParams() < 2 ||
1834 !FTy->getParamType(0)->isPointerTy() ||
1835 !FTy->getParamType(1)->isPointerTy())
1837 setOnlyReadsMemory(F);
1839 setDoesNotCapture(F, 1);
1840 setDoesNotCapture(F, 2);
1841 } else if (Name == "strstr" ||
1842 Name == "strpbrk") {
1843 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1845 setOnlyReadsMemory(F);
1847 setDoesNotCapture(F, 2);
1848 } else if (Name == "strtok" ||
1849 Name == "strtok_r") {
1850 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1853 setDoesNotCapture(F, 2);
1854 } else if (Name == "scanf" ||
1856 Name == "setvbuf") {
1857 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1860 setDoesNotCapture(F, 1);
1861 } else if (Name == "strdup" ||
1862 Name == "strndup") {
1863 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1864 !FTy->getParamType(0)->isPointerTy())
1867 setDoesNotAlias(F, 0);
1868 setDoesNotCapture(F, 1);
1869 } else if (Name == "stat" ||
1871 Name == "sprintf" ||
1872 Name == "statvfs") {
1873 if (FTy->getNumParams() < 2 ||
1874 !FTy->getParamType(0)->isPointerTy() ||
1875 !FTy->getParamType(1)->isPointerTy())
1878 setDoesNotCapture(F, 1);
1879 setDoesNotCapture(F, 2);
1880 } else if (Name == "snprintf") {
1881 if (FTy->getNumParams() != 3 ||
1882 !FTy->getParamType(0)->isPointerTy() ||
1883 !FTy->getParamType(2)->isPointerTy())
1886 setDoesNotCapture(F, 1);
1887 setDoesNotCapture(F, 3);
1888 } else if (Name == "setitimer") {
1889 if (FTy->getNumParams() != 3 ||
1890 !FTy->getParamType(1)->isPointerTy() ||
1891 !FTy->getParamType(2)->isPointerTy())
1894 setDoesNotCapture(F, 2);
1895 setDoesNotCapture(F, 3);
1896 } else if (Name == "system") {
1897 if (FTy->getNumParams() != 1 ||
1898 !FTy->getParamType(0)->isPointerTy())
1900 // May throw; "system" is a valid pthread cancellation point.
1901 setDoesNotCapture(F, 1);
1905 if (Name == "malloc") {
1906 if (FTy->getNumParams() != 1 ||
1907 !FTy->getReturnType()->isPointerTy())
1910 setDoesNotAlias(F, 0);
1911 } else if (Name == "memcmp") {
1912 if (FTy->getNumParams() != 3 ||
1913 !FTy->getParamType(0)->isPointerTy() ||
1914 !FTy->getParamType(1)->isPointerTy())
1916 setOnlyReadsMemory(F);
1918 setDoesNotCapture(F, 1);
1919 setDoesNotCapture(F, 2);
1920 } else if (Name == "memchr" ||
1921 Name == "memrchr") {
1922 if (FTy->getNumParams() != 3)
1924 setOnlyReadsMemory(F);
1926 } else if (Name == "modf" ||
1930 Name == "memccpy" ||
1931 Name == "memmove") {
1932 if (FTy->getNumParams() < 2 ||
1933 !FTy->getParamType(1)->isPointerTy())
1936 setDoesNotCapture(F, 2);
1937 } else if (Name == "memalign") {
1938 if (!FTy->getReturnType()->isPointerTy())
1940 setDoesNotAlias(F, 0);
1941 } else if (Name == "mkdir" ||
1943 if (FTy->getNumParams() == 0 ||
1944 !FTy->getParamType(0)->isPointerTy())
1947 setDoesNotCapture(F, 1);
1951 if (Name == "realloc") {
1952 if (FTy->getNumParams() != 2 ||
1953 !FTy->getParamType(0)->isPointerTy() ||
1954 !FTy->getReturnType()->isPointerTy())
1957 setDoesNotAlias(F, 0);
1958 setDoesNotCapture(F, 1);
1959 } else if (Name == "read") {
1960 if (FTy->getNumParams() != 3 ||
1961 !FTy->getParamType(1)->isPointerTy())
1963 // May throw; "read" is a valid pthread cancellation point.
1964 setDoesNotCapture(F, 2);
1965 } else if (Name == "rmdir" ||
1968 Name == "realpath") {
1969 if (FTy->getNumParams() < 1 ||
1970 !FTy->getParamType(0)->isPointerTy())
1973 setDoesNotCapture(F, 1);
1974 } else if (Name == "rename" ||
1975 Name == "readlink") {
1976 if (FTy->getNumParams() < 2 ||
1977 !FTy->getParamType(0)->isPointerTy() ||
1978 !FTy->getParamType(1)->isPointerTy())
1981 setDoesNotCapture(F, 1);
1982 setDoesNotCapture(F, 2);
1986 if (Name == "write") {
1987 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1989 // May throw; "write" is a valid pthread cancellation point.
1990 setDoesNotCapture(F, 2);
1994 if (Name == "bcopy") {
1995 if (FTy->getNumParams() != 3 ||
1996 !FTy->getParamType(0)->isPointerTy() ||
1997 !FTy->getParamType(1)->isPointerTy())
2000 setDoesNotCapture(F, 1);
2001 setDoesNotCapture(F, 2);
2002 } else if (Name == "bcmp") {
2003 if (FTy->getNumParams() != 3 ||
2004 !FTy->getParamType(0)->isPointerTy() ||
2005 !FTy->getParamType(1)->isPointerTy())
2008 setOnlyReadsMemory(F);
2009 setDoesNotCapture(F, 1);
2010 setDoesNotCapture(F, 2);
2011 } else if (Name == "bzero") {
2012 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2015 setDoesNotCapture(F, 1);
2019 if (Name == "calloc") {
2020 if (FTy->getNumParams() != 2 ||
2021 !FTy->getReturnType()->isPointerTy())
2024 setDoesNotAlias(F, 0);
2025 } else if (Name == "chmod" ||
2027 Name == "ctermid" ||
2028 Name == "clearerr" ||
2029 Name == "closedir") {
2030 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2033 setDoesNotCapture(F, 1);
2037 if (Name == "atoi" ||
2041 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2044 setOnlyReadsMemory(F);
2045 setDoesNotCapture(F, 1);
2046 } else if (Name == "access") {
2047 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2050 setDoesNotCapture(F, 1);
2054 if (Name == "fopen") {
2055 if (FTy->getNumParams() != 2 ||
2056 !FTy->getReturnType()->isPointerTy() ||
2057 !FTy->getParamType(0)->isPointerTy() ||
2058 !FTy->getParamType(1)->isPointerTy())
2061 setDoesNotAlias(F, 0);
2062 setDoesNotCapture(F, 1);
2063 setDoesNotCapture(F, 2);
2064 } else if (Name == "fdopen") {
2065 if (FTy->getNumParams() != 2 ||
2066 !FTy->getReturnType()->isPointerTy() ||
2067 !FTy->getParamType(1)->isPointerTy())
2070 setDoesNotAlias(F, 0);
2071 setDoesNotCapture(F, 2);
2072 } else if (Name == "feof" ||
2082 Name == "fsetpos" ||
2083 Name == "flockfile" ||
2084 Name == "funlockfile" ||
2085 Name == "ftrylockfile") {
2086 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2089 setDoesNotCapture(F, 1);
2090 } else if (Name == "ferror") {
2091 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2094 setDoesNotCapture(F, 1);
2095 setOnlyReadsMemory(F);
2096 } else if (Name == "fputc" ||
2101 Name == "fstatvfs") {
2102 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2105 setDoesNotCapture(F, 2);
2106 } else if (Name == "fgets") {
2107 if (FTy->getNumParams() != 3 ||
2108 !FTy->getParamType(0)->isPointerTy() ||
2109 !FTy->getParamType(2)->isPointerTy())
2112 setDoesNotCapture(F, 3);
2113 } else if (Name == "fread" ||
2115 if (FTy->getNumParams() != 4 ||
2116 !FTy->getParamType(0)->isPointerTy() ||
2117 !FTy->getParamType(3)->isPointerTy())
2120 setDoesNotCapture(F, 1);
2121 setDoesNotCapture(F, 4);
2122 } else if (Name == "fputs" ||
2124 Name == "fprintf" ||
2125 Name == "fgetpos") {
2126 if (FTy->getNumParams() < 2 ||
2127 !FTy->getParamType(0)->isPointerTy() ||
2128 !FTy->getParamType(1)->isPointerTy())
2131 setDoesNotCapture(F, 1);
2132 setDoesNotCapture(F, 2);
2136 if (Name == "getc" ||
2137 Name == "getlogin_r" ||
2138 Name == "getc_unlocked") {
2139 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2142 setDoesNotCapture(F, 1);
2143 } else if (Name == "getenv") {
2144 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2147 setOnlyReadsMemory(F);
2148 setDoesNotCapture(F, 1);
2149 } else if (Name == "gets" ||
2150 Name == "getchar") {
2152 } else if (Name == "getitimer") {
2153 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2156 setDoesNotCapture(F, 2);
2157 } else if (Name == "getpwnam") {
2158 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2161 setDoesNotCapture(F, 1);
2165 if (Name == "ungetc") {
2166 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2169 setDoesNotCapture(F, 2);
2170 } else if (Name == "uname" ||
2172 Name == "unsetenv") {
2173 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2176 setDoesNotCapture(F, 1);
2177 } else if (Name == "utime" ||
2179 if (FTy->getNumParams() != 2 ||
2180 !FTy->getParamType(0)->isPointerTy() ||
2181 !FTy->getParamType(1)->isPointerTy())
2184 setDoesNotCapture(F, 1);
2185 setDoesNotCapture(F, 2);
2189 if (Name == "putc") {
2190 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2193 setDoesNotCapture(F, 2);
2194 } else if (Name == "puts" ||
2197 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2200 setDoesNotCapture(F, 1);
2201 } else if (Name == "pread" ||
2203 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2205 // May throw; these are valid pthread cancellation points.
2206 setDoesNotCapture(F, 2);
2207 } else if (Name == "putchar") {
2209 } else if (Name == "popen") {
2210 if (FTy->getNumParams() != 2 ||
2211 !FTy->getReturnType()->isPointerTy() ||
2212 !FTy->getParamType(0)->isPointerTy() ||
2213 !FTy->getParamType(1)->isPointerTy())
2216 setDoesNotAlias(F, 0);
2217 setDoesNotCapture(F, 1);
2218 setDoesNotCapture(F, 2);
2219 } else if (Name == "pclose") {
2220 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2223 setDoesNotCapture(F, 1);
2227 if (Name == "vscanf") {
2228 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2231 setDoesNotCapture(F, 1);
2232 } else if (Name == "vsscanf" ||
2233 Name == "vfscanf") {
2234 if (FTy->getNumParams() != 3 ||
2235 !FTy->getParamType(1)->isPointerTy() ||
2236 !FTy->getParamType(2)->isPointerTy())
2239 setDoesNotCapture(F, 1);
2240 setDoesNotCapture(F, 2);
2241 } else if (Name == "valloc") {
2242 if (!FTy->getReturnType()->isPointerTy())
2245 setDoesNotAlias(F, 0);
2246 } else if (Name == "vprintf") {
2247 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2250 setDoesNotCapture(F, 1);
2251 } else if (Name == "vfprintf" ||
2252 Name == "vsprintf") {
2253 if (FTy->getNumParams() != 3 ||
2254 !FTy->getParamType(0)->isPointerTy() ||
2255 !FTy->getParamType(1)->isPointerTy())
2258 setDoesNotCapture(F, 1);
2259 setDoesNotCapture(F, 2);
2260 } else if (Name == "vsnprintf") {
2261 if (FTy->getNumParams() != 4 ||
2262 !FTy->getParamType(0)->isPointerTy() ||
2263 !FTy->getParamType(2)->isPointerTy())
2266 setDoesNotCapture(F, 1);
2267 setDoesNotCapture(F, 3);
2271 if (Name == "open") {
2272 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2274 // May throw; "open" is a valid pthread cancellation point.
2275 setDoesNotCapture(F, 1);
2276 } else if (Name == "opendir") {
2277 if (FTy->getNumParams() != 1 ||
2278 !FTy->getReturnType()->isPointerTy() ||
2279 !FTy->getParamType(0)->isPointerTy())
2282 setDoesNotAlias(F, 0);
2283 setDoesNotCapture(F, 1);
2287 if (Name == "tmpfile") {
2288 if (!FTy->getReturnType()->isPointerTy())
2291 setDoesNotAlias(F, 0);
2292 } else if (Name == "times") {
2293 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2296 setDoesNotCapture(F, 1);
2300 if (Name == "htonl" ||
2303 setDoesNotAccessMemory(F);
2307 if (Name == "ntohl" ||
2310 setDoesNotAccessMemory(F);
2314 if (Name == "lstat") {
2315 if (FTy->getNumParams() != 2 ||
2316 !FTy->getParamType(0)->isPointerTy() ||
2317 !FTy->getParamType(1)->isPointerTy())
2320 setDoesNotCapture(F, 1);
2321 setDoesNotCapture(F, 2);
2322 } else if (Name == "lchown") {
2323 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2326 setDoesNotCapture(F, 1);
2330 if (Name == "qsort") {
2331 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2333 // May throw; places call through function pointer.
2334 setDoesNotCapture(F, 4);
2338 if (Name == "__strdup" ||
2339 Name == "__strndup") {
2340 if (FTy->getNumParams() < 1 ||
2341 !FTy->getReturnType()->isPointerTy() ||
2342 !FTy->getParamType(0)->isPointerTy())
2345 setDoesNotAlias(F, 0);
2346 setDoesNotCapture(F, 1);
2347 } else if (Name == "__strtok_r") {
2348 if (FTy->getNumParams() != 3 ||
2349 !FTy->getParamType(1)->isPointerTy())
2352 setDoesNotCapture(F, 2);
2353 } else if (Name == "_IO_getc") {
2354 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2357 setDoesNotCapture(F, 1);
2358 } else if (Name == "_IO_putc") {
2359 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2362 setDoesNotCapture(F, 2);
2366 if (Name == "\1__isoc99_scanf") {
2367 if (FTy->getNumParams() < 1 ||
2368 !FTy->getParamType(0)->isPointerTy())
2371 setDoesNotCapture(F, 1);
2372 } else if (Name == "\1stat64" ||
2373 Name == "\1lstat64" ||
2374 Name == "\1statvfs64" ||
2375 Name == "\1__isoc99_sscanf") {
2376 if (FTy->getNumParams() < 1 ||
2377 !FTy->getParamType(0)->isPointerTy() ||
2378 !FTy->getParamType(1)->isPointerTy())
2381 setDoesNotCapture(F, 1);
2382 setDoesNotCapture(F, 2);
2383 } else if (Name == "\1fopen64") {
2384 if (FTy->getNumParams() != 2 ||
2385 !FTy->getReturnType()->isPointerTy() ||
2386 !FTy->getParamType(0)->isPointerTy() ||
2387 !FTy->getParamType(1)->isPointerTy())
2390 setDoesNotAlias(F, 0);
2391 setDoesNotCapture(F, 1);
2392 setDoesNotCapture(F, 2);
2393 } else if (Name == "\1fseeko64" ||
2394 Name == "\1ftello64") {
2395 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2398 setDoesNotCapture(F, 1);
2399 } else if (Name == "\1tmpfile64") {
2400 if (!FTy->getReturnType()->isPointerTy())
2403 setDoesNotAlias(F, 0);
2404 } else if (Name == "\1fstat64" ||
2405 Name == "\1fstatvfs64") {
2406 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2409 setDoesNotCapture(F, 2);
2410 } else if (Name == "\1open64") {
2411 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2413 // May throw; "open" is a valid pthread cancellation point.
2414 setDoesNotCapture(F, 1);
2420 /// doInitialization - Add attributes to well-known functions.
2422 bool SimplifyLibCalls::doInitialization(Module &M) {
2424 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2426 if (F.isDeclaration() && F.hasName())
2427 inferPrototypeAttributes(F);
2433 // Additional cases that we need to add to this file:
2436 // * cbrt(expN(X)) -> expN(x/3)
2437 // * cbrt(sqrt(x)) -> pow(x,1/6)
2438 // * cbrt(sqrt(x)) -> pow(x,1/9)
2441 // * exp(log(x)) -> x
2444 // * log(exp(x)) -> x
2445 // * log(x**y) -> y*log(x)
2446 // * log(exp(y)) -> y*log(e)
2447 // * log(exp2(y)) -> y*log(2)
2448 // * log(exp10(y)) -> y*log(10)
2449 // * log(sqrt(x)) -> 0.5*log(x)
2450 // * log(pow(x,y)) -> y*log(x)
2452 // lround, lroundf, lroundl:
2453 // * lround(cnst) -> cnst'
2456 // * pow(exp(x),y) -> exp(x*y)
2457 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2458 // * pow(pow(x,y),z)-> pow(x,y*z)
2460 // round, roundf, roundl:
2461 // * round(cnst) -> cnst'
2464 // * signbit(cnst) -> cnst'
2465 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2467 // sqrt, sqrtf, sqrtl:
2468 // * sqrt(expN(x)) -> expN(x*0.5)
2469 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2470 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2473 // * strchr(p, 0) -> strlen(p)
2475 // * tan(atan(x)) -> x
2477 // trunc, truncf, truncl:
2478 // * trunc(cnst) -> cnst'