Newer
Older
//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a simple pass that applies a variety of small
// optimizations for calls to specific well-known function calls (e.g. runtime
// library functions). Any optimization that takes the very simple form
// "replace call to library function with simpler code that provides the same
// result" belongs in this file.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "simplify-libcalls"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BuildLibCalls.h"
#include "llvm/Intrinsics.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Target/TargetData.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/config.h"
using namespace llvm;
STATISTIC(NumSimplified, "Number of library calls simplified");
STATISTIC(NumAnnotated, "Number of attributes added to library functions");
//===----------------------------------------------------------------------===//
// Optimizer Base Class
//===----------------------------------------------------------------------===//
/// This class is the abstract base class for the set of optimizations that
/// corresponds to one library call.
namespace {
class LibCallOptimization {
protected:
Function *Caller;
const TargetData *TD;
public:
LibCallOptimization() { }
virtual ~LibCallOptimization() {}
/// CallOptimizer - This pure virtual method is implemented by base classes to
/// do various optimizations. If this returns null then no transformation was
/// performed. If it returns CI, then it transformed the call and CI is to be
/// deleted. If it returns something else, replace CI with the new value and
/// delete CI.
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
=0;
Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
Caller = CI->getParent()->getParent();
Context = &CI->getCalledFunction()->getContext();
Rafael Espindola
committed
// We never change the calling convention.
if (CI->getCallingConv() != llvm::CallingConv::C)
return NULL;
return CallOptimizer(CI->getCalledFunction(), CI, B);
}
};
} // End anonymous namespace.
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
/// value is equal or not-equal to zero.
static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
UI != E; ++UI) {
if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
if (IC->isEquality())
if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
if (C->isNullValue())
continue;
// Unknown instruction.
return false;
}
return true;
}
Benjamin Kramer
committed
/// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
/// comparisons with With.
static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
UI != E; ++UI) {
if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
if (IC->isEquality() && IC->getOperand(1) == With)
continue;
// Unknown instruction.
return false;
}
return true;
}
//===----------------------------------------------------------------------===//
// String and Memory LibCall Optimizations
//===----------------------------------------------------------------------===//
//===---------------------------------------===//
// 'strcat' Optimizations
struct StrCatOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strcat" function prototype.
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 ||
FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
FT->getParamType(0) != FT->getReturnType() ||
FT->getParamType(1) != FT->getReturnType())
return 0;
// Extract some information from the instruction
Value *Dst = CI->getArgOperand(0);
Value *Src = CI->getArgOperand(1);
// See if we can get the length of the input string.
uint64_t Len = GetStringLength(Src);
--Len; // Unbias length.
// Handle the simple, do-nothing case: strcat(x, "") -> x
if (Len == 0)
return Dst;
// These optimizations require TargetData.
if (!TD) return 0;
EmitStrLenMemCpy(Src, Dst, Len, B);
return Dst;
}
void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
// We need to find the end of the destination string. That's where the
// memory is to be moved to. We just generate a call to strlen.
Value *DstLen = EmitStrLen(Dst, B, TD);
// Now that we have the destination's length, we must index into the
// destination's pointer to get the actual memcpy destination (end of
// the string .. we're concatenating).
Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
// We have enough information to now generate the memcpy call to do the
// concatenation for us. Make a memcpy to copy the nul byte with align = 1.
ConstantInt::get(TD->getIntPtrType(*Context), Len+1),
1, false, B, TD);
}
};
//===---------------------------------------===//
// 'strncat' Optimizations
struct StrNCatOpt : public StrCatOpt {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strncat" function prototype.
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 ||
FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
FT->getParamType(0) != FT->getReturnType() ||
FT->getParamType(1) != FT->getReturnType() ||
Duncan Sands
committed
!FT->getParamType(2)->isIntegerTy())
return 0;
// Extract some information from the instruction
Value *Dst = CI->getArgOperand(0);
Value *Src = CI->getArgOperand(1);
uint64_t Len;
// We don't do anything if length is not constant
if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Len = LengthArg->getZExtValue();
else
return 0;
// See if we can get the length of the input string.
uint64_t SrcLen = GetStringLength(Src);
if (SrcLen == 0) return 0;
--SrcLen; // Unbias length.
// Handle the simple, do-nothing cases:
// strncat(x, "", c) -> x
// strncat(x, c, 0) -> x
if (SrcLen == 0 || Len == 0) return Dst;
// These optimizations require TargetData.
if (!TD) return 0;
// We don't optimize this case
if (Len < SrcLen) return 0;
// strncat(x, s, c) -> strcat(x, s)
// s is constant so the strcat can be optimized further
EmitStrLenMemCpy(Src, Dst, SrcLen, B);
return Dst;
}
};
//===---------------------------------------===//
// 'strchr' Optimizations
struct StrChrOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strchr" function prototype.
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 ||
FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
FT->getParamType(0) != FT->getReturnType())
return 0;
// If the second operand is non-constant, see if we can compute the length
// of the input string and turn this into memchr.
ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
if (CharC == 0) {
// These optimizations require TargetData.
if (!TD) return 0;
uint64_t Len = GetStringLength(SrcStr);
if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
return 0;
return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
ConstantInt::get(TD->getIntPtrType(*Context), Len),
B, TD);
}
// Otherwise, the character is a constant, see if the first argument is
// a string literal. If so, we can constant fold.
std::string Str;
if (!GetConstantStringInfo(SrcStr, Str))
// strchr can find the nul character.
Str += '\0';
// Compute the offset.
size_t I = Str.find(CharC->getSExtValue());
if (I == std::string::npos) // Didn't find the char. strchr returns null.
return Constant::getNullValue(CI->getType());
// strchr(s+n,c) -> gep(s+n+i,c)
Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), I);
return B.CreateGEP(SrcStr, Idx, "strchr");
}
};
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//===---------------------------------------===//
// 'strrchr' Optimizations
struct StrRChrOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strrchr" function prototype.
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 ||
FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
FT->getParamType(0) != FT->getReturnType())
return 0;
Value *SrcStr = CI->getArgOperand(0);
ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
// Cannot fold anything if we're not looking for a constant.
if (!CharC)
return 0;
std::string Str;
if (!GetConstantStringInfo(SrcStr, Str)) {
// strrchr(s, 0) -> strchr(s, 0)
if (TD && CharC->isZero())
return EmitStrChr(SrcStr, '\0', B, TD);
return 0;
}
// strrchr can find the nul character.
Str += '\0';
// Compute the offset.
size_t I = Str.rfind(CharC->getSExtValue());
if (I == std::string::npos) // Didn't find the char. Return null.
return Constant::getNullValue(CI->getType());
// strrchr(s+n,c) -> gep(s+n+i,c)
Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), I);
return B.CreateGEP(SrcStr, Idx, "strrchr");
}
};
//===---------------------------------------===//
// 'strcmp' Optimizations
struct StrCmpOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strcmp" function prototype.
const FunctionType *FT = Callee->getFunctionType();
FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != Type::getInt8PtrTy(*Context))
return 0;
Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Anderson
committed
return ConstantInt::get(CI->getType(), 0);
std::string Str1, Str2;
bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
// strcmp(x, y) -> cnst (if both x and y are constant strings)
return ConstantInt::get(CI->getType(),
strcmp(Str1.c_str(),Str2.c_str()));
// strcmp(P, "x") -> memcmp(P, "x", 2)
uint64_t Len1 = GetStringLength(Str1P);
uint64_t Len2 = GetStringLength(Str2P);
if (Len1 && Len2) {
// These optimizations require TargetData.
if (!TD) return 0;
return EmitMemCmp(Str1P, Str2P,
ConstantInt::get(TD->getIntPtrType(*Context),
std::min(Len1, Len2)), B, TD);
}
return 0;
}
};
//===---------------------------------------===//
// 'strncmp' Optimizations
struct StrNCmpOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strncmp" function prototype.
const FunctionType *FT = Callee->getFunctionType();
FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Duncan Sands
committed
!FT->getParamType(2)->isIntegerTy())
return 0;
Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Anderson
committed
return ConstantInt::get(CI->getType(), 0);
// Get the length argument if it is constant.
uint64_t Length;
if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Length = LengthArg->getZExtValue();
else
return 0;
if (Length == 0) // strncmp(x,y,0) -> 0
Owen Anderson
committed
return ConstantInt::get(CI->getType(), 0);
if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
std::string Str1, Str2;
bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
// strncmp(x, y) -> cnst (if both x and y are constant strings)
Owen Anderson
committed
return ConstantInt::get(CI->getType(),
strncmp(Str1.c_str(), Str2.c_str(), Length));
return 0;
}
};
//===---------------------------------------===//
// 'strcpy' Optimizations
struct StrCpyOpt : public LibCallOptimization {
bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
StrCpyOpt(bool c) : OptChkCall(c) {}
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// Verify the "strcpy" function prototype.
unsigned NumParams = OptChkCall ? 3 : 2;
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != NumParams ||
FT->getReturnType() != FT->getParamType(0) ||
FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != Type::getInt8PtrTy(*Context))
return 0;
Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
if (Dst == Src) // strcpy(x,x) -> x
return Src;
// These optimizations require TargetData.
if (!TD) return 0;
// See if we can get the length of the input string.
uint64_t Len = GetStringLength(Src);
// We have enough information to now generate the memcpy call to do the
// concatenation for us. Make a memcpy to copy the nul byte with align = 1.
if (OptChkCall)
EmitMemCpyChk(Dst, Src,
ConstantInt::get(TD->getIntPtrType(*Context), Len),
else
EmitMemCpy(Dst, Src,
ConstantInt::get(TD->getIntPtrType(*Context), Len),
1, false, B, TD);
return Dst;
}
};
//===---------------------------------------===//
// 'strncpy' Optimizations
struct StrNCpyOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
FT->getParamType(0) != FT->getParamType(1) ||
FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Duncan Sands
committed
!FT->getParamType(2)->isIntegerTy())
Value *Dst = CI->getArgOperand(0);
Value *Src = CI->getArgOperand(1);
Value *LenOp = CI->getArgOperand(2);
// See if we can get the length of the input string.
uint64_t SrcLen = GetStringLength(Src);
if (SrcLen == 0) return 0;
--SrcLen;
if (SrcLen == 0) {
// strncpy(x, "", y) -> memset(x, '\0', y, 1)
EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'),
LenOp, false, B, TD);
return Dst;
}
uint64_t Len;
if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
Len = LengthArg->getZExtValue();
else
return 0;
if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
// These optimizations require TargetData.
if (!TD) return 0;
// Let strncpy handle the zero padding
if (Len > SrcLen+1) return 0;
// strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
ConstantInt::get(TD->getIntPtrType(*Context), Len),
1, false, B, TD);
return Dst;
}
};
//===---------------------------------------===//
// 'strlen' Optimizations
struct StrLenOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 1 ||
FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Duncan Sands
committed
!FT->getReturnType()->isIntegerTy())
return 0;
// Constant folding: strlen("xyz") -> 3
if (uint64_t Len = GetStringLength(Src))
Owen Anderson
committed
return ConstantInt::get(CI->getType(), Len-1);
// strlen(x) != 0 --> *x != 0
// strlen(x) == 0 --> *x == 0
if (IsOnlyUsedInZeroEqualityComparison(CI))
return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
return 0;
}
};
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//===---------------------------------------===//
// 'strpbrk' Optimizations
struct StrPBrkOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 ||
FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
FT->getParamType(1) != FT->getParamType(0) ||
FT->getReturnType() != FT->getParamType(0))
return 0;
std::string S1, S2;
bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
// strpbrk(s, "") -> NULL
// strpbrk("", s) -> NULL
if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
return Constant::getNullValue(CI->getType());
// Constant folding.
if (HasS1 && HasS2) {
size_t I = S1.find_first_of(S2);
if (I == std::string::npos) // No match.
return Constant::getNullValue(CI->getType());
Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), I);
return B.CreateGEP(CI->getArgOperand(0), Idx, "strpbrk");
}
// strpbrk(s, "a") -> strchr(s, 'a')
if (TD && HasS2 && S2.size() == 1)
return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
return 0;
}
};
Nick Lewycky
committed
//===---------------------------------------===//
// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky
committed
struct StrToOpt : public LibCallOptimization {
Nick Lewycky
committed
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands
committed
!FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy())
Nick Lewycky
committed
return 0;
if (isa<ConstantPointerNull>(EndPtr)) {
CI->setOnlyReadsMemory();
Nick Lewycky
committed
CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky
committed
return 0;
}
};
//===---------------------------------------===//
// 'strstr' Optimizations
struct StrStrOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 2 ||
Duncan Sands
committed
!FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
!FT->getReturnType()->isPointerTy())
return 0;
// fold strstr(x, x) -> x.
if (CI->getArgOperand(0) == CI->getArgOperand(1))
return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Benjamin Kramer
committed
// fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer
committed
StrLen, B, TD);
for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
UI != UE; ) {
ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer
committed
Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
ConstantInt::getNullValue(StrNCmp->getType()),
"cmp");
Old->replaceAllUsesWith(Cmp);
Old->eraseFromParent();
}
return CI;
}
// See if either input string is a constant string.
std::string SearchStr, ToFindStr;
bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
// fold strstr(x, "") -> x.
if (HasStr2 && ToFindStr.empty())
return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
// If both strings are known, constant fold it.
if (HasStr1 && HasStr2) {
std::string::size_type Offset = SearchStr.find(ToFindStr);
if (Offset == std::string::npos) // strstr("foo", "bar") -> null
return Constant::getNullValue(CI->getType());
// strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
return B.CreateBitCast(Result, CI->getType());
}
// fold strstr(x, "y") -> strchr(x, 'y').
if (HasStr2 && ToFindStr.size() == 1)
return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
ToFindStr[0], B, TD), CI->getType());
return 0;
}
};
Nick Lewycky
committed
//===---------------------------------------===//
// 'memcmp' Optimizations
struct MemCmpOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
Duncan Sands
committed
if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
!FT->getReturnType()->isIntegerTy(32))
return 0;
Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Anderson
committed
return Constant::getNullValue(CI->getType());
// Make sure we have a constant length.
ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
uint64_t Len = LenC->getZExtValue();
if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Anderson
committed
return Constant::getNullValue(CI->getType());
// memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
if (Len == 1) {
Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
CI->getType(), "lhsv");
Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
CI->getType(), "rhsv");
// Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
std::string LHSStr, RHSStr;
if (GetConstantStringInfo(LHS, LHSStr) &&
GetConstantStringInfo(RHS, RHSStr)) {
// Make sure we're not reading out-of-bounds memory.
if (Len > LHSStr.length() || Len > RHSStr.length())
return 0;
uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
return ConstantInt::get(CI->getType(), Ret);
}
return 0;
}
};
//===---------------------------------------===//
// 'memcpy' Optimizations
struct MemCpyOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// These optimizations require TargetData.
if (!TD) return 0;
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands
committed
!FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
FT->getParamType(2) != TD->getIntPtrType(*Context))
return 0;
// memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
EmitMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), 1, false, B, TD);
return CI->getArgOperand(0);
}
};
//===---------------------------------------===//
// 'memmove' Optimizations
struct MemMoveOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// These optimizations require TargetData.
if (!TD) return 0;
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands
committed
!FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isPointerTy() ||
FT->getParamType(2) != TD->getIntPtrType(*Context))
return 0;
// memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
EmitMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
CI->getArgOperand(2), 1, false, B, TD);
return CI->getArgOperand(0);
}
};
//===---------------------------------------===//
// 'memset' Optimizations
struct MemSetOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
// These optimizations require TargetData.
if (!TD) return 0;
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands
committed
!FT->getParamType(0)->isPointerTy() ||
!FT->getParamType(1)->isIntegerTy() ||
FT->getParamType(2) != TD->getIntPtrType(*Context))
return 0;
// memset(p, v, n) -> llvm.memset(p, v, n, 1)
Value *Val = B.CreateIntCast(CI->getArgOperand(1),
Type::getInt8Ty(*Context), false);
EmitMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), false, B, TD);
return CI->getArgOperand(0);
}
};
//===----------------------------------------------------------------------===//
// Math Library Optimizations
//===----------------------------------------------------------------------===//
//===---------------------------------------===//
// 'pow*' Optimizations
struct PowOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 2 arguments of the same FP type, which match the
// result type.
if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
FT->getParamType(0) != FT->getParamType(1) ||
!FT->getParamType(0)->isFloatingPointTy())
return 0;
Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
return Op1C;
if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
if (Op2C == 0) return 0;
if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
return ConstantFP::get(CI->getType(), 1.0);
if (Op2C->isExactlyValue(0.5)) {
// Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
// This is faster than calling pow, and still handles negative zero
// and negative infinite correctly.
// TODO: In fast-math mode, this could be just sqrt(x).
// TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Value *Inf = ConstantFP::getInfinity(CI->getType());
Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
Callee->getAttributes());
Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
Callee->getAttributes());
Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
return Sel;
if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
return Op1;
if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
return B.CreateFMul(Op1, Op1, "pow2");
if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
return 0;
}
};
//===---------------------------------------===//
// 'exp2' Optimizations
struct Exp2Opt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 1 argument of FP type, which matches the
// result type.
if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
!FT->getParamType(0)->isFloatingPointTy())
// Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
// Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Value *LdExpArg = 0;
if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
LdExpArg = B.CreateSExt(OpC->getOperand(0),
} else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
LdExpArg = B.CreateZExt(OpC->getOperand(0),
if (LdExpArg) {
const char *Name;
if (Op->getType()->isFloatTy())
else if (Op->getType()->isDoubleTy())
Name = "ldexp";
else
Name = "ldexpl";
Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
if (!Op->getType()->isFloatTy())
One = ConstantExpr::getFPExtend(One, Op->getType());
Module *M = Caller->getParent();
Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Type::getInt32Ty(*Context),NULL);
CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
CI->setCallingConv(F->getCallingConv());
return CI;
}
return 0;
}
};
//===---------------------------------------===//
// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
struct UnaryDoubleFPOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
!FT->getParamType(0)->isDoubleTy())
return 0;
// If this is something like 'floor((double)floatval)', convert to floorf.
FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
return 0;
// floor((double)floatval) -> (double)floorf(floatval)
Value *V = Cast->getOperand(0);
V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
Callee->getAttributes());
return B.CreateFPExt(V, Type::getDoubleTy(*Context));
}
};
//===----------------------------------------------------------------------===//
// Integer Optimizations
//===----------------------------------------------------------------------===//
//===---------------------------------------===//
// 'ffs*' Optimizations
struct FFSOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
// Just make sure this has 2 arguments of the same FP type, which match the
// result type.
Duncan Sands
committed
!FT->getParamType(0)->isIntegerTy())
return 0;
// Constant fold.
if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Anderson
committed
return Constant::getNullValue(CI->getType());
return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
CI->getValue().countTrailingZeros()+1);
}
// ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
const Type *ArgType = Op->getType();
Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Intrinsic::cttz, &ArgType, 1);
Value *V = B.CreateCall(F, Op, "cttz");
Owen Anderson
committed
V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
Owen Anderson
committed
Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
}
};
//===---------------------------------------===//
// 'isdigit' Optimizations
struct IsDigitOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
// We require integer(i32)
Duncan Sands
committed
if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
!FT->getParamType(0)->isIntegerTy(32))
return 0;
// isdigit(c) -> (c-'0') <u 10
Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
return B.CreateZExt(Op, CI->getType());
}
};
//===---------------------------------------===//
// 'isascii' Optimizations
struct IsAsciiOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
// We require integer(i32)
Duncan Sands
committed
if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
!FT->getParamType(0)->isIntegerTy(32))
return 0;
// isascii(c) -> c <u 128
Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
return B.CreateZExt(Op, CI->getType());
}
};
//===---------------------------------------===//
// 'abs', 'labs', 'llabs' Optimizations
struct AbsOpt : public LibCallOptimization {
virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
const FunctionType *FT = Callee->getFunctionType();
// We require integer(integer) where the types agree.
Duncan Sands
committed
if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
FT->getParamType(0) != FT->getReturnType())
return 0;
Owen Anderson
committed
Constant::getAllOnesValue(Op->getType()),
"ispos");
Value *Neg = B.CreateNeg(Op, "neg");
return B.CreateSelect(Pos, Op, Neg);
}
};