1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
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 is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification. If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/DataLayout.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Function.h"
22 #include "llvm/IRBuilder.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Module.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Target/TargetLibraryInfo.h"
27 #include "llvm/Transforms/Utils/BuildLibCalls.h"
31 /// This class is the abstract base class for the set of optimizations that
32 /// corresponds to one library call.
34 class LibCallOptimization {
38 const TargetLibraryInfo *TLI;
39 const LibCallSimplifier *LCS;
42 LibCallOptimization() { }
43 virtual ~LibCallOptimization() {}
45 /// callOptimizer - This pure virtual method is implemented by base classes to
46 /// do various optimizations. If this returns null then no transformation was
47 /// performed. If it returns CI, then it transformed the call and CI is to be
48 /// deleted. If it returns something else, replace CI with the new value and
50 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
53 Value *optimizeCall(CallInst *CI, const DataLayout *TD,
54 const TargetLibraryInfo *TLI,
55 const LibCallSimplifier *LCS, IRBuilder<> &B) {
56 Caller = CI->getParent()->getParent();
60 if (CI->getCalledFunction())
61 Context = &CI->getCalledFunction()->getContext();
63 // We never change the calling convention.
64 if (CI->getCallingConv() != llvm::CallingConv::C)
67 return callOptimizer(CI->getCalledFunction(), CI, B);
71 //===----------------------------------------------------------------------===//
73 //===----------------------------------------------------------------------===//
75 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
76 /// value is equal or not-equal to zero.
77 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
78 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
80 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
82 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
85 // Unknown instruction.
91 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
92 /// comparisons with With.
93 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
94 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
96 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
97 if (IC->isEquality() && IC->getOperand(1) == With)
99 // Unknown instruction.
105 //===----------------------------------------------------------------------===//
106 // Fortified Library Call Optimizations
107 //===----------------------------------------------------------------------===//
109 struct FortifiedLibCallOptimization : public LibCallOptimization {
111 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
112 bool isString) const = 0;
115 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
118 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
119 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
121 if (ConstantInt *SizeCI =
122 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
123 if (SizeCI->isAllOnesValue())
126 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
127 // If the length is 0 we don't know how long it is and so we can't
129 if (Len == 0) return false;
130 return SizeCI->getZExtValue() >= Len;
132 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
133 CI->getArgOperand(SizeArgOp)))
134 return SizeCI->getZExtValue() >= Arg->getZExtValue();
140 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
141 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
143 FunctionType *FT = Callee->getFunctionType();
144 LLVMContext &Context = CI->getParent()->getContext();
146 // Check if this has the right signature.
147 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
148 !FT->getParamType(0)->isPointerTy() ||
149 !FT->getParamType(1)->isPointerTy() ||
150 FT->getParamType(2) != TD->getIntPtrType(Context) ||
151 FT->getParamType(3) != TD->getIntPtrType(Context))
154 if (isFoldable(3, 2, false)) {
155 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
156 CI->getArgOperand(2), 1);
157 return CI->getArgOperand(0);
163 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
164 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
166 FunctionType *FT = Callee->getFunctionType();
167 LLVMContext &Context = CI->getParent()->getContext();
169 // Check if this has the right signature.
170 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
171 !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isPointerTy() ||
173 FT->getParamType(2) != TD->getIntPtrType(Context) ||
174 FT->getParamType(3) != TD->getIntPtrType(Context))
177 if (isFoldable(3, 2, false)) {
178 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
179 CI->getArgOperand(2), 1);
180 return CI->getArgOperand(0);
186 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
187 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
189 FunctionType *FT = Callee->getFunctionType();
190 LLVMContext &Context = CI->getParent()->getContext();
192 // Check if this has the right signature.
193 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
194 !FT->getParamType(0)->isPointerTy() ||
195 !FT->getParamType(1)->isIntegerTy() ||
196 FT->getParamType(2) != TD->getIntPtrType(Context) ||
197 FT->getParamType(3) != TD->getIntPtrType(Context))
200 if (isFoldable(3, 2, false)) {
201 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
203 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
204 return CI->getArgOperand(0);
210 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
211 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
213 StringRef Name = Callee->getName();
214 FunctionType *FT = Callee->getFunctionType();
215 LLVMContext &Context = CI->getParent()->getContext();
217 // Check if this has the right signature.
218 if (FT->getNumParams() != 3 ||
219 FT->getReturnType() != FT->getParamType(0) ||
220 FT->getParamType(0) != FT->getParamType(1) ||
221 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
222 FT->getParamType(2) != TD->getIntPtrType(Context))
225 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
226 if (Dst == Src) // __strcpy_chk(x,x) -> x
229 // If a) we don't have any length information, or b) we know this will
230 // fit then just lower to a plain strcpy. Otherwise we'll keep our
231 // strcpy_chk call which may fail at runtime if the size is too long.
232 // TODO: It might be nice to get a maximum length out of the possible
233 // string lengths for varying.
234 if (isFoldable(2, 1, true)) {
235 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
238 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
239 uint64_t Len = GetStringLength(Src);
240 if (Len == 0) return 0;
242 // This optimization require DataLayout.
246 EmitMemCpyChk(Dst, Src,
247 ConstantInt::get(TD->getIntPtrType(Context), Len),
248 CI->getArgOperand(2), B, TD, TLI);
255 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
256 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
258 StringRef Name = Callee->getName();
259 FunctionType *FT = Callee->getFunctionType();
260 LLVMContext &Context = CI->getParent()->getContext();
262 // Check if this has the right signature.
263 if (FT->getNumParams() != 3 ||
264 FT->getReturnType() != FT->getParamType(0) ||
265 FT->getParamType(0) != FT->getParamType(1) ||
266 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
267 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
270 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
271 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
272 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
273 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
276 // If a) we don't have any length information, or b) we know this will
277 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
278 // stpcpy_chk call which may fail at runtime if the size is too long.
279 // TODO: It might be nice to get a maximum length out of the possible
280 // string lengths for varying.
281 if (isFoldable(2, 1, true)) {
282 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
285 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
286 uint64_t Len = GetStringLength(Src);
287 if (Len == 0) return 0;
289 // This optimization require DataLayout.
292 Type *PT = FT->getParamType(0);
293 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
294 Value *DstEnd = B.CreateGEP(Dst,
295 ConstantInt::get(TD->getIntPtrType(PT),
297 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI))
305 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
306 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
308 StringRef Name = Callee->getName();
309 FunctionType *FT = Callee->getFunctionType();
310 LLVMContext &Context = CI->getParent()->getContext();
312 // Check if this has the right signature.
313 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
314 FT->getParamType(0) != FT->getParamType(1) ||
315 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
316 !FT->getParamType(2)->isIntegerTy() ||
317 FT->getParamType(3) != TD->getIntPtrType(Context))
320 if (isFoldable(3, 2, false)) {
321 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
322 CI->getArgOperand(2), B, TD, TLI,
330 //===----------------------------------------------------------------------===//
331 // String and Memory Library Call Optimizations
332 //===----------------------------------------------------------------------===//
334 struct StrCatOpt : public LibCallOptimization {
335 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
336 // Verify the "strcat" function prototype.
337 FunctionType *FT = Callee->getFunctionType();
338 if (FT->getNumParams() != 2 ||
339 FT->getReturnType() != B.getInt8PtrTy() ||
340 FT->getParamType(0) != FT->getReturnType() ||
341 FT->getParamType(1) != FT->getReturnType())
344 // Extract some information from the instruction
345 Value *Dst = CI->getArgOperand(0);
346 Value *Src = CI->getArgOperand(1);
348 // See if we can get the length of the input string.
349 uint64_t Len = GetStringLength(Src);
350 if (Len == 0) return 0;
351 --Len; // Unbias length.
353 // Handle the simple, do-nothing case: strcat(x, "") -> x
357 // These optimizations require DataLayout.
360 return emitStrLenMemCpy(Src, Dst, Len, B);
363 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
365 // We need to find the end of the destination string. That's where the
366 // memory is to be moved to. We just generate a call to strlen.
367 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
371 // Now that we have the destination's length, we must index into the
372 // destination's pointer to get the actual memcpy destination (end of
373 // the string .. we're concatenating).
374 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
376 // We have enough information to now generate the memcpy call to do the
377 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
378 B.CreateMemCpy(CpyDst, Src,
379 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
384 struct StrNCatOpt : public StrCatOpt {
385 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
386 // Verify the "strncat" function prototype.
387 FunctionType *FT = Callee->getFunctionType();
388 if (FT->getNumParams() != 3 ||
389 FT->getReturnType() != B.getInt8PtrTy() ||
390 FT->getParamType(0) != FT->getReturnType() ||
391 FT->getParamType(1) != FT->getReturnType() ||
392 !FT->getParamType(2)->isIntegerTy())
395 // Extract some information from the instruction
396 Value *Dst = CI->getArgOperand(0);
397 Value *Src = CI->getArgOperand(1);
400 // We don't do anything if length is not constant
401 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
402 Len = LengthArg->getZExtValue();
406 // See if we can get the length of the input string.
407 uint64_t SrcLen = GetStringLength(Src);
408 if (SrcLen == 0) return 0;
409 --SrcLen; // Unbias length.
411 // Handle the simple, do-nothing cases:
412 // strncat(x, "", c) -> x
413 // strncat(x, c, 0) -> x
414 if (SrcLen == 0 || Len == 0) return Dst;
416 // These optimizations require DataLayout.
419 // We don't optimize this case
420 if (Len < SrcLen) return 0;
422 // strncat(x, s, c) -> strcat(x, s)
423 // s is constant so the strcat can be optimized further
424 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
428 struct StrChrOpt : public LibCallOptimization {
429 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
430 // Verify the "strchr" function prototype.
431 FunctionType *FT = Callee->getFunctionType();
432 if (FT->getNumParams() != 2 ||
433 FT->getReturnType() != B.getInt8PtrTy() ||
434 FT->getParamType(0) != FT->getReturnType() ||
435 !FT->getParamType(1)->isIntegerTy(32))
438 Value *SrcStr = CI->getArgOperand(0);
440 // If the second operand is non-constant, see if we can compute the length
441 // of the input string and turn this into memchr.
442 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
444 // These optimizations require DataLayout.
447 uint64_t Len = GetStringLength(SrcStr);
448 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
451 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
452 ConstantInt::get(TD->getIntPtrType(*Context), Len),
456 // Otherwise, the character is a constant, see if the first argument is
457 // a string literal. If so, we can constant fold.
459 if (!getConstantStringInfo(SrcStr, Str))
462 // Compute the offset, make sure to handle the case when we're searching for
463 // zero (a weird way to spell strlen).
464 size_t I = CharC->getSExtValue() == 0 ?
465 Str.size() : Str.find(CharC->getSExtValue());
466 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
467 return Constant::getNullValue(CI->getType());
469 // strchr(s+n,c) -> gep(s+n+i,c)
470 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
474 struct StrRChrOpt : public LibCallOptimization {
475 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
476 // Verify the "strrchr" function prototype.
477 FunctionType *FT = Callee->getFunctionType();
478 if (FT->getNumParams() != 2 ||
479 FT->getReturnType() != B.getInt8PtrTy() ||
480 FT->getParamType(0) != FT->getReturnType() ||
481 !FT->getParamType(1)->isIntegerTy(32))
484 Value *SrcStr = CI->getArgOperand(0);
485 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
487 // Cannot fold anything if we're not looking for a constant.
492 if (!getConstantStringInfo(SrcStr, Str)) {
493 // strrchr(s, 0) -> strchr(s, 0)
494 if (TD && CharC->isZero())
495 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
499 // Compute the offset.
500 size_t I = CharC->getSExtValue() == 0 ?
501 Str.size() : Str.rfind(CharC->getSExtValue());
502 if (I == StringRef::npos) // Didn't find the char. Return null.
503 return Constant::getNullValue(CI->getType());
505 // strrchr(s+n,c) -> gep(s+n+i,c)
506 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
510 struct StrCmpOpt : public LibCallOptimization {
511 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
512 // Verify the "strcmp" function prototype.
513 FunctionType *FT = Callee->getFunctionType();
514 if (FT->getNumParams() != 2 ||
515 !FT->getReturnType()->isIntegerTy(32) ||
516 FT->getParamType(0) != FT->getParamType(1) ||
517 FT->getParamType(0) != B.getInt8PtrTy())
520 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
521 if (Str1P == Str2P) // strcmp(x,x) -> 0
522 return ConstantInt::get(CI->getType(), 0);
524 StringRef Str1, Str2;
525 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
526 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
528 // strcmp(x, y) -> cnst (if both x and y are constant strings)
529 if (HasStr1 && HasStr2)
530 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
532 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
533 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
536 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
537 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
539 // strcmp(P, "x") -> memcmp(P, "x", 2)
540 uint64_t Len1 = GetStringLength(Str1P);
541 uint64_t Len2 = GetStringLength(Str2P);
543 // These optimizations require DataLayout.
546 return EmitMemCmp(Str1P, Str2P,
547 ConstantInt::get(TD->getIntPtrType(*Context),
548 std::min(Len1, Len2)), B, TD, TLI);
555 struct StrNCmpOpt : public LibCallOptimization {
556 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
557 // Verify the "strncmp" function prototype.
558 FunctionType *FT = Callee->getFunctionType();
559 if (FT->getNumParams() != 3 ||
560 !FT->getReturnType()->isIntegerTy(32) ||
561 FT->getParamType(0) != FT->getParamType(1) ||
562 FT->getParamType(0) != B.getInt8PtrTy() ||
563 !FT->getParamType(2)->isIntegerTy())
566 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
567 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
568 return ConstantInt::get(CI->getType(), 0);
570 // Get the length argument if it is constant.
572 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
573 Length = LengthArg->getZExtValue();
577 if (Length == 0) // strncmp(x,y,0) -> 0
578 return ConstantInt::get(CI->getType(), 0);
580 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
581 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
583 StringRef Str1, Str2;
584 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
585 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
587 // strncmp(x, y) -> cnst (if both x and y are constant strings)
588 if (HasStr1 && HasStr2) {
589 StringRef SubStr1 = Str1.substr(0, Length);
590 StringRef SubStr2 = Str2.substr(0, Length);
591 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
594 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
595 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
598 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
599 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
605 struct StrCpyOpt : public LibCallOptimization {
606 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
607 // Verify the "strcpy" function prototype.
608 FunctionType *FT = Callee->getFunctionType();
609 if (FT->getNumParams() != 2 ||
610 FT->getReturnType() != FT->getParamType(0) ||
611 FT->getParamType(0) != FT->getParamType(1) ||
612 FT->getParamType(0) != B.getInt8PtrTy())
615 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
616 if (Dst == Src) // strcpy(x,x) -> x
619 // These optimizations require DataLayout.
622 // See if we can get the length of the input string.
623 uint64_t Len = GetStringLength(Src);
624 if (Len == 0) return 0;
626 // We have enough information to now generate the memcpy call to do the
627 // copy for us. Make a memcpy to copy the nul byte with align = 1.
628 B.CreateMemCpy(Dst, Src,
629 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
634 struct StpCpyOpt: public LibCallOptimization {
635 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
636 // Verify the "stpcpy" function prototype.
637 FunctionType *FT = Callee->getFunctionType();
638 if (FT->getNumParams() != 2 ||
639 FT->getReturnType() != FT->getParamType(0) ||
640 FT->getParamType(0) != FT->getParamType(1) ||
641 FT->getParamType(0) != B.getInt8PtrTy())
644 // These optimizations require DataLayout.
647 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
648 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
649 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
650 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
653 // See if we can get the length of the input string.
654 uint64_t Len = GetStringLength(Src);
655 if (Len == 0) return 0;
657 Type *PT = FT->getParamType(0);
658 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
659 Value *DstEnd = B.CreateGEP(Dst,
660 ConstantInt::get(TD->getIntPtrType(PT),
663 // We have enough information to now generate the memcpy call to do the
664 // copy for us. Make a memcpy to copy the nul byte with align = 1.
665 B.CreateMemCpy(Dst, Src, LenV, 1);
670 struct StrNCpyOpt : public LibCallOptimization {
671 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
672 FunctionType *FT = Callee->getFunctionType();
673 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
674 FT->getParamType(0) != FT->getParamType(1) ||
675 FT->getParamType(0) != B.getInt8PtrTy() ||
676 !FT->getParamType(2)->isIntegerTy())
679 Value *Dst = CI->getArgOperand(0);
680 Value *Src = CI->getArgOperand(1);
681 Value *LenOp = CI->getArgOperand(2);
683 // See if we can get the length of the input string.
684 uint64_t SrcLen = GetStringLength(Src);
685 if (SrcLen == 0) return 0;
689 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
690 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
695 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
696 Len = LengthArg->getZExtValue();
700 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
702 // These optimizations require DataLayout.
705 // Let strncpy handle the zero padding
706 if (Len > SrcLen+1) return 0;
708 Type *PT = FT->getParamType(0);
709 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
710 B.CreateMemCpy(Dst, Src,
711 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
717 struct StrLenOpt : public LibCallOptimization {
718 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
719 FunctionType *FT = Callee->getFunctionType();
720 if (FT->getNumParams() != 1 ||
721 FT->getParamType(0) != B.getInt8PtrTy() ||
722 !FT->getReturnType()->isIntegerTy())
725 Value *Src = CI->getArgOperand(0);
727 // Constant folding: strlen("xyz") -> 3
728 if (uint64_t Len = GetStringLength(Src))
729 return ConstantInt::get(CI->getType(), Len-1);
731 // strlen(x) != 0 --> *x != 0
732 // strlen(x) == 0 --> *x == 0
733 if (isOnlyUsedInZeroEqualityComparison(CI))
734 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
739 struct StrPBrkOpt : public LibCallOptimization {
740 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
741 FunctionType *FT = Callee->getFunctionType();
742 if (FT->getNumParams() != 2 ||
743 FT->getParamType(0) != B.getInt8PtrTy() ||
744 FT->getParamType(1) != FT->getParamType(0) ||
745 FT->getReturnType() != FT->getParamType(0))
749 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
750 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
752 // strpbrk(s, "") -> NULL
753 // strpbrk("", s) -> NULL
754 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
755 return Constant::getNullValue(CI->getType());
758 if (HasS1 && HasS2) {
759 size_t I = S1.find_first_of(S2);
760 if (I == std::string::npos) // No match.
761 return Constant::getNullValue(CI->getType());
763 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
766 // strpbrk(s, "a") -> strchr(s, 'a')
767 if (TD && HasS2 && S2.size() == 1)
768 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
774 struct StrToOpt : public LibCallOptimization {
775 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
776 FunctionType *FT = Callee->getFunctionType();
777 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
778 !FT->getParamType(0)->isPointerTy() ||
779 !FT->getParamType(1)->isPointerTy())
782 Value *EndPtr = CI->getArgOperand(1);
783 if (isa<ConstantPointerNull>(EndPtr)) {
784 // With a null EndPtr, this function won't capture the main argument.
785 // It would be readonly too, except that it still may write to errno.
786 CI->addAttribute(1, Attributes::get(Callee->getContext(),
787 Attributes::NoCapture));
794 struct StrSpnOpt : public LibCallOptimization {
795 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
796 FunctionType *FT = Callee->getFunctionType();
797 if (FT->getNumParams() != 2 ||
798 FT->getParamType(0) != B.getInt8PtrTy() ||
799 FT->getParamType(1) != FT->getParamType(0) ||
800 !FT->getReturnType()->isIntegerTy())
804 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
805 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
807 // strspn(s, "") -> 0
808 // strspn("", s) -> 0
809 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
810 return Constant::getNullValue(CI->getType());
813 if (HasS1 && HasS2) {
814 size_t Pos = S1.find_first_not_of(S2);
815 if (Pos == StringRef::npos) Pos = S1.size();
816 return ConstantInt::get(CI->getType(), Pos);
823 struct StrCSpnOpt : public LibCallOptimization {
824 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
825 FunctionType *FT = Callee->getFunctionType();
826 if (FT->getNumParams() != 2 ||
827 FT->getParamType(0) != B.getInt8PtrTy() ||
828 FT->getParamType(1) != FT->getParamType(0) ||
829 !FT->getReturnType()->isIntegerTy())
833 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
834 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
836 // strcspn("", s) -> 0
837 if (HasS1 && S1.empty())
838 return Constant::getNullValue(CI->getType());
841 if (HasS1 && HasS2) {
842 size_t Pos = S1.find_first_of(S2);
843 if (Pos == StringRef::npos) Pos = S1.size();
844 return ConstantInt::get(CI->getType(), Pos);
847 // strcspn(s, "") -> strlen(s)
848 if (TD && HasS2 && S2.empty())
849 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
855 struct StrStrOpt : public LibCallOptimization {
856 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
857 FunctionType *FT = Callee->getFunctionType();
858 if (FT->getNumParams() != 2 ||
859 !FT->getParamType(0)->isPointerTy() ||
860 !FT->getParamType(1)->isPointerTy() ||
861 !FT->getReturnType()->isPointerTy())
864 // fold strstr(x, x) -> x.
865 if (CI->getArgOperand(0) == CI->getArgOperand(1))
866 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
868 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
869 if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
870 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
873 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
877 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
879 ICmpInst *Old = cast<ICmpInst>(*UI++);
880 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
881 ConstantInt::getNullValue(StrNCmp->getType()),
883 LCS->replaceAllUsesWith(Old, Cmp);
888 // See if either input string is a constant string.
889 StringRef SearchStr, ToFindStr;
890 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
891 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
893 // fold strstr(x, "") -> x.
894 if (HasStr2 && ToFindStr.empty())
895 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
897 // If both strings are known, constant fold it.
898 if (HasStr1 && HasStr2) {
899 std::string::size_type Offset = SearchStr.find(ToFindStr);
901 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
902 return Constant::getNullValue(CI->getType());
904 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
905 Value *Result = CastToCStr(CI->getArgOperand(0), B);
906 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
907 return B.CreateBitCast(Result, CI->getType());
910 // fold strstr(x, "y") -> strchr(x, 'y').
911 if (HasStr2 && ToFindStr.size() == 1) {
912 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
913 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
919 struct MemCmpOpt : public LibCallOptimization {
920 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
921 FunctionType *FT = Callee->getFunctionType();
922 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
923 !FT->getParamType(1)->isPointerTy() ||
924 !FT->getReturnType()->isIntegerTy(32))
927 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
929 if (LHS == RHS) // memcmp(s,s,x) -> 0
930 return Constant::getNullValue(CI->getType());
932 // Make sure we have a constant length.
933 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
935 uint64_t Len = LenC->getZExtValue();
937 if (Len == 0) // memcmp(s1,s2,0) -> 0
938 return Constant::getNullValue(CI->getType());
940 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
942 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
943 CI->getType(), "lhsv");
944 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
945 CI->getType(), "rhsv");
946 return B.CreateSub(LHSV, RHSV, "chardiff");
949 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
950 StringRef LHSStr, RHSStr;
951 if (getConstantStringInfo(LHS, LHSStr) &&
952 getConstantStringInfo(RHS, RHSStr)) {
953 // Make sure we're not reading out-of-bounds memory.
954 if (Len > LHSStr.size() || Len > RHSStr.size())
956 // Fold the memcmp and normalize the result. This way we get consistent
957 // results across multiple platforms.
959 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
964 return ConstantInt::get(CI->getType(), Ret);
971 struct MemCpyOpt : public LibCallOptimization {
972 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
973 // These optimizations require DataLayout.
976 FunctionType *FT = Callee->getFunctionType();
977 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
978 !FT->getParamType(0)->isPointerTy() ||
979 !FT->getParamType(1)->isPointerTy() ||
980 FT->getParamType(2) != TD->getIntPtrType(*Context))
983 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
984 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
985 CI->getArgOperand(2), 1);
986 return CI->getArgOperand(0);
990 struct MemMoveOpt : public LibCallOptimization {
991 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
992 // These optimizations require DataLayout.
995 FunctionType *FT = Callee->getFunctionType();
996 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
997 !FT->getParamType(0)->isPointerTy() ||
998 !FT->getParamType(1)->isPointerTy() ||
999 FT->getParamType(2) != TD->getIntPtrType(*Context))
1002 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1003 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1004 CI->getArgOperand(2), 1);
1005 return CI->getArgOperand(0);
1009 struct MemSetOpt : public LibCallOptimization {
1010 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1011 // These optimizations require DataLayout.
1014 FunctionType *FT = Callee->getFunctionType();
1015 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1016 !FT->getParamType(0)->isPointerTy() ||
1017 !FT->getParamType(1)->isIntegerTy() ||
1018 FT->getParamType(2) != TD->getIntPtrType(*Context))
1021 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1022 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1023 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1024 return CI->getArgOperand(0);
1028 //===----------------------------------------------------------------------===//
1029 // Math Library Optimizations
1030 //===----------------------------------------------------------------------===//
1032 //===----------------------------------------------------------------------===//
1033 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1035 struct UnaryDoubleFPOpt : public LibCallOptimization {
1037 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1038 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1039 FunctionType *FT = Callee->getFunctionType();
1040 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1041 !FT->getParamType(0)->isDoubleTy())
1045 // Check if all the uses for function like 'sin' are converted to float.
1046 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1048 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1049 if (Cast == 0 || !Cast->getType()->isFloatTy())
1054 // If this is something like 'floor((double)floatval)', convert to floorf.
1055 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1056 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1059 // floor((double)floatval) -> (double)floorf(floatval)
1060 Value *V = Cast->getOperand(0);
1061 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1062 return B.CreateFPExt(V, B.getDoubleTy());
1066 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1067 bool UnsafeFPShrink;
1068 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1069 this->UnsafeFPShrink = UnsafeFPShrink;
1073 struct CosOpt : public UnsafeFPLibCallOptimization {
1074 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1075 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1077 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1078 TLI->has(LibFunc::cosf)) {
1079 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1080 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1083 FunctionType *FT = Callee->getFunctionType();
1084 // Just make sure this has 1 argument of FP type, which matches the
1086 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1087 !FT->getParamType(0)->isFloatingPointTy())
1090 // cos(-x) -> cos(x)
1091 Value *Op1 = CI->getArgOperand(0);
1092 if (BinaryOperator::isFNeg(Op1)) {
1093 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1094 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1100 struct PowOpt : public UnsafeFPLibCallOptimization {
1101 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1102 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1104 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1105 TLI->has(LibFunc::powf)) {
1106 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1107 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1110 FunctionType *FT = Callee->getFunctionType();
1111 // Just make sure this has 2 arguments of the same FP type, which match the
1113 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1114 FT->getParamType(0) != FT->getParamType(1) ||
1115 !FT->getParamType(0)->isFloatingPointTy())
1118 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1119 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1120 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1122 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1123 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1126 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1127 if (Op2C == 0) return Ret;
1129 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1130 return ConstantFP::get(CI->getType(), 1.0);
1132 if (Op2C->isExactlyValue(0.5)) {
1133 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1134 // This is faster than calling pow, and still handles negative zero
1135 // and negative infinity correctly.
1136 // TODO: In fast-math mode, this could be just sqrt(x).
1137 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1138 Value *Inf = ConstantFP::getInfinity(CI->getType());
1139 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1140 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1141 Callee->getAttributes());
1142 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1143 Callee->getAttributes());
1144 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1145 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1149 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1151 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1152 return B.CreateFMul(Op1, Op1, "pow2");
1153 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1154 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1160 struct Exp2Opt : public UnsafeFPLibCallOptimization {
1161 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1162 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1164 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1165 TLI->has(LibFunc::exp2)) {
1166 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1167 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1170 FunctionType *FT = Callee->getFunctionType();
1171 // Just make sure this has 1 argument of FP type, which matches the
1173 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1174 !FT->getParamType(0)->isFloatingPointTy())
1177 Value *Op = CI->getArgOperand(0);
1178 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1179 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1180 Value *LdExpArg = 0;
1181 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1182 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1183 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1184 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1185 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1186 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1191 if (Op->getType()->isFloatTy())
1193 else if (Op->getType()->isDoubleTy())
1198 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1199 if (!Op->getType()->isFloatTy())
1200 One = ConstantExpr::getFPExtend(One, Op->getType());
1202 Module *M = Caller->getParent();
1203 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1205 B.getInt32Ty(), NULL);
1206 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1207 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1208 CI->setCallingConv(F->getCallingConv());
1216 //===----------------------------------------------------------------------===//
1217 // Integer Library Call Optimizations
1218 //===----------------------------------------------------------------------===//
1220 struct FFSOpt : public LibCallOptimization {
1221 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1222 FunctionType *FT = Callee->getFunctionType();
1223 // Just make sure this has 2 arguments of the same FP type, which match the
1225 if (FT->getNumParams() != 1 ||
1226 !FT->getReturnType()->isIntegerTy(32) ||
1227 !FT->getParamType(0)->isIntegerTy())
1230 Value *Op = CI->getArgOperand(0);
1233 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1234 if (CI->isZero()) // ffs(0) -> 0.
1235 return B.getInt32(0);
1236 // ffs(c) -> cttz(c)+1
1237 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1240 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1241 Type *ArgType = Op->getType();
1242 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1243 Intrinsic::cttz, ArgType);
1244 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1245 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1246 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1248 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1249 return B.CreateSelect(Cond, V, B.getInt32(0));
1253 struct AbsOpt : public LibCallOptimization {
1254 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1255 FunctionType *FT = Callee->getFunctionType();
1256 // We require integer(integer) where the types agree.
1257 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1258 FT->getParamType(0) != FT->getReturnType())
1261 // abs(x) -> x >s -1 ? x : -x
1262 Value *Op = CI->getArgOperand(0);
1263 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1265 Value *Neg = B.CreateNeg(Op, "neg");
1266 return B.CreateSelect(Pos, Op, Neg);
1270 struct IsDigitOpt : public LibCallOptimization {
1271 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1272 FunctionType *FT = Callee->getFunctionType();
1273 // We require integer(i32)
1274 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1275 !FT->getParamType(0)->isIntegerTy(32))
1278 // isdigit(c) -> (c-'0') <u 10
1279 Value *Op = CI->getArgOperand(0);
1280 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1281 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1282 return B.CreateZExt(Op, CI->getType());
1286 } // End anonymous namespace.
1290 class LibCallSimplifierImpl {
1291 const DataLayout *TD;
1292 const TargetLibraryInfo *TLI;
1293 const LibCallSimplifier *LCS;
1294 bool UnsafeFPShrink;
1295 StringMap<LibCallOptimization*> Optimizations;
1297 // Fortified library call optimizations.
1298 MemCpyChkOpt MemCpyChk;
1299 MemMoveChkOpt MemMoveChk;
1300 MemSetChkOpt MemSetChk;
1301 StrCpyChkOpt StrCpyChk;
1302 StpCpyChkOpt StpCpyChk;
1303 StrNCpyChkOpt StrNCpyChk;
1305 // String library call optimizations.
1322 // Memory library call optimizations.
1328 // Math library call optimizations.
1329 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
1330 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1332 // Integer library call optimizations.
1337 void initOptimizations();
1338 void addOpt(LibFunc::Func F, LibCallOptimization* Opt);
1339 void addOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1341 LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
1342 const LibCallSimplifier *LCS,
1343 bool UnsafeFPShrink = false)
1344 : UnaryDoubleFP(false), UnsafeUnaryDoubleFP(true),
1345 Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
1349 this->UnsafeFPShrink = UnsafeFPShrink;
1352 Value *optimizeCall(CallInst *CI);
1355 void LibCallSimplifierImpl::initOptimizations() {
1356 // Fortified library call optimizations.
1357 Optimizations["__memcpy_chk"] = &MemCpyChk;
1358 Optimizations["__memmove_chk"] = &MemMoveChk;
1359 Optimizations["__memset_chk"] = &MemSetChk;
1360 Optimizations["__strcpy_chk"] = &StrCpyChk;
1361 Optimizations["__stpcpy_chk"] = &StpCpyChk;
1362 Optimizations["__strncpy_chk"] = &StrNCpyChk;
1363 Optimizations["__stpncpy_chk"] = &StrNCpyChk;
1365 // String library call optimizations.
1366 addOpt(LibFunc::strcat, &StrCat);
1367 addOpt(LibFunc::strncat, &StrNCat);
1368 addOpt(LibFunc::strchr, &StrChr);
1369 addOpt(LibFunc::strrchr, &StrRChr);
1370 addOpt(LibFunc::strcmp, &StrCmp);
1371 addOpt(LibFunc::strncmp, &StrNCmp);
1372 addOpt(LibFunc::strcpy, &StrCpy);
1373 addOpt(LibFunc::stpcpy, &StpCpy);
1374 addOpt(LibFunc::strncpy, &StrNCpy);
1375 addOpt(LibFunc::strlen, &StrLen);
1376 addOpt(LibFunc::strpbrk, &StrPBrk);
1377 addOpt(LibFunc::strtol, &StrTo);
1378 addOpt(LibFunc::strtod, &StrTo);
1379 addOpt(LibFunc::strtof, &StrTo);
1380 addOpt(LibFunc::strtoul, &StrTo);
1381 addOpt(LibFunc::strtoll, &StrTo);
1382 addOpt(LibFunc::strtold, &StrTo);
1383 addOpt(LibFunc::strtoull, &StrTo);
1384 addOpt(LibFunc::strspn, &StrSpn);
1385 addOpt(LibFunc::strcspn, &StrCSpn);
1386 addOpt(LibFunc::strstr, &StrStr);
1388 // Memory library call optimizations.
1389 addOpt(LibFunc::memcmp, &MemCmp);
1390 addOpt(LibFunc::memcpy, &MemCpy);
1391 addOpt(LibFunc::memmove, &MemMove);
1392 addOpt(LibFunc::memset, &MemSet);
1394 // Math library call optimizations.
1395 addOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1396 addOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
1397 addOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1398 addOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1399 addOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1400 addOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1401 addOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
1403 if(UnsafeFPShrink) {
1404 addOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1405 addOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1406 addOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1407 addOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1408 addOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1409 addOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1410 addOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1411 addOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1412 addOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1413 addOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1414 addOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1415 addOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1416 addOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1417 addOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1418 addOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1419 addOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1420 addOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1421 addOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1422 addOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1423 addOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1424 addOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1427 addOpt(LibFunc::cosf, &Cos);
1428 addOpt(LibFunc::cos, &Cos);
1429 addOpt(LibFunc::cosl, &Cos);
1430 addOpt(LibFunc::powf, &Pow);
1431 addOpt(LibFunc::pow, &Pow);
1432 addOpt(LibFunc::powl, &Pow);
1433 Optimizations["llvm.pow.f32"] = &Pow;
1434 Optimizations["llvm.pow.f64"] = &Pow;
1435 Optimizations["llvm.pow.f80"] = &Pow;
1436 Optimizations["llvm.pow.f128"] = &Pow;
1437 Optimizations["llvm.pow.ppcf128"] = &Pow;
1438 addOpt(LibFunc::exp2l, &Exp2);
1439 addOpt(LibFunc::exp2, &Exp2);
1440 addOpt(LibFunc::exp2f, &Exp2);
1441 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1442 Optimizations["llvm.exp2.f128"] = &Exp2;
1443 Optimizations["llvm.exp2.f80"] = &Exp2;
1444 Optimizations["llvm.exp2.f64"] = &Exp2;
1445 Optimizations["llvm.exp2.f32"] = &Exp2;
1447 // Integer library call optimizations.
1448 addOpt(LibFunc::ffs, &FFS);
1449 addOpt(LibFunc::ffsl, &FFS);
1450 addOpt(LibFunc::ffsll, &FFS);
1451 addOpt(LibFunc::abs, &Abs);
1452 addOpt(LibFunc::labs, &Abs);
1453 addOpt(LibFunc::llabs, &Abs);
1454 addOpt(LibFunc::isdigit, &IsDigit);
1457 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
1458 if (Optimizations.empty())
1459 initOptimizations();
1461 Function *Callee = CI->getCalledFunction();
1462 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1464 IRBuilder<> Builder(CI);
1465 return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
1470 void LibCallSimplifierImpl::addOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1472 Optimizations[TLI->getName(F)] = Opt;
1475 void LibCallSimplifierImpl::addOpt(LibFunc::Func F1, LibFunc::Func F2,
1476 LibCallOptimization* Opt) {
1477 if (TLI->has(F1) && TLI->has(F2))
1478 Optimizations[TLI->getName(F1)] = Opt;
1481 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
1482 const TargetLibraryInfo *TLI,
1483 bool UnsafeFPShrink) {
1484 Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink);
1487 LibCallSimplifier::~LibCallSimplifier() {
1491 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1492 return Impl->optimizeCall(CI);
1495 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
1496 I->replaceAllUsesWith(With);
1497 I->eraseFromParent();