1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BuildLibCalls.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Config/config.h"
37 STATISTIC(NumSimplified, "Number of library calls simplified");
38 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
40 //===----------------------------------------------------------------------===//
41 // Optimizer Base Class
42 //===----------------------------------------------------------------------===//
44 /// This class is the abstract base class for the set of optimizations that
45 /// corresponds to one library call.
47 class LibCallOptimization {
53 LibCallOptimization() { }
54 virtual ~LibCallOptimization() {}
56 /// CallOptimizer - This pure virtual method is implemented by base classes to
57 /// do various optimizations. If this returns null then no transformation was
58 /// performed. If it returns CI, then it transformed the call and CI is to be
59 /// deleted. If it returns something else, replace CI with the new value and
61 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
64 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
65 Caller = CI->getParent()->getParent();
67 if (CI->getCalledFunction())
68 Context = &CI->getCalledFunction()->getContext();
70 // We never change the calling convention.
71 if (CI->getCallingConv() != llvm::CallingConv::C)
74 return CallOptimizer(CI->getCalledFunction(), CI, B);
77 } // End anonymous namespace.
80 //===----------------------------------------------------------------------===//
82 //===----------------------------------------------------------------------===//
84 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
85 /// value is equal or not-equal to zero.
86 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
87 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
89 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
91 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
94 // Unknown instruction.
100 /// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
101 /// comparisons with With.
102 static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
103 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
105 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
106 if (IC->isEquality() && IC->getOperand(1) == With)
108 // Unknown instruction.
114 //===----------------------------------------------------------------------===//
115 // String and Memory LibCall Optimizations
116 //===----------------------------------------------------------------------===//
118 //===---------------------------------------===//
119 // 'strcat' Optimizations
121 struct StrCatOpt : public LibCallOptimization {
122 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
123 // Verify the "strcat" function prototype.
124 const FunctionType *FT = Callee->getFunctionType();
125 if (FT->getNumParams() != 2 ||
126 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
127 FT->getParamType(0) != FT->getReturnType() ||
128 FT->getParamType(1) != FT->getReturnType())
131 // Extract some information from the instruction
132 Value *Dst = CI->getArgOperand(0);
133 Value *Src = CI->getArgOperand(1);
135 // See if we can get the length of the input string.
136 uint64_t Len = GetStringLength(Src);
137 if (Len == 0) return 0;
138 --Len; // Unbias length.
140 // Handle the simple, do-nothing case: strcat(x, "") -> x
144 // These optimizations require TargetData.
147 EmitStrLenMemCpy(Src, Dst, Len, B);
151 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
152 // We need to find the end of the destination string. That's where the
153 // memory is to be moved to. We just generate a call to strlen.
154 Value *DstLen = EmitStrLen(Dst, B, TD);
156 // Now that we have the destination's length, we must index into the
157 // destination's pointer to get the actual memcpy destination (end of
158 // the string .. we're concatenating).
159 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
161 // We have enough information to now generate the memcpy call to do the
162 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
163 EmitMemCpy(CpyDst, Src,
164 ConstantInt::get(TD->getIntPtrType(*Context), Len+1),
169 //===---------------------------------------===//
170 // 'strncat' Optimizations
172 struct StrNCatOpt : public StrCatOpt {
173 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
174 // Verify the "strncat" function prototype.
175 const FunctionType *FT = Callee->getFunctionType();
176 if (FT->getNumParams() != 3 ||
177 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
178 FT->getParamType(0) != FT->getReturnType() ||
179 FT->getParamType(1) != FT->getReturnType() ||
180 !FT->getParamType(2)->isIntegerTy())
183 // Extract some information from the instruction
184 Value *Dst = CI->getArgOperand(0);
185 Value *Src = CI->getArgOperand(1);
188 // We don't do anything if length is not constant
189 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
190 Len = LengthArg->getZExtValue();
194 // See if we can get the length of the input string.
195 uint64_t SrcLen = GetStringLength(Src);
196 if (SrcLen == 0) return 0;
197 --SrcLen; // Unbias length.
199 // Handle the simple, do-nothing cases:
200 // strncat(x, "", c) -> x
201 // strncat(x, c, 0) -> x
202 if (SrcLen == 0 || Len == 0) return Dst;
204 // These optimizations require TargetData.
207 // We don't optimize this case
208 if (Len < SrcLen) return 0;
210 // strncat(x, s, c) -> strcat(x, s)
211 // s is constant so the strcat can be optimized further
212 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
217 //===---------------------------------------===//
218 // 'strchr' Optimizations
220 struct StrChrOpt : public LibCallOptimization {
221 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
222 // Verify the "strchr" function prototype.
223 const FunctionType *FT = Callee->getFunctionType();
224 if (FT->getNumParams() != 2 ||
225 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
226 FT->getParamType(0) != FT->getReturnType())
229 Value *SrcStr = CI->getArgOperand(0);
231 // If the second operand is non-constant, see if we can compute the length
232 // of the input string and turn this into memchr.
233 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
235 // These optimizations require TargetData.
238 uint64_t Len = GetStringLength(SrcStr);
239 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
242 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
243 ConstantInt::get(TD->getIntPtrType(*Context), Len),
247 // Otherwise, the character is a constant, see if the first argument is
248 // a string literal. If so, we can constant fold.
250 if (!GetConstantStringInfo(SrcStr, Str))
253 // strchr can find the nul character.
255 char CharValue = CharC->getSExtValue();
257 // Compute the offset.
260 if (i == Str.size()) // Didn't find the char. strchr returns null.
261 return Constant::getNullValue(CI->getType());
262 // Did we find our match?
263 if (Str[i] == CharValue)
268 // strchr(s+n,c) -> gep(s+n+i,c)
269 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
270 return B.CreateGEP(SrcStr, Idx, "strchr");
274 //===---------------------------------------===//
275 // 'strrchr' Optimizations
277 struct StrRChrOpt : public LibCallOptimization {
278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
279 // Verify the "strrchr" function prototype.
280 const FunctionType *FT = Callee->getFunctionType();
281 if (FT->getNumParams() != 2 ||
282 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
283 FT->getParamType(0) != FT->getReturnType())
286 Value *SrcStr = CI->getArgOperand(0);
287 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
289 // Cannot fold anything if we're not looking for a constant.
294 if (!GetConstantStringInfo(SrcStr, Str)) {
295 // strrchr(s, 0) -> strchr(s, 0)
296 if (TD && CharC->isZero())
297 return EmitStrChr(SrcStr, '\0', B, TD);
301 // strrchr can find the nul character.
304 // Compute the offset.
305 size_t I = Str.rfind(CharC->getSExtValue());
306 if (I == std::string::npos) // Didn't find the char. Return null.
307 return Constant::getNullValue(CI->getType());
309 // strrchr(s+n,c) -> gep(s+n+i,c)
310 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), I);
311 return B.CreateGEP(SrcStr, Idx, "strrchr");
315 //===---------------------------------------===//
316 // 'strcmp' Optimizations
318 struct StrCmpOpt : public LibCallOptimization {
319 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
320 // Verify the "strcmp" function prototype.
321 const FunctionType *FT = Callee->getFunctionType();
322 if (FT->getNumParams() != 2 ||
323 !FT->getReturnType()->isIntegerTy(32) ||
324 FT->getParamType(0) != FT->getParamType(1) ||
325 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
328 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
329 if (Str1P == Str2P) // strcmp(x,x) -> 0
330 return ConstantInt::get(CI->getType(), 0);
332 std::string Str1, Str2;
333 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
334 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
336 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
337 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
339 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
340 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
342 // strcmp(x, y) -> cnst (if both x and y are constant strings)
343 if (HasStr1 && HasStr2)
344 return ConstantInt::get(CI->getType(),
345 strcmp(Str1.c_str(),Str2.c_str()));
347 // strcmp(P, "x") -> memcmp(P, "x", 2)
348 uint64_t Len1 = GetStringLength(Str1P);
349 uint64_t Len2 = GetStringLength(Str2P);
351 // These optimizations require TargetData.
354 return EmitMemCmp(Str1P, Str2P,
355 ConstantInt::get(TD->getIntPtrType(*Context),
356 std::min(Len1, Len2)), B, TD);
363 //===---------------------------------------===//
364 // 'strncmp' Optimizations
366 struct StrNCmpOpt : public LibCallOptimization {
367 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
368 // Verify the "strncmp" function prototype.
369 const FunctionType *FT = Callee->getFunctionType();
370 if (FT->getNumParams() != 3 ||
371 !FT->getReturnType()->isIntegerTy(32) ||
372 FT->getParamType(0) != FT->getParamType(1) ||
373 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
374 !FT->getParamType(2)->isIntegerTy())
377 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
378 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
379 return ConstantInt::get(CI->getType(), 0);
381 // Get the length argument if it is constant.
383 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
384 Length = LengthArg->getZExtValue();
388 if (Length == 0) // strncmp(x,y,0) -> 0
389 return ConstantInt::get(CI->getType(), 0);
391 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
392 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
394 std::string Str1, Str2;
395 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
396 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
398 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
399 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
401 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
402 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
404 // strncmp(x, y) -> cnst (if both x and y are constant strings)
405 if (HasStr1 && HasStr2)
406 return ConstantInt::get(CI->getType(),
407 strncmp(Str1.c_str(), Str2.c_str(), Length));
413 //===---------------------------------------===//
414 // 'strcpy' Optimizations
416 struct StrCpyOpt : public LibCallOptimization {
417 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
419 StrCpyOpt(bool c) : OptChkCall(c) {}
421 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
422 // Verify the "strcpy" function prototype.
423 unsigned NumParams = OptChkCall ? 3 : 2;
424 const FunctionType *FT = Callee->getFunctionType();
425 if (FT->getNumParams() != NumParams ||
426 FT->getReturnType() != FT->getParamType(0) ||
427 FT->getParamType(0) != FT->getParamType(1) ||
428 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
431 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
432 if (Dst == Src) // strcpy(x,x) -> x
435 // These optimizations require TargetData.
438 // See if we can get the length of the input string.
439 uint64_t Len = GetStringLength(Src);
440 if (Len == 0) return 0;
442 // We have enough information to now generate the memcpy call to do the
443 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
445 EmitMemCpyChk(Dst, Src,
446 ConstantInt::get(TD->getIntPtrType(*Context), Len),
447 CI->getArgOperand(2), B, TD);
450 ConstantInt::get(TD->getIntPtrType(*Context), Len),
456 //===---------------------------------------===//
457 // 'strncpy' Optimizations
459 struct StrNCpyOpt : public LibCallOptimization {
460 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
461 const FunctionType *FT = Callee->getFunctionType();
462 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
463 FT->getParamType(0) != FT->getParamType(1) ||
464 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
465 !FT->getParamType(2)->isIntegerTy())
468 Value *Dst = CI->getArgOperand(0);
469 Value *Src = CI->getArgOperand(1);
470 Value *LenOp = CI->getArgOperand(2);
472 // See if we can get the length of the input string.
473 uint64_t SrcLen = GetStringLength(Src);
474 if (SrcLen == 0) return 0;
478 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
479 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'),
480 LenOp, false, B, TD);
485 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
486 Len = LengthArg->getZExtValue();
490 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
492 // These optimizations require TargetData.
495 // Let strncpy handle the zero padding
496 if (Len > SrcLen+1) return 0;
498 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
500 ConstantInt::get(TD->getIntPtrType(*Context), Len),
507 //===---------------------------------------===//
508 // 'strlen' Optimizations
510 struct StrLenOpt : public LibCallOptimization {
511 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
512 const FunctionType *FT = Callee->getFunctionType();
513 if (FT->getNumParams() != 1 ||
514 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
515 !FT->getReturnType()->isIntegerTy())
518 Value *Src = CI->getArgOperand(0);
520 // Constant folding: strlen("xyz") -> 3
521 if (uint64_t Len = GetStringLength(Src))
522 return ConstantInt::get(CI->getType(), Len-1);
524 // strlen(x) != 0 --> *x != 0
525 // strlen(x) == 0 --> *x == 0
526 if (IsOnlyUsedInZeroEqualityComparison(CI))
527 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
532 //===---------------------------------------===//
533 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
535 struct StrToOpt : public LibCallOptimization {
536 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
537 const FunctionType *FT = Callee->getFunctionType();
538 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
539 !FT->getParamType(0)->isPointerTy() ||
540 !FT->getParamType(1)->isPointerTy())
543 Value *EndPtr = CI->getArgOperand(1);
544 if (isa<ConstantPointerNull>(EndPtr)) {
545 CI->setOnlyReadsMemory();
546 CI->addAttribute(1, Attribute::NoCapture);
553 //===---------------------------------------===//
554 // 'strstr' Optimizations
556 struct StrStrOpt : public LibCallOptimization {
557 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
558 const FunctionType *FT = Callee->getFunctionType();
559 if (FT->getNumParams() != 2 ||
560 !FT->getParamType(0)->isPointerTy() ||
561 !FT->getParamType(1)->isPointerTy() ||
562 !FT->getReturnType()->isPointerTy())
565 // fold strstr(x, x) -> x.
566 if (CI->getArgOperand(0) == CI->getArgOperand(1))
567 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
569 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
570 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
571 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
572 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
574 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
576 ICmpInst *Old = cast<ICmpInst>(*UI++);
577 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
578 ConstantInt::getNullValue(StrNCmp->getType()),
580 Old->replaceAllUsesWith(Cmp);
581 Old->eraseFromParent();
586 // See if either input string is a constant string.
587 std::string SearchStr, ToFindStr;
588 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
589 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
591 // fold strstr(x, "") -> x.
592 if (HasStr2 && ToFindStr.empty())
593 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
595 // If both strings are known, constant fold it.
596 if (HasStr1 && HasStr2) {
597 std::string::size_type Offset = SearchStr.find(ToFindStr);
599 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
600 return Constant::getNullValue(CI->getType());
602 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
603 Value *Result = CastToCStr(CI->getArgOperand(0), B);
604 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
605 return B.CreateBitCast(Result, CI->getType());
608 // fold strstr(x, "y") -> strchr(x, 'y').
609 if (HasStr2 && ToFindStr.size() == 1)
610 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
611 ToFindStr[0], B, TD), CI->getType());
617 //===---------------------------------------===//
618 // 'memcmp' Optimizations
620 struct MemCmpOpt : public LibCallOptimization {
621 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
622 const FunctionType *FT = Callee->getFunctionType();
623 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
624 !FT->getParamType(1)->isPointerTy() ||
625 !FT->getReturnType()->isIntegerTy(32))
628 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
630 if (LHS == RHS) // memcmp(s,s,x) -> 0
631 return Constant::getNullValue(CI->getType());
633 // Make sure we have a constant length.
634 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
636 uint64_t Len = LenC->getZExtValue();
638 if (Len == 0) // memcmp(s1,s2,0) -> 0
639 return Constant::getNullValue(CI->getType());
641 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
643 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
644 CI->getType(), "lhsv");
645 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
646 CI->getType(), "rhsv");
647 return B.CreateSub(LHSV, RHSV, "chardiff");
650 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
651 std::string LHSStr, RHSStr;
652 if (GetConstantStringInfo(LHS, LHSStr) &&
653 GetConstantStringInfo(RHS, RHSStr)) {
654 // Make sure we're not reading out-of-bounds memory.
655 if (Len > LHSStr.length() || Len > RHSStr.length())
657 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
658 return ConstantInt::get(CI->getType(), Ret);
665 //===---------------------------------------===//
666 // 'memcpy' Optimizations
668 struct MemCpyOpt : public LibCallOptimization {
669 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
670 // These optimizations require TargetData.
673 const FunctionType *FT = Callee->getFunctionType();
674 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
675 !FT->getParamType(0)->isPointerTy() ||
676 !FT->getParamType(1)->isPointerTy() ||
677 FT->getParamType(2) != TD->getIntPtrType(*Context))
680 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
681 EmitMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
682 CI->getArgOperand(2), 1, false, B, TD);
683 return CI->getArgOperand(0);
687 //===---------------------------------------===//
688 // 'memmove' Optimizations
690 struct MemMoveOpt : public LibCallOptimization {
691 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
692 // These optimizations require TargetData.
695 const FunctionType *FT = Callee->getFunctionType();
696 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
697 !FT->getParamType(0)->isPointerTy() ||
698 !FT->getParamType(1)->isPointerTy() ||
699 FT->getParamType(2) != TD->getIntPtrType(*Context))
702 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
703 EmitMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
704 CI->getArgOperand(2), 1, false, B, TD);
705 return CI->getArgOperand(0);
709 //===---------------------------------------===//
710 // 'memset' Optimizations
712 struct MemSetOpt : public LibCallOptimization {
713 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
714 // These optimizations require TargetData.
717 const FunctionType *FT = Callee->getFunctionType();
718 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
719 !FT->getParamType(0)->isPointerTy() ||
720 !FT->getParamType(1)->isIntegerTy() ||
721 FT->getParamType(2) != TD->getIntPtrType(*Context))
724 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
725 Value *Val = B.CreateIntCast(CI->getArgOperand(1),
726 Type::getInt8Ty(*Context), false);
727 EmitMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), false, B, TD);
728 return CI->getArgOperand(0);
732 //===----------------------------------------------------------------------===//
733 // Math Library Optimizations
734 //===----------------------------------------------------------------------===//
736 //===---------------------------------------===//
737 // 'pow*' Optimizations
739 struct PowOpt : public LibCallOptimization {
740 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
741 const FunctionType *FT = Callee->getFunctionType();
742 // Just make sure this has 2 arguments of the same FP type, which match the
744 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
745 FT->getParamType(0) != FT->getParamType(1) ||
746 !FT->getParamType(0)->isFloatingPointTy())
749 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
750 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
751 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
753 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
754 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
757 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
758 if (Op2C == 0) return 0;
760 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
761 return ConstantFP::get(CI->getType(), 1.0);
763 if (Op2C->isExactlyValue(0.5)) {
764 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
765 // This is faster than calling pow, and still handles negative zero
766 // and negative infinite correctly.
767 // TODO: In fast-math mode, this could be just sqrt(x).
768 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
769 Value *Inf = ConstantFP::getInfinity(CI->getType());
770 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
771 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
772 Callee->getAttributes());
773 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
774 Callee->getAttributes());
775 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
776 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
780 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
782 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
783 return B.CreateFMul(Op1, Op1, "pow2");
784 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
785 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
791 //===---------------------------------------===//
792 // 'exp2' Optimizations
794 struct Exp2Opt : public LibCallOptimization {
795 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
796 const FunctionType *FT = Callee->getFunctionType();
797 // Just make sure this has 1 argument of FP type, which matches the
799 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
800 !FT->getParamType(0)->isFloatingPointTy())
803 Value *Op = CI->getArgOperand(0);
804 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
805 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
807 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
808 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
809 LdExpArg = B.CreateSExt(OpC->getOperand(0),
810 Type::getInt32Ty(*Context), "tmp");
811 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
812 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
813 LdExpArg = B.CreateZExt(OpC->getOperand(0),
814 Type::getInt32Ty(*Context), "tmp");
819 if (Op->getType()->isFloatTy())
821 else if (Op->getType()->isDoubleTy())
826 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
827 if (!Op->getType()->isFloatTy())
828 One = ConstantExpr::getFPExtend(One, Op->getType());
830 Module *M = Caller->getParent();
831 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
833 Type::getInt32Ty(*Context),NULL);
834 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
835 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
836 CI->setCallingConv(F->getCallingConv());
844 //===---------------------------------------===//
845 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
847 struct UnaryDoubleFPOpt : public LibCallOptimization {
848 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
849 const FunctionType *FT = Callee->getFunctionType();
850 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
851 !FT->getParamType(0)->isDoubleTy())
854 // If this is something like 'floor((double)floatval)', convert to floorf.
855 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
856 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
859 // floor((double)floatval) -> (double)floorf(floatval)
860 Value *V = Cast->getOperand(0);
861 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
862 Callee->getAttributes());
863 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
867 //===----------------------------------------------------------------------===//
868 // Integer Optimizations
869 //===----------------------------------------------------------------------===//
871 //===---------------------------------------===//
872 // 'ffs*' Optimizations
874 struct FFSOpt : public LibCallOptimization {
875 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
876 const FunctionType *FT = Callee->getFunctionType();
877 // Just make sure this has 2 arguments of the same FP type, which match the
879 if (FT->getNumParams() != 1 ||
880 !FT->getReturnType()->isIntegerTy(32) ||
881 !FT->getParamType(0)->isIntegerTy())
884 Value *Op = CI->getArgOperand(0);
887 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
888 if (CI->getValue() == 0) // ffs(0) -> 0.
889 return Constant::getNullValue(CI->getType());
890 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
891 CI->getValue().countTrailingZeros()+1);
894 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
895 const Type *ArgType = Op->getType();
896 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
897 Intrinsic::cttz, &ArgType, 1);
898 Value *V = B.CreateCall(F, Op, "cttz");
899 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
900 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
902 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
903 return B.CreateSelect(Cond, V,
904 ConstantInt::get(Type::getInt32Ty(*Context), 0));
908 //===---------------------------------------===//
909 // 'isdigit' Optimizations
911 struct IsDigitOpt : public LibCallOptimization {
912 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
913 const FunctionType *FT = Callee->getFunctionType();
914 // We require integer(i32)
915 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
916 !FT->getParamType(0)->isIntegerTy(32))
919 // isdigit(c) -> (c-'0') <u 10
920 Value *Op = CI->getArgOperand(0);
921 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
923 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
925 return B.CreateZExt(Op, CI->getType());
929 //===---------------------------------------===//
930 // 'isascii' Optimizations
932 struct IsAsciiOpt : public LibCallOptimization {
933 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
934 const FunctionType *FT = Callee->getFunctionType();
935 // We require integer(i32)
936 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
937 !FT->getParamType(0)->isIntegerTy(32))
940 // isascii(c) -> c <u 128
941 Value *Op = CI->getArgOperand(0);
942 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
944 return B.CreateZExt(Op, CI->getType());
948 //===---------------------------------------===//
949 // 'abs', 'labs', 'llabs' Optimizations
951 struct AbsOpt : public LibCallOptimization {
952 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
953 const FunctionType *FT = Callee->getFunctionType();
954 // We require integer(integer) where the types agree.
955 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
956 FT->getParamType(0) != FT->getReturnType())
959 // abs(x) -> x >s -1 ? x : -x
960 Value *Op = CI->getArgOperand(0);
961 Value *Pos = B.CreateICmpSGT(Op,
962 Constant::getAllOnesValue(Op->getType()),
964 Value *Neg = B.CreateNeg(Op, "neg");
965 return B.CreateSelect(Pos, Op, Neg);
970 //===---------------------------------------===//
971 // 'toascii' Optimizations
973 struct ToAsciiOpt : public LibCallOptimization {
974 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
975 const FunctionType *FT = Callee->getFunctionType();
976 // We require i32(i32)
977 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
978 !FT->getParamType(0)->isIntegerTy(32))
981 // isascii(c) -> c & 0x7f
982 return B.CreateAnd(CI->getArgOperand(0),
983 ConstantInt::get(CI->getType(),0x7F));
987 //===----------------------------------------------------------------------===//
988 // Formatting and IO Optimizations
989 //===----------------------------------------------------------------------===//
991 //===---------------------------------------===//
992 // 'printf' Optimizations
994 struct PrintFOpt : public LibCallOptimization {
995 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
996 // Require one fixed pointer argument and an integer/void result.
997 const FunctionType *FT = Callee->getFunctionType();
998 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
999 !(FT->getReturnType()->isIntegerTy() ||
1000 FT->getReturnType()->isVoidTy()))
1003 // Check for a fixed format string.
1004 std::string FormatStr;
1005 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
1008 // Empty format string -> noop.
1009 if (FormatStr.empty()) // Tolerate printf's declared void.
1010 return CI->use_empty() ? (Value*)CI :
1011 ConstantInt::get(CI->getType(), 0);
1013 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1014 // in case there is an error writing to stdout.
1015 if (FormatStr.size() == 1) {
1016 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1017 FormatStr[0]), B, TD);
1018 if (CI->use_empty()) return CI;
1019 return B.CreateIntCast(Res, CI->getType(), true);
1022 // printf("foo\n") --> puts("foo")
1023 if (FormatStr[FormatStr.size()-1] == '\n' &&
1024 FormatStr.find('%') == std::string::npos) { // no format characters.
1025 // Create a string literal with no \n on it. We expect the constant merge
1026 // pass to be run after this pass, to merge duplicate strings.
1027 FormatStr.erase(FormatStr.end()-1);
1028 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1029 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1030 GlobalVariable::InternalLinkage, C, "str");
1032 return CI->use_empty() ? (Value*)CI :
1033 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1036 // Optimize specific format strings.
1037 // printf("%c", chr) --> putchar(chr)
1038 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1039 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1040 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
1042 if (CI->use_empty()) return CI;
1043 return B.CreateIntCast(Res, CI->getType(), true);
1046 // printf("%s\n", str) --> puts(str)
1047 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1048 CI->getArgOperand(1)->getType()->isPointerTy() &&
1050 EmitPutS(CI->getArgOperand(1), B, TD);
1057 //===---------------------------------------===//
1058 // 'sprintf' Optimizations
1060 struct SPrintFOpt : public LibCallOptimization {
1061 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1062 // Require two fixed pointer arguments and an integer result.
1063 const FunctionType *FT = Callee->getFunctionType();
1064 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1065 !FT->getParamType(1)->isPointerTy() ||
1066 !FT->getReturnType()->isIntegerTy())
1069 // Check for a fixed format string.
1070 std::string FormatStr;
1071 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1074 // If we just have a format string (nothing else crazy) transform it.
1075 if (CI->getNumArgOperands() == 2) {
1076 // Make sure there's no % in the constant array. We could try to handle
1077 // %% -> % in the future if we cared.
1078 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1079 if (FormatStr[i] == '%')
1080 return 0; // we found a format specifier, bail out.
1082 // These optimizations require TargetData.
1085 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1086 EmitMemCpy(CI->getArgOperand(0), CI->getArgOperand(1), // Copy the
1087 ConstantInt::get(TD->getIntPtrType(*Context), // nul byte.
1088 FormatStr.size() + 1), 1, false, B, TD);
1089 return ConstantInt::get(CI->getType(), FormatStr.size());
1092 // The remaining optimizations require the format string to be "%s" or "%c"
1093 // and have an extra operand.
1094 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1095 CI->getNumArgOperands() < 3)
1098 // Decode the second character of the format string.
1099 if (FormatStr[1] == 'c') {
1100 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1101 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1102 Value *V = B.CreateTrunc(CI->getArgOperand(2),
1103 Type::getInt8Ty(*Context), "char");
1104 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1105 B.CreateStore(V, Ptr);
1106 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1108 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1110 return ConstantInt::get(CI->getType(), 1);
1113 if (FormatStr[1] == 's') {
1114 // These optimizations require TargetData.
1117 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1118 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1120 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
1121 Value *IncLen = B.CreateAdd(Len,
1122 ConstantInt::get(Len->getType(), 1),
1124 EmitMemCpy(CI->getArgOperand(0), CI->getArgOperand(2),
1125 IncLen, 1, false, B, TD);
1127 // The sprintf result is the unincremented number of bytes in the string.
1128 return B.CreateIntCast(Len, CI->getType(), false);
1134 //===---------------------------------------===//
1135 // 'fwrite' Optimizations
1137 struct FWriteOpt : public LibCallOptimization {
1138 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1139 // Require a pointer, an integer, an integer, a pointer, returning integer.
1140 const FunctionType *FT = Callee->getFunctionType();
1141 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1142 !FT->getParamType(1)->isIntegerTy() ||
1143 !FT->getParamType(2)->isIntegerTy() ||
1144 !FT->getParamType(3)->isPointerTy() ||
1145 !FT->getReturnType()->isIntegerTy())
1148 // Get the element size and count.
1149 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1150 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1151 if (!SizeC || !CountC) return 0;
1152 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1154 // If this is writing zero records, remove the call (it's a noop).
1156 return ConstantInt::get(CI->getType(), 0);
1158 // If this is writing one byte, turn it into fputc.
1159 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1160 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1161 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
1162 return ConstantInt::get(CI->getType(), 1);
1169 //===---------------------------------------===//
1170 // 'fputs' Optimizations
1172 struct FPutsOpt : public LibCallOptimization {
1173 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1174 // These optimizations require TargetData.
1177 // Require two pointers. Also, we can't optimize if return value is used.
1178 const FunctionType *FT = Callee->getFunctionType();
1179 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1180 !FT->getParamType(1)->isPointerTy() ||
1184 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1185 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1187 EmitFWrite(CI->getArgOperand(0),
1188 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1189 CI->getArgOperand(1), B, TD);
1190 return CI; // Known to have no uses (see above).
1194 //===---------------------------------------===//
1195 // 'fprintf' Optimizations
1197 struct FPrintFOpt : public LibCallOptimization {
1198 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1199 // Require two fixed paramters as pointers and integer result.
1200 const FunctionType *FT = Callee->getFunctionType();
1201 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1202 !FT->getParamType(1)->isPointerTy() ||
1203 !FT->getReturnType()->isIntegerTy())
1206 // All the optimizations depend on the format string.
1207 std::string FormatStr;
1208 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
1211 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1212 if (CI->getNumArgOperands() == 2) {
1213 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1214 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1215 return 0; // We found a format specifier.
1217 // These optimizations require TargetData.
1220 EmitFWrite(CI->getArgOperand(1),
1221 ConstantInt::get(TD->getIntPtrType(*Context),
1223 CI->getArgOperand(0), B, TD);
1224 return ConstantInt::get(CI->getType(), FormatStr.size());
1227 // The remaining optimizations require the format string to be "%s" or "%c"
1228 // and have an extra operand.
1229 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1230 CI->getNumArgOperands() < 3)
1233 // Decode the second character of the format string.
1234 if (FormatStr[1] == 'c') {
1235 // fprintf(F, "%c", chr) --> fputc(chr, F)
1236 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1237 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1238 return ConstantInt::get(CI->getType(), 1);
1241 if (FormatStr[1] == 's') {
1242 // fprintf(F, "%s", str) --> fputs(str, F)
1243 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
1245 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
1252 } // end anonymous namespace.
1254 //===----------------------------------------------------------------------===//
1255 // SimplifyLibCalls Pass Implementation
1256 //===----------------------------------------------------------------------===//
1259 /// This pass optimizes well known library functions from libc and libm.
1261 class SimplifyLibCalls : public FunctionPass {
1262 StringMap<LibCallOptimization*> Optimizations;
1263 // String and Memory LibCall Optimizations
1264 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1265 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1266 StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1267 StrToOpt StrTo; StrStrOpt StrStr;
1268 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1269 // Math Library Optimizations
1270 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1271 // Integer Optimizations
1272 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1274 // Formatting and IO Optimizations
1275 SPrintFOpt SPrintF; PrintFOpt PrintF;
1276 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1278 bool Modified; // This is only used by doInitialization.
1280 static char ID; // Pass identification
1281 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {}
1282 void InitOptimizations();
1283 bool runOnFunction(Function &F);
1285 void setDoesNotAccessMemory(Function &F);
1286 void setOnlyReadsMemory(Function &F);
1287 void setDoesNotThrow(Function &F);
1288 void setDoesNotCapture(Function &F, unsigned n);
1289 void setDoesNotAlias(Function &F, unsigned n);
1290 bool doInitialization(Module &M);
1292 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1295 char SimplifyLibCalls::ID = 0;
1296 } // end anonymous namespace.
1298 INITIALIZE_PASS(SimplifyLibCalls, "simplify-libcalls",
1299 "Simplify well-known library calls", false, false);
1301 // Public interface to the Simplify LibCalls pass.
1302 FunctionPass *llvm::createSimplifyLibCallsPass() {
1303 return new SimplifyLibCalls();
1306 /// Optimizations - Populate the Optimizations map with all the optimizations
1308 void SimplifyLibCalls::InitOptimizations() {
1309 // String and Memory LibCall Optimizations
1310 Optimizations["strcat"] = &StrCat;
1311 Optimizations["strncat"] = &StrNCat;
1312 Optimizations["strchr"] = &StrChr;
1313 Optimizations["strrchr"] = &StrRChr;
1314 Optimizations["strcmp"] = &StrCmp;
1315 Optimizations["strncmp"] = &StrNCmp;
1316 Optimizations["strcpy"] = &StrCpy;
1317 Optimizations["strncpy"] = &StrNCpy;
1318 Optimizations["strlen"] = &StrLen;
1319 Optimizations["strtol"] = &StrTo;
1320 Optimizations["strtod"] = &StrTo;
1321 Optimizations["strtof"] = &StrTo;
1322 Optimizations["strtoul"] = &StrTo;
1323 Optimizations["strtoll"] = &StrTo;
1324 Optimizations["strtold"] = &StrTo;
1325 Optimizations["strtoull"] = &StrTo;
1326 Optimizations["strstr"] = &StrStr;
1327 Optimizations["memcmp"] = &MemCmp;
1328 Optimizations["memcpy"] = &MemCpy;
1329 Optimizations["memmove"] = &MemMove;
1330 Optimizations["memset"] = &MemSet;
1332 // _chk variants of String and Memory LibCall Optimizations.
1333 Optimizations["__strcpy_chk"] = &StrCpyChk;
1335 // Math Library Optimizations
1336 Optimizations["powf"] = &Pow;
1337 Optimizations["pow"] = &Pow;
1338 Optimizations["powl"] = &Pow;
1339 Optimizations["llvm.pow.f32"] = &Pow;
1340 Optimizations["llvm.pow.f64"] = &Pow;
1341 Optimizations["llvm.pow.f80"] = &Pow;
1342 Optimizations["llvm.pow.f128"] = &Pow;
1343 Optimizations["llvm.pow.ppcf128"] = &Pow;
1344 Optimizations["exp2l"] = &Exp2;
1345 Optimizations["exp2"] = &Exp2;
1346 Optimizations["exp2f"] = &Exp2;
1347 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1348 Optimizations["llvm.exp2.f128"] = &Exp2;
1349 Optimizations["llvm.exp2.f80"] = &Exp2;
1350 Optimizations["llvm.exp2.f64"] = &Exp2;
1351 Optimizations["llvm.exp2.f32"] = &Exp2;
1354 Optimizations["floor"] = &UnaryDoubleFP;
1357 Optimizations["ceil"] = &UnaryDoubleFP;
1360 Optimizations["round"] = &UnaryDoubleFP;
1363 Optimizations["rint"] = &UnaryDoubleFP;
1365 #ifdef HAVE_NEARBYINTF
1366 Optimizations["nearbyint"] = &UnaryDoubleFP;
1369 // Integer Optimizations
1370 Optimizations["ffs"] = &FFS;
1371 Optimizations["ffsl"] = &FFS;
1372 Optimizations["ffsll"] = &FFS;
1373 Optimizations["abs"] = &Abs;
1374 Optimizations["labs"] = &Abs;
1375 Optimizations["llabs"] = &Abs;
1376 Optimizations["isdigit"] = &IsDigit;
1377 Optimizations["isascii"] = &IsAscii;
1378 Optimizations["toascii"] = &ToAscii;
1380 // Formatting and IO Optimizations
1381 Optimizations["sprintf"] = &SPrintF;
1382 Optimizations["printf"] = &PrintF;
1383 Optimizations["fwrite"] = &FWrite;
1384 Optimizations["fputs"] = &FPuts;
1385 Optimizations["fprintf"] = &FPrintF;
1389 /// runOnFunction - Top level algorithm.
1391 bool SimplifyLibCalls::runOnFunction(Function &F) {
1392 if (Optimizations.empty())
1393 InitOptimizations();
1395 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1397 IRBuilder<> Builder(F.getContext());
1399 bool Changed = false;
1400 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1401 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1402 // Ignore non-calls.
1403 CallInst *CI = dyn_cast<CallInst>(I++);
1406 // Ignore indirect calls and calls to non-external functions.
1407 Function *Callee = CI->getCalledFunction();
1408 if (Callee == 0 || !Callee->isDeclaration() ||
1409 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1412 // Ignore unknown calls.
1413 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1416 // Set the builder to the instruction after the call.
1417 Builder.SetInsertPoint(BB, I);
1419 // Try to optimize this call.
1420 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1421 if (Result == 0) continue;
1423 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1424 dbgs() << " into: " << *Result << "\n");
1426 // Something changed!
1430 // Inspect the instruction after the call (which was potentially just
1434 if (CI != Result && !CI->use_empty()) {
1435 CI->replaceAllUsesWith(Result);
1436 if (!Result->hasName())
1437 Result->takeName(CI);
1439 CI->eraseFromParent();
1445 // Utility methods for doInitialization.
1447 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1448 if (!F.doesNotAccessMemory()) {
1449 F.setDoesNotAccessMemory();
1454 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1455 if (!F.onlyReadsMemory()) {
1456 F.setOnlyReadsMemory();
1461 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1462 if (!F.doesNotThrow()) {
1463 F.setDoesNotThrow();
1468 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1469 if (!F.doesNotCapture(n)) {
1470 F.setDoesNotCapture(n);
1475 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1476 if (!F.doesNotAlias(n)) {
1477 F.setDoesNotAlias(n);
1483 /// doInitialization - Add attributes to well-known functions.
1485 bool SimplifyLibCalls::doInitialization(Module &M) {
1487 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1489 if (!F.isDeclaration())
1495 const FunctionType *FTy = F.getFunctionType();
1497 StringRef Name = F.getName();
1500 if (Name == "strlen") {
1501 if (FTy->getNumParams() != 1 ||
1502 !FTy->getParamType(0)->isPointerTy())
1504 setOnlyReadsMemory(F);
1506 setDoesNotCapture(F, 1);
1507 } else if (Name == "strchr" ||
1508 Name == "strrchr") {
1509 if (FTy->getNumParams() != 2 ||
1510 !FTy->getParamType(0)->isPointerTy() ||
1511 !FTy->getParamType(1)->isIntegerTy())
1513 setOnlyReadsMemory(F);
1515 } else if (Name == "strcpy" ||
1521 Name == "strtoul" ||
1522 Name == "strtoll" ||
1523 Name == "strtold" ||
1524 Name == "strncat" ||
1525 Name == "strncpy" ||
1526 Name == "strtoull") {
1527 if (FTy->getNumParams() < 2 ||
1528 !FTy->getParamType(1)->isPointerTy())
1531 setDoesNotCapture(F, 2);
1532 } else if (Name == "strxfrm") {
1533 if (FTy->getNumParams() != 3 ||
1534 !FTy->getParamType(0)->isPointerTy() ||
1535 !FTy->getParamType(1)->isPointerTy())
1538 setDoesNotCapture(F, 1);
1539 setDoesNotCapture(F, 2);
1540 } else if (Name == "strcmp" ||
1542 Name == "strncmp" ||
1543 Name == "strcspn" ||
1544 Name == "strcoll" ||
1545 Name == "strcasecmp" ||
1546 Name == "strncasecmp") {
1547 if (FTy->getNumParams() < 2 ||
1548 !FTy->getParamType(0)->isPointerTy() ||
1549 !FTy->getParamType(1)->isPointerTy())
1551 setOnlyReadsMemory(F);
1553 setDoesNotCapture(F, 1);
1554 setDoesNotCapture(F, 2);
1555 } else if (Name == "strstr" ||
1556 Name == "strpbrk") {
1557 if (FTy->getNumParams() != 2 ||
1558 !FTy->getParamType(1)->isPointerTy())
1560 setOnlyReadsMemory(F);
1562 setDoesNotCapture(F, 2);
1563 } else if (Name == "strtok" ||
1564 Name == "strtok_r") {
1565 if (FTy->getNumParams() < 2 ||
1566 !FTy->getParamType(1)->isPointerTy())
1569 setDoesNotCapture(F, 2);
1570 } else if (Name == "scanf" ||
1572 Name == "setvbuf") {
1573 if (FTy->getNumParams() < 1 ||
1574 !FTy->getParamType(0)->isPointerTy())
1577 setDoesNotCapture(F, 1);
1578 } else if (Name == "strdup" ||
1579 Name == "strndup") {
1580 if (FTy->getNumParams() < 1 ||
1581 !FTy->getReturnType()->isPointerTy() ||
1582 !FTy->getParamType(0)->isPointerTy())
1585 setDoesNotAlias(F, 0);
1586 setDoesNotCapture(F, 1);
1587 } else if (Name == "stat" ||
1589 Name == "sprintf" ||
1590 Name == "statvfs") {
1591 if (FTy->getNumParams() < 2 ||
1592 !FTy->getParamType(0)->isPointerTy() ||
1593 !FTy->getParamType(1)->isPointerTy())
1596 setDoesNotCapture(F, 1);
1597 setDoesNotCapture(F, 2);
1598 } else if (Name == "snprintf") {
1599 if (FTy->getNumParams() != 3 ||
1600 !FTy->getParamType(0)->isPointerTy() ||
1601 !FTy->getParamType(2)->isPointerTy())
1604 setDoesNotCapture(F, 1);
1605 setDoesNotCapture(F, 3);
1606 } else if (Name == "setitimer") {
1607 if (FTy->getNumParams() != 3 ||
1608 !FTy->getParamType(1)->isPointerTy() ||
1609 !FTy->getParamType(2)->isPointerTy())
1612 setDoesNotCapture(F, 2);
1613 setDoesNotCapture(F, 3);
1614 } else if (Name == "system") {
1615 if (FTy->getNumParams() != 1 ||
1616 !FTy->getParamType(0)->isPointerTy())
1618 // May throw; "system" is a valid pthread cancellation point.
1619 setDoesNotCapture(F, 1);
1623 if (Name == "malloc") {
1624 if (FTy->getNumParams() != 1 ||
1625 !FTy->getReturnType()->isPointerTy())
1628 setDoesNotAlias(F, 0);
1629 } else if (Name == "memcmp") {
1630 if (FTy->getNumParams() != 3 ||
1631 !FTy->getParamType(0)->isPointerTy() ||
1632 !FTy->getParamType(1)->isPointerTy())
1634 setOnlyReadsMemory(F);
1636 setDoesNotCapture(F, 1);
1637 setDoesNotCapture(F, 2);
1638 } else if (Name == "memchr" ||
1639 Name == "memrchr") {
1640 if (FTy->getNumParams() != 3)
1642 setOnlyReadsMemory(F);
1644 } else if (Name == "modf" ||
1648 Name == "memccpy" ||
1649 Name == "memmove") {
1650 if (FTy->getNumParams() < 2 ||
1651 !FTy->getParamType(1)->isPointerTy())
1654 setDoesNotCapture(F, 2);
1655 } else if (Name == "memalign") {
1656 if (!FTy->getReturnType()->isPointerTy())
1658 setDoesNotAlias(F, 0);
1659 } else if (Name == "mkdir" ||
1661 if (FTy->getNumParams() == 0 ||
1662 !FTy->getParamType(0)->isPointerTy())
1665 setDoesNotCapture(F, 1);
1669 if (Name == "realloc") {
1670 if (FTy->getNumParams() != 2 ||
1671 !FTy->getParamType(0)->isPointerTy() ||
1672 !FTy->getReturnType()->isPointerTy())
1675 setDoesNotAlias(F, 0);
1676 setDoesNotCapture(F, 1);
1677 } else if (Name == "read") {
1678 if (FTy->getNumParams() != 3 ||
1679 !FTy->getParamType(1)->isPointerTy())
1681 // May throw; "read" is a valid pthread cancellation point.
1682 setDoesNotCapture(F, 2);
1683 } else if (Name == "rmdir" ||
1686 Name == "realpath") {
1687 if (FTy->getNumParams() < 1 ||
1688 !FTy->getParamType(0)->isPointerTy())
1691 setDoesNotCapture(F, 1);
1692 } else if (Name == "rename" ||
1693 Name == "readlink") {
1694 if (FTy->getNumParams() < 2 ||
1695 !FTy->getParamType(0)->isPointerTy() ||
1696 !FTy->getParamType(1)->isPointerTy())
1699 setDoesNotCapture(F, 1);
1700 setDoesNotCapture(F, 2);
1704 if (Name == "write") {
1705 if (FTy->getNumParams() != 3 ||
1706 !FTy->getParamType(1)->isPointerTy())
1708 // May throw; "write" is a valid pthread cancellation point.
1709 setDoesNotCapture(F, 2);
1713 if (Name == "bcopy") {
1714 if (FTy->getNumParams() != 3 ||
1715 !FTy->getParamType(0)->isPointerTy() ||
1716 !FTy->getParamType(1)->isPointerTy())
1719 setDoesNotCapture(F, 1);
1720 setDoesNotCapture(F, 2);
1721 } else if (Name == "bcmp") {
1722 if (FTy->getNumParams() != 3 ||
1723 !FTy->getParamType(0)->isPointerTy() ||
1724 !FTy->getParamType(1)->isPointerTy())
1727 setOnlyReadsMemory(F);
1728 setDoesNotCapture(F, 1);
1729 setDoesNotCapture(F, 2);
1730 } else if (Name == "bzero") {
1731 if (FTy->getNumParams() != 2 ||
1732 !FTy->getParamType(0)->isPointerTy())
1735 setDoesNotCapture(F, 1);
1739 if (Name == "calloc") {
1740 if (FTy->getNumParams() != 2 ||
1741 !FTy->getReturnType()->isPointerTy())
1744 setDoesNotAlias(F, 0);
1745 } else if (Name == "chmod" ||
1747 Name == "ctermid" ||
1748 Name == "clearerr" ||
1749 Name == "closedir") {
1750 if (FTy->getNumParams() == 0 ||
1751 !FTy->getParamType(0)->isPointerTy())
1754 setDoesNotCapture(F, 1);
1758 if (Name == "atoi" ||
1762 if (FTy->getNumParams() != 1 ||
1763 !FTy->getParamType(0)->isPointerTy())
1766 setOnlyReadsMemory(F);
1767 setDoesNotCapture(F, 1);
1768 } else if (Name == "access") {
1769 if (FTy->getNumParams() != 2 ||
1770 !FTy->getParamType(0)->isPointerTy())
1773 setDoesNotCapture(F, 1);
1777 if (Name == "fopen") {
1778 if (FTy->getNumParams() != 2 ||
1779 !FTy->getReturnType()->isPointerTy() ||
1780 !FTy->getParamType(0)->isPointerTy() ||
1781 !FTy->getParamType(1)->isPointerTy())
1784 setDoesNotAlias(F, 0);
1785 setDoesNotCapture(F, 1);
1786 setDoesNotCapture(F, 2);
1787 } else if (Name == "fdopen") {
1788 if (FTy->getNumParams() != 2 ||
1789 !FTy->getReturnType()->isPointerTy() ||
1790 !FTy->getParamType(1)->isPointerTy())
1793 setDoesNotAlias(F, 0);
1794 setDoesNotCapture(F, 2);
1795 } else if (Name == "feof" ||
1805 Name == "fsetpos" ||
1806 Name == "flockfile" ||
1807 Name == "funlockfile" ||
1808 Name == "ftrylockfile") {
1809 if (FTy->getNumParams() == 0 ||
1810 !FTy->getParamType(0)->isPointerTy())
1813 setDoesNotCapture(F, 1);
1814 } else if (Name == "ferror") {
1815 if (FTy->getNumParams() != 1 ||
1816 !FTy->getParamType(0)->isPointerTy())
1819 setDoesNotCapture(F, 1);
1820 setOnlyReadsMemory(F);
1821 } else if (Name == "fputc" ||
1826 Name == "fstatvfs") {
1827 if (FTy->getNumParams() != 2 ||
1828 !FTy->getParamType(1)->isPointerTy())
1831 setDoesNotCapture(F, 2);
1832 } else if (Name == "fgets") {
1833 if (FTy->getNumParams() != 3 ||
1834 !FTy->getParamType(0)->isPointerTy() ||
1835 !FTy->getParamType(2)->isPointerTy())
1838 setDoesNotCapture(F, 3);
1839 } else if (Name == "fread" ||
1841 if (FTy->getNumParams() != 4 ||
1842 !FTy->getParamType(0)->isPointerTy() ||
1843 !FTy->getParamType(3)->isPointerTy())
1846 setDoesNotCapture(F, 1);
1847 setDoesNotCapture(F, 4);
1848 } else if (Name == "fputs" ||
1850 Name == "fprintf" ||
1851 Name == "fgetpos") {
1852 if (FTy->getNumParams() < 2 ||
1853 !FTy->getParamType(0)->isPointerTy() ||
1854 !FTy->getParamType(1)->isPointerTy())
1857 setDoesNotCapture(F, 1);
1858 setDoesNotCapture(F, 2);
1862 if (Name == "getc" ||
1863 Name == "getlogin_r" ||
1864 Name == "getc_unlocked") {
1865 if (FTy->getNumParams() == 0 ||
1866 !FTy->getParamType(0)->isPointerTy())
1869 setDoesNotCapture(F, 1);
1870 } else if (Name == "getenv") {
1871 if (FTy->getNumParams() != 1 ||
1872 !FTy->getParamType(0)->isPointerTy())
1875 setOnlyReadsMemory(F);
1876 setDoesNotCapture(F, 1);
1877 } else if (Name == "gets" ||
1878 Name == "getchar") {
1880 } else if (Name == "getitimer") {
1881 if (FTy->getNumParams() != 2 ||
1882 !FTy->getParamType(1)->isPointerTy())
1885 setDoesNotCapture(F, 2);
1886 } else if (Name == "getpwnam") {
1887 if (FTy->getNumParams() != 1 ||
1888 !FTy->getParamType(0)->isPointerTy())
1891 setDoesNotCapture(F, 1);
1895 if (Name == "ungetc") {
1896 if (FTy->getNumParams() != 2 ||
1897 !FTy->getParamType(1)->isPointerTy())
1900 setDoesNotCapture(F, 2);
1901 } else if (Name == "uname" ||
1903 Name == "unsetenv") {
1904 if (FTy->getNumParams() != 1 ||
1905 !FTy->getParamType(0)->isPointerTy())
1908 setDoesNotCapture(F, 1);
1909 } else if (Name == "utime" ||
1911 if (FTy->getNumParams() != 2 ||
1912 !FTy->getParamType(0)->isPointerTy() ||
1913 !FTy->getParamType(1)->isPointerTy())
1916 setDoesNotCapture(F, 1);
1917 setDoesNotCapture(F, 2);
1921 if (Name == "putc") {
1922 if (FTy->getNumParams() != 2 ||
1923 !FTy->getParamType(1)->isPointerTy())
1926 setDoesNotCapture(F, 2);
1927 } else if (Name == "puts" ||
1930 if (FTy->getNumParams() != 1 ||
1931 !FTy->getParamType(0)->isPointerTy())
1934 setDoesNotCapture(F, 1);
1935 } else if (Name == "pread" ||
1937 if (FTy->getNumParams() != 4 ||
1938 !FTy->getParamType(1)->isPointerTy())
1940 // May throw; these are valid pthread cancellation points.
1941 setDoesNotCapture(F, 2);
1942 } else if (Name == "putchar") {
1944 } else if (Name == "popen") {
1945 if (FTy->getNumParams() != 2 ||
1946 !FTy->getReturnType()->isPointerTy() ||
1947 !FTy->getParamType(0)->isPointerTy() ||
1948 !FTy->getParamType(1)->isPointerTy())
1951 setDoesNotAlias(F, 0);
1952 setDoesNotCapture(F, 1);
1953 setDoesNotCapture(F, 2);
1954 } else if (Name == "pclose") {
1955 if (FTy->getNumParams() != 1 ||
1956 !FTy->getParamType(0)->isPointerTy())
1959 setDoesNotCapture(F, 1);
1963 if (Name == "vscanf") {
1964 if (FTy->getNumParams() != 2 ||
1965 !FTy->getParamType(1)->isPointerTy())
1968 setDoesNotCapture(F, 1);
1969 } else if (Name == "vsscanf" ||
1970 Name == "vfscanf") {
1971 if (FTy->getNumParams() != 3 ||
1972 !FTy->getParamType(1)->isPointerTy() ||
1973 !FTy->getParamType(2)->isPointerTy())
1976 setDoesNotCapture(F, 1);
1977 setDoesNotCapture(F, 2);
1978 } else if (Name == "valloc") {
1979 if (!FTy->getReturnType()->isPointerTy())
1982 setDoesNotAlias(F, 0);
1983 } else if (Name == "vprintf") {
1984 if (FTy->getNumParams() != 2 ||
1985 !FTy->getParamType(0)->isPointerTy())
1988 setDoesNotCapture(F, 1);
1989 } else if (Name == "vfprintf" ||
1990 Name == "vsprintf") {
1991 if (FTy->getNumParams() != 3 ||
1992 !FTy->getParamType(0)->isPointerTy() ||
1993 !FTy->getParamType(1)->isPointerTy())
1996 setDoesNotCapture(F, 1);
1997 setDoesNotCapture(F, 2);
1998 } else if (Name == "vsnprintf") {
1999 if (FTy->getNumParams() != 4 ||
2000 !FTy->getParamType(0)->isPointerTy() ||
2001 !FTy->getParamType(2)->isPointerTy())
2004 setDoesNotCapture(F, 1);
2005 setDoesNotCapture(F, 3);
2009 if (Name == "open") {
2010 if (FTy->getNumParams() < 2 ||
2011 !FTy->getParamType(0)->isPointerTy())
2013 // May throw; "open" is a valid pthread cancellation point.
2014 setDoesNotCapture(F, 1);
2015 } else if (Name == "opendir") {
2016 if (FTy->getNumParams() != 1 ||
2017 !FTy->getReturnType()->isPointerTy() ||
2018 !FTy->getParamType(0)->isPointerTy())
2021 setDoesNotAlias(F, 0);
2022 setDoesNotCapture(F, 1);
2026 if (Name == "tmpfile") {
2027 if (!FTy->getReturnType()->isPointerTy())
2030 setDoesNotAlias(F, 0);
2031 } else if (Name == "times") {
2032 if (FTy->getNumParams() != 1 ||
2033 !FTy->getParamType(0)->isPointerTy())
2036 setDoesNotCapture(F, 1);
2040 if (Name == "htonl" ||
2043 setDoesNotAccessMemory(F);
2047 if (Name == "ntohl" ||
2050 setDoesNotAccessMemory(F);
2054 if (Name == "lstat") {
2055 if (FTy->getNumParams() != 2 ||
2056 !FTy->getParamType(0)->isPointerTy() ||
2057 !FTy->getParamType(1)->isPointerTy())
2060 setDoesNotCapture(F, 1);
2061 setDoesNotCapture(F, 2);
2062 } else if (Name == "lchown") {
2063 if (FTy->getNumParams() != 3 ||
2064 !FTy->getParamType(0)->isPointerTy())
2067 setDoesNotCapture(F, 1);
2071 if (Name == "qsort") {
2072 if (FTy->getNumParams() != 4 ||
2073 !FTy->getParamType(3)->isPointerTy())
2075 // May throw; places call through function pointer.
2076 setDoesNotCapture(F, 4);
2080 if (Name == "__strdup" ||
2081 Name == "__strndup") {
2082 if (FTy->getNumParams() < 1 ||
2083 !FTy->getReturnType()->isPointerTy() ||
2084 !FTy->getParamType(0)->isPointerTy())
2087 setDoesNotAlias(F, 0);
2088 setDoesNotCapture(F, 1);
2089 } else if (Name == "__strtok_r") {
2090 if (FTy->getNumParams() != 3 ||
2091 !FTy->getParamType(1)->isPointerTy())
2094 setDoesNotCapture(F, 2);
2095 } else if (Name == "_IO_getc") {
2096 if (FTy->getNumParams() != 1 ||
2097 !FTy->getParamType(0)->isPointerTy())
2100 setDoesNotCapture(F, 1);
2101 } else if (Name == "_IO_putc") {
2102 if (FTy->getNumParams() != 2 ||
2103 !FTy->getParamType(1)->isPointerTy())
2106 setDoesNotCapture(F, 2);
2110 if (Name == "\1__isoc99_scanf") {
2111 if (FTy->getNumParams() < 1 ||
2112 !FTy->getParamType(0)->isPointerTy())
2115 setDoesNotCapture(F, 1);
2116 } else if (Name == "\1stat64" ||
2117 Name == "\1lstat64" ||
2118 Name == "\1statvfs64" ||
2119 Name == "\1__isoc99_sscanf") {
2120 if (FTy->getNumParams() < 1 ||
2121 !FTy->getParamType(0)->isPointerTy() ||
2122 !FTy->getParamType(1)->isPointerTy())
2125 setDoesNotCapture(F, 1);
2126 setDoesNotCapture(F, 2);
2127 } else if (Name == "\1fopen64") {
2128 if (FTy->getNumParams() != 2 ||
2129 !FTy->getReturnType()->isPointerTy() ||
2130 !FTy->getParamType(0)->isPointerTy() ||
2131 !FTy->getParamType(1)->isPointerTy())
2134 setDoesNotAlias(F, 0);
2135 setDoesNotCapture(F, 1);
2136 setDoesNotCapture(F, 2);
2137 } else if (Name == "\1fseeko64" ||
2138 Name == "\1ftello64") {
2139 if (FTy->getNumParams() == 0 ||
2140 !FTy->getParamType(0)->isPointerTy())
2143 setDoesNotCapture(F, 1);
2144 } else if (Name == "\1tmpfile64") {
2145 if (!FTy->getReturnType()->isPointerTy())
2148 setDoesNotAlias(F, 0);
2149 } else if (Name == "\1fstat64" ||
2150 Name == "\1fstatvfs64") {
2151 if (FTy->getNumParams() != 2 ||
2152 !FTy->getParamType(1)->isPointerTy())
2155 setDoesNotCapture(F, 2);
2156 } else if (Name == "\1open64") {
2157 if (FTy->getNumParams() < 2 ||
2158 !FTy->getParamType(0)->isPointerTy())
2160 // May throw; "open" is a valid pthread cancellation point.
2161 setDoesNotCapture(F, 1);
2170 // Additional cases that we need to add to this file:
2173 // * cbrt(expN(X)) -> expN(x/3)
2174 // * cbrt(sqrt(x)) -> pow(x,1/6)
2175 // * cbrt(sqrt(x)) -> pow(x,1/9)
2178 // * cos(-x) -> cos(x)
2181 // * exp(log(x)) -> x
2184 // * log(exp(x)) -> x
2185 // * log(x**y) -> y*log(x)
2186 // * log(exp(y)) -> y*log(e)
2187 // * log(exp2(y)) -> y*log(2)
2188 // * log(exp10(y)) -> y*log(10)
2189 // * log(sqrt(x)) -> 0.5*log(x)
2190 // * log(pow(x,y)) -> y*log(x)
2192 // lround, lroundf, lroundl:
2193 // * lround(cnst) -> cnst'
2196 // * pow(exp(x),y) -> exp(x*y)
2197 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2198 // * pow(pow(x,y),z)-> pow(x,y*z)
2201 // * puts("") -> putchar('\n')
2203 // round, roundf, roundl:
2204 // * round(cnst) -> cnst'
2207 // * signbit(cnst) -> cnst'
2208 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2210 // sqrt, sqrtf, sqrtl:
2211 // * sqrt(expN(x)) -> expN(x*0.5)
2212 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2213 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2216 // * stpcpy(str, "literal") ->
2217 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2220 // * strpbrk(s,a) -> offset_in_for(s,a)
2221 // (if s and a are both constant strings)
2222 // * strpbrk(s,"") -> 0
2223 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2226 // * strspn(s,a) -> const_int (if both args are constant)
2227 // * strspn("",a) -> 0
2228 // * strspn(s,"") -> 0
2229 // * strcspn(s,a) -> const_int (if both args are constant)
2230 // * strcspn("",a) -> 0
2231 // * strcspn(s,"") -> strlen(a)
2234 // * tan(atan(x)) -> x
2236 // trunc, truncf, truncl:
2237 // * trunc(cnst) -> cnst'