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/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 /// This class is the abstract base class for the set of optimizations that
36 /// corresponds to one library call.
38 class LibCallOptimization {
42 const TargetLibraryInfo *TLI;
43 const LibCallSimplifier *LCS;
46 LibCallOptimization() { }
47 virtual ~LibCallOptimization() {}
49 /// callOptimizer - This pure virtual method is implemented by base classes to
50 /// do various optimizations. If this returns null then no transformation was
51 /// performed. If it returns CI, then it transformed the call and CI is to be
52 /// deleted. If it returns something else, replace CI with the new value and
54 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
57 /// ignoreCallingConv - Returns false if this transformation could possibly
58 /// change the calling convention.
59 virtual bool ignoreCallingConv() { return false; }
61 Value *optimizeCall(CallInst *CI, const DataLayout *TD,
62 const TargetLibraryInfo *TLI,
63 const LibCallSimplifier *LCS, IRBuilder<> &B) {
64 Caller = CI->getParent()->getParent();
68 if (CI->getCalledFunction())
69 Context = &CI->getCalledFunction()->getContext();
71 // We never change the calling convention.
72 if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
75 return callOptimizer(CI->getCalledFunction(), CI, B);
79 //===----------------------------------------------------------------------===//
81 //===----------------------------------------------------------------------===//
83 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
84 /// value is equal or not-equal to zero.
85 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
86 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
88 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
90 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
93 // Unknown instruction.
99 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
100 /// comparisons with With.
101 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
102 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
104 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
105 if (IC->isEquality() && IC->getOperand(1) == With)
107 // Unknown instruction.
113 static bool callHasFloatingPointArgument(const CallInst *CI) {
114 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
116 if ((*it)->getType()->isFloatingPointTy())
122 /// \brief Check whether the overloaded unary floating point function
123 /// corresponing to \a Ty is available.
124 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
125 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
126 LibFunc::Func LongDoubleFn) {
127 switch (Ty->getTypeID()) {
128 case Type::FloatTyID:
129 return TLI->has(FloatFn);
130 case Type::DoubleTyID:
131 return TLI->has(DoubleFn);
133 return TLI->has(LongDoubleFn);
137 //===----------------------------------------------------------------------===//
138 // Fortified Library Call Optimizations
139 //===----------------------------------------------------------------------===//
141 struct FortifiedLibCallOptimization : public LibCallOptimization {
143 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
144 bool isString) const = 0;
147 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
150 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
151 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
153 if (ConstantInt *SizeCI =
154 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
155 if (SizeCI->isAllOnesValue())
158 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
159 // If the length is 0 we don't know how long it is and so we can't
161 if (Len == 0) return false;
162 return SizeCI->getZExtValue() >= Len;
164 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
165 CI->getArgOperand(SizeArgOp)))
166 return SizeCI->getZExtValue() >= Arg->getZExtValue();
172 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
173 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
175 FunctionType *FT = Callee->getFunctionType();
176 LLVMContext &Context = CI->getParent()->getContext();
178 // Check if this has the right signature.
179 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
180 !FT->getParamType(0)->isPointerTy() ||
181 !FT->getParamType(1)->isPointerTy() ||
182 FT->getParamType(2) != TD->getIntPtrType(Context) ||
183 FT->getParamType(3) != TD->getIntPtrType(Context))
186 if (isFoldable(3, 2, false)) {
187 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
188 CI->getArgOperand(2), 1);
189 return CI->getArgOperand(0);
195 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
196 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
198 FunctionType *FT = Callee->getFunctionType();
199 LLVMContext &Context = CI->getParent()->getContext();
201 // Check if this has the right signature.
202 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
203 !FT->getParamType(0)->isPointerTy() ||
204 !FT->getParamType(1)->isPointerTy() ||
205 FT->getParamType(2) != TD->getIntPtrType(Context) ||
206 FT->getParamType(3) != TD->getIntPtrType(Context))
209 if (isFoldable(3, 2, false)) {
210 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
211 CI->getArgOperand(2), 1);
212 return CI->getArgOperand(0);
218 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
219 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
221 FunctionType *FT = Callee->getFunctionType();
222 LLVMContext &Context = CI->getParent()->getContext();
224 // Check if this has the right signature.
225 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
226 !FT->getParamType(0)->isPointerTy() ||
227 !FT->getParamType(1)->isIntegerTy() ||
228 FT->getParamType(2) != TD->getIntPtrType(Context) ||
229 FT->getParamType(3) != TD->getIntPtrType(Context))
232 if (isFoldable(3, 2, false)) {
233 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
235 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
236 return CI->getArgOperand(0);
242 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
243 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
245 StringRef Name = Callee->getName();
246 FunctionType *FT = Callee->getFunctionType();
247 LLVMContext &Context = CI->getParent()->getContext();
249 // Check if this has the right signature.
250 if (FT->getNumParams() != 3 ||
251 FT->getReturnType() != FT->getParamType(0) ||
252 FT->getParamType(0) != FT->getParamType(1) ||
253 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
254 FT->getParamType(2) != TD->getIntPtrType(Context))
257 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
258 if (Dst == Src) // __strcpy_chk(x,x) -> x
261 // If a) we don't have any length information, or b) we know this will
262 // fit then just lower to a plain strcpy. Otherwise we'll keep our
263 // strcpy_chk call which may fail at runtime if the size is too long.
264 // TODO: It might be nice to get a maximum length out of the possible
265 // string lengths for varying.
266 if (isFoldable(2, 1, true)) {
267 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
270 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
271 uint64_t Len = GetStringLength(Src);
272 if (Len == 0) return 0;
274 // This optimization require DataLayout.
278 EmitMemCpyChk(Dst, Src,
279 ConstantInt::get(TD->getIntPtrType(Context), Len),
280 CI->getArgOperand(2), B, TD, TLI);
287 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
288 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
290 StringRef Name = Callee->getName();
291 FunctionType *FT = Callee->getFunctionType();
292 LLVMContext &Context = CI->getParent()->getContext();
294 // Check if this has the right signature.
295 if (FT->getNumParams() != 3 ||
296 FT->getReturnType() != FT->getParamType(0) ||
297 FT->getParamType(0) != FT->getParamType(1) ||
298 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
299 FT->getParamType(2) != TD->getIntPtrType(FT->getParamType(0)))
302 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
303 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
304 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
305 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
308 // If a) we don't have any length information, or b) we know this will
309 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
310 // stpcpy_chk call which may fail at runtime if the size is too long.
311 // TODO: It might be nice to get a maximum length out of the possible
312 // string lengths for varying.
313 if (isFoldable(2, 1, true)) {
314 Value *Ret = EmitStrCpy(Dst, Src, B, TD, TLI, Name.substr(2, 6));
317 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
318 uint64_t Len = GetStringLength(Src);
319 if (Len == 0) return 0;
321 // This optimization require DataLayout.
324 Type *PT = FT->getParamType(0);
325 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
326 Value *DstEnd = B.CreateGEP(Dst,
327 ConstantInt::get(TD->getIntPtrType(PT),
329 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, TD, TLI))
337 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
338 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
340 StringRef Name = Callee->getName();
341 FunctionType *FT = Callee->getFunctionType();
342 LLVMContext &Context = CI->getParent()->getContext();
344 // Check if this has the right signature.
345 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
346 FT->getParamType(0) != FT->getParamType(1) ||
347 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
348 !FT->getParamType(2)->isIntegerTy() ||
349 FT->getParamType(3) != TD->getIntPtrType(Context))
352 if (isFoldable(3, 2, false)) {
353 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
354 CI->getArgOperand(2), B, TD, TLI,
362 //===----------------------------------------------------------------------===//
363 // String and Memory Library Call Optimizations
364 //===----------------------------------------------------------------------===//
366 struct StrCatOpt : public LibCallOptimization {
367 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
368 // Verify the "strcat" function prototype.
369 FunctionType *FT = Callee->getFunctionType();
370 if (FT->getNumParams() != 2 ||
371 FT->getReturnType() != B.getInt8PtrTy() ||
372 FT->getParamType(0) != FT->getReturnType() ||
373 FT->getParamType(1) != FT->getReturnType())
376 // Extract some information from the instruction
377 Value *Dst = CI->getArgOperand(0);
378 Value *Src = CI->getArgOperand(1);
380 // See if we can get the length of the input string.
381 uint64_t Len = GetStringLength(Src);
382 if (Len == 0) return 0;
383 --Len; // Unbias length.
385 // Handle the simple, do-nothing case: strcat(x, "") -> x
389 // These optimizations require DataLayout.
392 return emitStrLenMemCpy(Src, Dst, Len, B);
395 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
397 // We need to find the end of the destination string. That's where the
398 // memory is to be moved to. We just generate a call to strlen.
399 Value *DstLen = EmitStrLen(Dst, B, TD, TLI);
403 // Now that we have the destination's length, we must index into the
404 // destination's pointer to get the actual memcpy destination (end of
405 // the string .. we're concatenating).
406 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
408 // We have enough information to now generate the memcpy call to do the
409 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
410 B.CreateMemCpy(CpyDst, Src,
411 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
416 struct StrNCatOpt : public StrCatOpt {
417 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
418 // Verify the "strncat" function prototype.
419 FunctionType *FT = Callee->getFunctionType();
420 if (FT->getNumParams() != 3 ||
421 FT->getReturnType() != B.getInt8PtrTy() ||
422 FT->getParamType(0) != FT->getReturnType() ||
423 FT->getParamType(1) != FT->getReturnType() ||
424 !FT->getParamType(2)->isIntegerTy())
427 // Extract some information from the instruction
428 Value *Dst = CI->getArgOperand(0);
429 Value *Src = CI->getArgOperand(1);
432 // We don't do anything if length is not constant
433 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
434 Len = LengthArg->getZExtValue();
438 // See if we can get the length of the input string.
439 uint64_t SrcLen = GetStringLength(Src);
440 if (SrcLen == 0) return 0;
441 --SrcLen; // Unbias length.
443 // Handle the simple, do-nothing cases:
444 // strncat(x, "", c) -> x
445 // strncat(x, c, 0) -> x
446 if (SrcLen == 0 || Len == 0) return Dst;
448 // These optimizations require DataLayout.
451 // We don't optimize this case
452 if (Len < SrcLen) return 0;
454 // strncat(x, s, c) -> strcat(x, s)
455 // s is constant so the strcat can be optimized further
456 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
460 struct StrChrOpt : public LibCallOptimization {
461 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
462 // Verify the "strchr" function prototype.
463 FunctionType *FT = Callee->getFunctionType();
464 if (FT->getNumParams() != 2 ||
465 FT->getReturnType() != B.getInt8PtrTy() ||
466 FT->getParamType(0) != FT->getReturnType() ||
467 !FT->getParamType(1)->isIntegerTy(32))
470 Value *SrcStr = CI->getArgOperand(0);
472 // If the second operand is non-constant, see if we can compute the length
473 // of the input string and turn this into memchr.
474 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
476 // These optimizations require DataLayout.
479 uint64_t Len = GetStringLength(SrcStr);
480 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
483 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
484 ConstantInt::get(TD->getIntPtrType(*Context), Len),
488 // Otherwise, the character is a constant, see if the first argument is
489 // a string literal. If so, we can constant fold.
491 if (!getConstantStringInfo(SrcStr, Str))
494 // Compute the offset, make sure to handle the case when we're searching for
495 // zero (a weird way to spell strlen).
496 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
497 Str.size() : Str.find(CharC->getSExtValue());
498 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
499 return Constant::getNullValue(CI->getType());
501 // strchr(s+n,c) -> gep(s+n+i,c)
502 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
506 struct StrRChrOpt : public LibCallOptimization {
507 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
508 // Verify the "strrchr" function prototype.
509 FunctionType *FT = Callee->getFunctionType();
510 if (FT->getNumParams() != 2 ||
511 FT->getReturnType() != B.getInt8PtrTy() ||
512 FT->getParamType(0) != FT->getReturnType() ||
513 !FT->getParamType(1)->isIntegerTy(32))
516 Value *SrcStr = CI->getArgOperand(0);
517 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
519 // Cannot fold anything if we're not looking for a constant.
524 if (!getConstantStringInfo(SrcStr, Str)) {
525 // strrchr(s, 0) -> strchr(s, 0)
526 if (TD && CharC->isZero())
527 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
531 // Compute the offset.
532 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
533 Str.size() : Str.rfind(CharC->getSExtValue());
534 if (I == StringRef::npos) // Didn't find the char. Return null.
535 return Constant::getNullValue(CI->getType());
537 // strrchr(s+n,c) -> gep(s+n+i,c)
538 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
542 struct StrCmpOpt : public LibCallOptimization {
543 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
544 // Verify the "strcmp" function prototype.
545 FunctionType *FT = Callee->getFunctionType();
546 if (FT->getNumParams() != 2 ||
547 !FT->getReturnType()->isIntegerTy(32) ||
548 FT->getParamType(0) != FT->getParamType(1) ||
549 FT->getParamType(0) != B.getInt8PtrTy())
552 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
553 if (Str1P == Str2P) // strcmp(x,x) -> 0
554 return ConstantInt::get(CI->getType(), 0);
556 StringRef Str1, Str2;
557 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
558 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
560 // strcmp(x, y) -> cnst (if both x and y are constant strings)
561 if (HasStr1 && HasStr2)
562 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
564 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
565 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
568 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
569 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
571 // strcmp(P, "x") -> memcmp(P, "x", 2)
572 uint64_t Len1 = GetStringLength(Str1P);
573 uint64_t Len2 = GetStringLength(Str2P);
575 // These optimizations require DataLayout.
578 return EmitMemCmp(Str1P, Str2P,
579 ConstantInt::get(TD->getIntPtrType(*Context),
580 std::min(Len1, Len2)), B, TD, TLI);
587 struct StrNCmpOpt : public LibCallOptimization {
588 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
589 // Verify the "strncmp" function prototype.
590 FunctionType *FT = Callee->getFunctionType();
591 if (FT->getNumParams() != 3 ||
592 !FT->getReturnType()->isIntegerTy(32) ||
593 FT->getParamType(0) != FT->getParamType(1) ||
594 FT->getParamType(0) != B.getInt8PtrTy() ||
595 !FT->getParamType(2)->isIntegerTy())
598 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
599 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
600 return ConstantInt::get(CI->getType(), 0);
602 // Get the length argument if it is constant.
604 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
605 Length = LengthArg->getZExtValue();
609 if (Length == 0) // strncmp(x,y,0) -> 0
610 return ConstantInt::get(CI->getType(), 0);
612 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
613 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
615 StringRef Str1, Str2;
616 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
617 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
619 // strncmp(x, y) -> cnst (if both x and y are constant strings)
620 if (HasStr1 && HasStr2) {
621 StringRef SubStr1 = Str1.substr(0, Length);
622 StringRef SubStr2 = Str2.substr(0, Length);
623 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
626 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
627 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
630 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
631 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
637 struct StrCpyOpt : public LibCallOptimization {
638 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
639 // Verify the "strcpy" function prototype.
640 FunctionType *FT = Callee->getFunctionType();
641 if (FT->getNumParams() != 2 ||
642 FT->getReturnType() != FT->getParamType(0) ||
643 FT->getParamType(0) != FT->getParamType(1) ||
644 FT->getParamType(0) != B.getInt8PtrTy())
647 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
648 if (Dst == Src) // strcpy(x,x) -> x
651 // These optimizations require DataLayout.
654 // See if we can get the length of the input string.
655 uint64_t Len = GetStringLength(Src);
656 if (Len == 0) return 0;
658 // We have enough information to now generate the memcpy call to do the
659 // copy for us. Make a memcpy to copy the nul byte with align = 1.
660 B.CreateMemCpy(Dst, Src,
661 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
666 struct StpCpyOpt: public LibCallOptimization {
667 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
668 // Verify the "stpcpy" function prototype.
669 FunctionType *FT = Callee->getFunctionType();
670 if (FT->getNumParams() != 2 ||
671 FT->getReturnType() != FT->getParamType(0) ||
672 FT->getParamType(0) != FT->getParamType(1) ||
673 FT->getParamType(0) != B.getInt8PtrTy())
676 // These optimizations require DataLayout.
679 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
680 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
681 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
682 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
685 // See if we can get the length of the input string.
686 uint64_t Len = GetStringLength(Src);
687 if (Len == 0) return 0;
689 Type *PT = FT->getParamType(0);
690 Value *LenV = ConstantInt::get(TD->getIntPtrType(PT), Len);
691 Value *DstEnd = B.CreateGEP(Dst,
692 ConstantInt::get(TD->getIntPtrType(PT),
695 // We have enough information to now generate the memcpy call to do the
696 // copy for us. Make a memcpy to copy the nul byte with align = 1.
697 B.CreateMemCpy(Dst, Src, LenV, 1);
702 struct StrNCpyOpt : public LibCallOptimization {
703 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
704 FunctionType *FT = Callee->getFunctionType();
705 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
706 FT->getParamType(0) != FT->getParamType(1) ||
707 FT->getParamType(0) != B.getInt8PtrTy() ||
708 !FT->getParamType(2)->isIntegerTy())
711 Value *Dst = CI->getArgOperand(0);
712 Value *Src = CI->getArgOperand(1);
713 Value *LenOp = CI->getArgOperand(2);
715 // See if we can get the length of the input string.
716 uint64_t SrcLen = GetStringLength(Src);
717 if (SrcLen == 0) return 0;
721 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
722 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
727 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
728 Len = LengthArg->getZExtValue();
732 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
734 // These optimizations require DataLayout.
737 // Let strncpy handle the zero padding
738 if (Len > SrcLen+1) return 0;
740 Type *PT = FT->getParamType(0);
741 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
742 B.CreateMemCpy(Dst, Src,
743 ConstantInt::get(TD->getIntPtrType(PT), Len), 1);
749 struct StrLenOpt : public LibCallOptimization {
750 virtual bool ignoreCallingConv() { return true; }
751 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
752 FunctionType *FT = Callee->getFunctionType();
753 if (FT->getNumParams() != 1 ||
754 FT->getParamType(0) != B.getInt8PtrTy() ||
755 !FT->getReturnType()->isIntegerTy())
758 Value *Src = CI->getArgOperand(0);
760 // Constant folding: strlen("xyz") -> 3
761 if (uint64_t Len = GetStringLength(Src))
762 return ConstantInt::get(CI->getType(), Len-1);
764 // strlen(x) != 0 --> *x != 0
765 // strlen(x) == 0 --> *x == 0
766 if (isOnlyUsedInZeroEqualityComparison(CI))
767 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
772 struct StrPBrkOpt : public LibCallOptimization {
773 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
774 FunctionType *FT = Callee->getFunctionType();
775 if (FT->getNumParams() != 2 ||
776 FT->getParamType(0) != B.getInt8PtrTy() ||
777 FT->getParamType(1) != FT->getParamType(0) ||
778 FT->getReturnType() != FT->getParamType(0))
782 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
783 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
785 // strpbrk(s, "") -> NULL
786 // strpbrk("", s) -> NULL
787 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
788 return Constant::getNullValue(CI->getType());
791 if (HasS1 && HasS2) {
792 size_t I = S1.find_first_of(S2);
793 if (I == StringRef::npos) // No match.
794 return Constant::getNullValue(CI->getType());
796 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
799 // strpbrk(s, "a") -> strchr(s, 'a')
800 if (TD && HasS2 && S2.size() == 1)
801 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
807 struct StrToOpt : public LibCallOptimization {
808 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
809 FunctionType *FT = Callee->getFunctionType();
810 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
811 !FT->getParamType(0)->isPointerTy() ||
812 !FT->getParamType(1)->isPointerTy())
815 Value *EndPtr = CI->getArgOperand(1);
816 if (isa<ConstantPointerNull>(EndPtr)) {
817 // With a null EndPtr, this function won't capture the main argument.
818 // It would be readonly too, except that it still may write to errno.
819 CI->addAttribute(1, Attribute::NoCapture);
826 struct StrSpnOpt : public LibCallOptimization {
827 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
828 FunctionType *FT = Callee->getFunctionType();
829 if (FT->getNumParams() != 2 ||
830 FT->getParamType(0) != B.getInt8PtrTy() ||
831 FT->getParamType(1) != FT->getParamType(0) ||
832 !FT->getReturnType()->isIntegerTy())
836 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
837 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
839 // strspn(s, "") -> 0
840 // strspn("", s) -> 0
841 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
842 return Constant::getNullValue(CI->getType());
845 if (HasS1 && HasS2) {
846 size_t Pos = S1.find_first_not_of(S2);
847 if (Pos == StringRef::npos) Pos = S1.size();
848 return ConstantInt::get(CI->getType(), Pos);
855 struct StrCSpnOpt : 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) != B.getInt8PtrTy() ||
860 FT->getParamType(1) != FT->getParamType(0) ||
861 !FT->getReturnType()->isIntegerTy())
865 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
866 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
868 // strcspn("", s) -> 0
869 if (HasS1 && S1.empty())
870 return Constant::getNullValue(CI->getType());
873 if (HasS1 && HasS2) {
874 size_t Pos = S1.find_first_of(S2);
875 if (Pos == StringRef::npos) Pos = S1.size();
876 return ConstantInt::get(CI->getType(), Pos);
879 // strcspn(s, "") -> strlen(s)
880 if (TD && HasS2 && S2.empty())
881 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
887 struct StrStrOpt : public LibCallOptimization {
888 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
889 FunctionType *FT = Callee->getFunctionType();
890 if (FT->getNumParams() != 2 ||
891 !FT->getParamType(0)->isPointerTy() ||
892 !FT->getParamType(1)->isPointerTy() ||
893 !FT->getReturnType()->isPointerTy())
896 // fold strstr(x, x) -> x.
897 if (CI->getArgOperand(0) == CI->getArgOperand(1))
898 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
900 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
901 if (TD && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
902 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
905 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
909 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
911 ICmpInst *Old = cast<ICmpInst>(*UI++);
912 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
913 ConstantInt::getNullValue(StrNCmp->getType()),
915 LCS->replaceAllUsesWith(Old, Cmp);
920 // See if either input string is a constant string.
921 StringRef SearchStr, ToFindStr;
922 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
923 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
925 // fold strstr(x, "") -> x.
926 if (HasStr2 && ToFindStr.empty())
927 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
929 // If both strings are known, constant fold it.
930 if (HasStr1 && HasStr2) {
931 size_t Offset = SearchStr.find(ToFindStr);
933 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
934 return Constant::getNullValue(CI->getType());
936 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
937 Value *Result = CastToCStr(CI->getArgOperand(0), B);
938 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
939 return B.CreateBitCast(Result, CI->getType());
942 // fold strstr(x, "y") -> strchr(x, 'y').
943 if (HasStr2 && ToFindStr.size() == 1) {
944 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
945 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
951 struct MemCmpOpt : public LibCallOptimization {
952 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
953 FunctionType *FT = Callee->getFunctionType();
954 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
955 !FT->getParamType(1)->isPointerTy() ||
956 !FT->getReturnType()->isIntegerTy(32))
959 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
961 if (LHS == RHS) // memcmp(s,s,x) -> 0
962 return Constant::getNullValue(CI->getType());
964 // Make sure we have a constant length.
965 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
967 uint64_t Len = LenC->getZExtValue();
969 if (Len == 0) // memcmp(s1,s2,0) -> 0
970 return Constant::getNullValue(CI->getType());
972 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
974 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
975 CI->getType(), "lhsv");
976 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
977 CI->getType(), "rhsv");
978 return B.CreateSub(LHSV, RHSV, "chardiff");
981 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
982 StringRef LHSStr, RHSStr;
983 if (getConstantStringInfo(LHS, LHSStr) &&
984 getConstantStringInfo(RHS, RHSStr)) {
985 // Make sure we're not reading out-of-bounds memory.
986 if (Len > LHSStr.size() || Len > RHSStr.size())
988 // Fold the memcmp and normalize the result. This way we get consistent
989 // results across multiple platforms.
991 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
996 return ConstantInt::get(CI->getType(), Ret);
1003 struct MemCpyOpt : public LibCallOptimization {
1004 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1005 // These optimizations require DataLayout.
1008 FunctionType *FT = Callee->getFunctionType();
1009 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1010 !FT->getParamType(0)->isPointerTy() ||
1011 !FT->getParamType(1)->isPointerTy() ||
1012 FT->getParamType(2) != TD->getIntPtrType(*Context))
1015 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1016 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1017 CI->getArgOperand(2), 1);
1018 return CI->getArgOperand(0);
1022 struct MemMoveOpt : public LibCallOptimization {
1023 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1024 // These optimizations require DataLayout.
1027 FunctionType *FT = Callee->getFunctionType();
1028 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1029 !FT->getParamType(0)->isPointerTy() ||
1030 !FT->getParamType(1)->isPointerTy() ||
1031 FT->getParamType(2) != TD->getIntPtrType(*Context))
1034 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1035 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1036 CI->getArgOperand(2), 1);
1037 return CI->getArgOperand(0);
1041 struct MemSetOpt : public LibCallOptimization {
1042 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1043 // These optimizations require DataLayout.
1046 FunctionType *FT = Callee->getFunctionType();
1047 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1048 !FT->getParamType(0)->isPointerTy() ||
1049 !FT->getParamType(1)->isIntegerTy() ||
1050 FT->getParamType(2) != TD->getIntPtrType(*Context))
1053 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1054 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1055 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1056 return CI->getArgOperand(0);
1060 //===----------------------------------------------------------------------===//
1061 // Math Library Optimizations
1062 //===----------------------------------------------------------------------===//
1064 //===----------------------------------------------------------------------===//
1065 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1067 struct UnaryDoubleFPOpt : public LibCallOptimization {
1069 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1070 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1071 FunctionType *FT = Callee->getFunctionType();
1072 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1073 !FT->getParamType(0)->isDoubleTy())
1077 // Check if all the uses for function like 'sin' are converted to float.
1078 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1080 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1081 if (Cast == 0 || !Cast->getType()->isFloatTy())
1086 // If this is something like 'floor((double)floatval)', convert to floorf.
1087 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1088 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1091 // floor((double)floatval) -> (double)floorf(floatval)
1092 Value *V = Cast->getOperand(0);
1093 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1094 return B.CreateFPExt(V, B.getDoubleTy());
1098 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1099 bool UnsafeFPShrink;
1100 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1101 this->UnsafeFPShrink = UnsafeFPShrink;
1105 struct CosOpt : public UnsafeFPLibCallOptimization {
1106 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1107 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1109 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1110 TLI->has(LibFunc::cosf)) {
1111 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1112 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1115 FunctionType *FT = Callee->getFunctionType();
1116 // Just make sure this has 1 argument of FP type, which matches the
1118 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1119 !FT->getParamType(0)->isFloatingPointTy())
1122 // cos(-x) -> cos(x)
1123 Value *Op1 = CI->getArgOperand(0);
1124 if (BinaryOperator::isFNeg(Op1)) {
1125 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1126 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1132 struct PowOpt : public UnsafeFPLibCallOptimization {
1133 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1134 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1136 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1137 TLI->has(LibFunc::powf)) {
1138 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1139 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1142 FunctionType *FT = Callee->getFunctionType();
1143 // Just make sure this has 2 arguments of the same FP type, which match the
1145 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1146 FT->getParamType(0) != FT->getParamType(1) ||
1147 !FT->getParamType(0)->isFloatingPointTy())
1150 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1151 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1152 // pow(1.0, x) -> 1.0
1153 if (Op1C->isExactlyValue(1.0))
1155 // pow(2.0, x) -> exp2(x)
1156 if (Op1C->isExactlyValue(2.0) &&
1157 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1159 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1162 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1163 if (Op2C == 0) return Ret;
1165 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1166 return ConstantFP::get(CI->getType(), 1.0);
1168 if (Op2C->isExactlyValue(0.5) &&
1169 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1171 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1173 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1174 // This is faster than calling pow, and still handles negative zero
1175 // and negative infinity correctly.
1176 // TODO: In fast-math mode, this could be just sqrt(x).
1177 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1178 Value *Inf = ConstantFP::getInfinity(CI->getType());
1179 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1180 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1181 Callee->getAttributes());
1182 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1183 Callee->getAttributes());
1184 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1185 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1189 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1191 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1192 return B.CreateFMul(Op1, Op1, "pow2");
1193 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1194 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1200 struct Exp2Opt : public UnsafeFPLibCallOptimization {
1201 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1202 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1204 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1205 TLI->has(LibFunc::exp2f)) {
1206 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1207 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1210 FunctionType *FT = Callee->getFunctionType();
1211 // Just make sure this has 1 argument of FP type, which matches the
1213 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1214 !FT->getParamType(0)->isFloatingPointTy())
1217 Value *Op = CI->getArgOperand(0);
1218 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1219 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1220 Value *LdExpArg = 0;
1221 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1222 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1223 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1224 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1225 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1226 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1231 if (Op->getType()->isFloatTy())
1233 else if (Op->getType()->isDoubleTy())
1238 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1239 if (!Op->getType()->isFloatTy())
1240 One = ConstantExpr::getFPExtend(One, Op->getType());
1242 Module *M = Caller->getParent();
1243 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1245 B.getInt32Ty(), NULL);
1246 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1247 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1248 CI->setCallingConv(F->getCallingConv());
1256 struct SinCosPiOpt : public LibCallOptimization {
1259 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1260 // Make sure the prototype is as expected, otherwise the rest of the
1261 // function is probably invalid and likely to abort.
1262 if (!isTrigLibCall(CI))
1265 Value *Arg = CI->getArgOperand(0);
1266 SmallVector<CallInst *, 1> SinCalls;
1267 SmallVector<CallInst *, 1> CosCalls;
1268 SmallVector<CallInst *, 1> SinCosCalls;
1270 bool IsFloat = Arg->getType()->isFloatTy();
1272 // Look for all compatible sinpi, cospi and sincospi calls with the same
1273 // argument. If there are enough (in some sense) we can make the
1275 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
1277 classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls,
1280 // It's only worthwhile if both sinpi and cospi are actually used.
1281 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1284 Value *Sin, *Cos, *SinCos;
1285 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1288 replaceTrigInsts(SinCalls, Sin);
1289 replaceTrigInsts(CosCalls, Cos);
1290 replaceTrigInsts(SinCosCalls, SinCos);
1295 bool isTrigLibCall(CallInst *CI) {
1296 Function *Callee = CI->getCalledFunction();
1297 FunctionType *FT = Callee->getFunctionType();
1299 // We can only hope to do anything useful if we can ignore things like errno
1300 // and floating-point exceptions.
1301 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1302 CI->hasFnAttr(Attribute::ReadNone);
1304 // Other than that we need float(float) or double(double)
1305 return AttributesSafe && FT->getNumParams() == 1 &&
1306 FT->getReturnType() == FT->getParamType(0) &&
1307 (FT->getParamType(0)->isFloatTy() ||
1308 FT->getParamType(0)->isDoubleTy());
1311 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1312 SmallVectorImpl<CallInst *> &SinCalls,
1313 SmallVectorImpl<CallInst *> &CosCalls,
1314 SmallVectorImpl<CallInst *> &SinCosCalls) {
1315 CallInst *CI = dyn_cast<CallInst>(Val);
1320 Function *Callee = CI->getCalledFunction();
1321 StringRef FuncName = Callee->getName();
1323 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1328 if (Func == LibFunc::sinpif)
1329 SinCalls.push_back(CI);
1330 else if (Func == LibFunc::cospif)
1331 CosCalls.push_back(CI);
1332 else if (Func == LibFunc::sincospi_stretf)
1333 SinCosCalls.push_back(CI);
1335 if (Func == LibFunc::sinpi)
1336 SinCalls.push_back(CI);
1337 else if (Func == LibFunc::cospi)
1338 CosCalls.push_back(CI);
1339 else if (Func == LibFunc::sincospi_stret)
1340 SinCosCalls.push_back(CI);
1344 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1345 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1348 LCS->replaceAllUsesWith(*I, Res);
1352 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1353 bool UseFloat, Value *&Sin, Value *&Cos,
1355 Type *ArgTy = Arg->getType();
1359 Triple T(OrigCallee->getParent()->getTargetTriple());
1361 Name = "__sincospi_stretf";
1363 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1364 // x86_64 can't use {float, float} since that would be returned in both
1365 // xmm0 and xmm1, which isn't what a real struct would do.
1366 ResTy = T.getArch() == Triple::x86_64
1367 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1368 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1370 Name = "__sincospi_stret";
1371 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1374 Module *M = OrigCallee->getParent();
1375 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1376 ResTy, ArgTy, NULL);
1378 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1379 // If the argument is an instruction, it must dominate all uses so put our
1380 // sincos call there.
1381 BasicBlock::iterator Loc = ArgInst;
1382 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1384 // Otherwise (e.g. for a constant) the beginning of the function is as
1385 // good a place as any.
1386 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1387 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1390 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1392 if (SinCos->getType()->isStructTy()) {
1393 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1394 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1396 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1398 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1405 //===----------------------------------------------------------------------===//
1406 // Integer Library Call Optimizations
1407 //===----------------------------------------------------------------------===//
1409 struct FFSOpt : public LibCallOptimization {
1410 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1411 FunctionType *FT = Callee->getFunctionType();
1412 // Just make sure this has 2 arguments of the same FP type, which match the
1414 if (FT->getNumParams() != 1 ||
1415 !FT->getReturnType()->isIntegerTy(32) ||
1416 !FT->getParamType(0)->isIntegerTy())
1419 Value *Op = CI->getArgOperand(0);
1422 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1423 if (CI->isZero()) // ffs(0) -> 0.
1424 return B.getInt32(0);
1425 // ffs(c) -> cttz(c)+1
1426 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1429 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1430 Type *ArgType = Op->getType();
1431 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1432 Intrinsic::cttz, ArgType);
1433 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1434 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1435 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1437 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1438 return B.CreateSelect(Cond, V, B.getInt32(0));
1442 struct AbsOpt : public LibCallOptimization {
1443 virtual bool ignoreCallingConv() { return true; }
1444 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1445 FunctionType *FT = Callee->getFunctionType();
1446 // We require integer(integer) where the types agree.
1447 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1448 FT->getParamType(0) != FT->getReturnType())
1451 // abs(x) -> x >s -1 ? x : -x
1452 Value *Op = CI->getArgOperand(0);
1453 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1455 Value *Neg = B.CreateNeg(Op, "neg");
1456 return B.CreateSelect(Pos, Op, Neg);
1460 struct IsDigitOpt : public LibCallOptimization {
1461 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1462 FunctionType *FT = Callee->getFunctionType();
1463 // We require integer(i32)
1464 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1465 !FT->getParamType(0)->isIntegerTy(32))
1468 // isdigit(c) -> (c-'0') <u 10
1469 Value *Op = CI->getArgOperand(0);
1470 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1471 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1472 return B.CreateZExt(Op, CI->getType());
1476 struct IsAsciiOpt : public LibCallOptimization {
1477 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1478 FunctionType *FT = Callee->getFunctionType();
1479 // We require integer(i32)
1480 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1481 !FT->getParamType(0)->isIntegerTy(32))
1484 // isascii(c) -> c <u 128
1485 Value *Op = CI->getArgOperand(0);
1486 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1487 return B.CreateZExt(Op, CI->getType());
1491 struct ToAsciiOpt : public LibCallOptimization {
1492 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1493 FunctionType *FT = Callee->getFunctionType();
1494 // We require i32(i32)
1495 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1496 !FT->getParamType(0)->isIntegerTy(32))
1499 // toascii(c) -> c & 0x7f
1500 return B.CreateAnd(CI->getArgOperand(0),
1501 ConstantInt::get(CI->getType(),0x7F));
1505 //===----------------------------------------------------------------------===//
1506 // Formatting and IO Library Call Optimizations
1507 //===----------------------------------------------------------------------===//
1509 struct PrintFOpt : public LibCallOptimization {
1510 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1512 // Check for a fixed format string.
1513 StringRef FormatStr;
1514 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1517 // Empty format string -> noop.
1518 if (FormatStr.empty()) // Tolerate printf's declared void.
1519 return CI->use_empty() ? (Value*)CI :
1520 ConstantInt::get(CI->getType(), 0);
1522 // Do not do any of the following transformations if the printf return value
1523 // is used, in general the printf return value is not compatible with either
1524 // putchar() or puts().
1525 if (!CI->use_empty())
1528 // printf("x") -> putchar('x'), even for '%'.
1529 if (FormatStr.size() == 1) {
1530 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
1531 if (CI->use_empty() || !Res) return Res;
1532 return B.CreateIntCast(Res, CI->getType(), true);
1535 // printf("foo\n") --> puts("foo")
1536 if (FormatStr[FormatStr.size()-1] == '\n' &&
1537 FormatStr.find('%') == StringRef::npos) { // No format characters.
1538 // Create a string literal with no \n on it. We expect the constant merge
1539 // pass to be run after this pass, to merge duplicate strings.
1540 FormatStr = FormatStr.drop_back();
1541 Value *GV = B.CreateGlobalString(FormatStr, "str");
1542 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1543 return (CI->use_empty() || !NewCI) ?
1545 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1548 // Optimize specific format strings.
1549 // printf("%c", chr) --> putchar(chr)
1550 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1551 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1552 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
1554 if (CI->use_empty() || !Res) return Res;
1555 return B.CreateIntCast(Res, CI->getType(), true);
1558 // printf("%s\n", str) --> puts(str)
1559 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1560 CI->getArgOperand(1)->getType()->isPointerTy()) {
1561 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
1566 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1567 // Require one fixed pointer argument and an integer/void result.
1568 FunctionType *FT = Callee->getFunctionType();
1569 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1570 !(FT->getReturnType()->isIntegerTy() ||
1571 FT->getReturnType()->isVoidTy()))
1574 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1578 // printf(format, ...) -> iprintf(format, ...) if no floating point
1580 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1581 Module *M = B.GetInsertBlock()->getParent()->getParent();
1582 Constant *IPrintFFn =
1583 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1584 CallInst *New = cast<CallInst>(CI->clone());
1585 New->setCalledFunction(IPrintFFn);
1593 struct SPrintFOpt : public LibCallOptimization {
1594 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1596 // Check for a fixed format string.
1597 StringRef FormatStr;
1598 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1601 // If we just have a format string (nothing else crazy) transform it.
1602 if (CI->getNumArgOperands() == 2) {
1603 // Make sure there's no % in the constant array. We could try to handle
1604 // %% -> % in the future if we cared.
1605 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1606 if (FormatStr[i] == '%')
1607 return 0; // we found a format specifier, bail out.
1609 // These optimizations require DataLayout.
1612 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1613 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1614 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1615 FormatStr.size() + 1), 1); // nul byte.
1616 return ConstantInt::get(CI->getType(), FormatStr.size());
1619 // The remaining optimizations require the format string to be "%s" or "%c"
1620 // and have an extra operand.
1621 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1622 CI->getNumArgOperands() < 3)
1625 // Decode the second character of the format string.
1626 if (FormatStr[1] == 'c') {
1627 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1628 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1629 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1630 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1631 B.CreateStore(V, Ptr);
1632 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1633 B.CreateStore(B.getInt8(0), Ptr);
1635 return ConstantInt::get(CI->getType(), 1);
1638 if (FormatStr[1] == 's') {
1639 // These optimizations require DataLayout.
1642 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1643 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1645 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1648 Value *IncLen = B.CreateAdd(Len,
1649 ConstantInt::get(Len->getType(), 1),
1651 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1653 // The sprintf result is the unincremented number of bytes in the string.
1654 return B.CreateIntCast(Len, CI->getType(), false);
1659 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1660 // Require two fixed pointer arguments and an integer result.
1661 FunctionType *FT = Callee->getFunctionType();
1662 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1663 !FT->getParamType(1)->isPointerTy() ||
1664 !FT->getReturnType()->isIntegerTy())
1667 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1671 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1673 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1674 Module *M = B.GetInsertBlock()->getParent()->getParent();
1675 Constant *SIPrintFFn =
1676 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1677 CallInst *New = cast<CallInst>(CI->clone());
1678 New->setCalledFunction(SIPrintFFn);
1686 struct FPrintFOpt : public LibCallOptimization {
1687 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1689 // All the optimizations depend on the format string.
1690 StringRef FormatStr;
1691 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1694 // Do not do any of the following transformations if the fprintf return
1695 // value is used, in general the fprintf return value is not compatible
1696 // with fwrite(), fputc() or fputs().
1697 if (!CI->use_empty())
1700 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1701 if (CI->getNumArgOperands() == 2) {
1702 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1703 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1704 return 0; // We found a format specifier.
1706 // These optimizations require DataLayout.
1709 return EmitFWrite(CI->getArgOperand(1),
1710 ConstantInt::get(TD->getIntPtrType(*Context),
1712 CI->getArgOperand(0), B, TD, TLI);
1715 // The remaining optimizations require the format string to be "%s" or "%c"
1716 // and have an extra operand.
1717 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1718 CI->getNumArgOperands() < 3)
1721 // Decode the second character of the format string.
1722 if (FormatStr[1] == 'c') {
1723 // fprintf(F, "%c", chr) --> fputc(chr, F)
1724 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1725 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1728 if (FormatStr[1] == 's') {
1729 // fprintf(F, "%s", str) --> fputs(str, F)
1730 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1732 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
1737 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1738 // Require two fixed paramters as pointers and integer result.
1739 FunctionType *FT = Callee->getFunctionType();
1740 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1741 !FT->getParamType(1)->isPointerTy() ||
1742 !FT->getReturnType()->isIntegerTy())
1745 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1749 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1750 // floating point arguments.
1751 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1752 Module *M = B.GetInsertBlock()->getParent()->getParent();
1753 Constant *FIPrintFFn =
1754 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1755 CallInst *New = cast<CallInst>(CI->clone());
1756 New->setCalledFunction(FIPrintFFn);
1764 struct FWriteOpt : public LibCallOptimization {
1765 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1766 // Require a pointer, an integer, an integer, a pointer, returning integer.
1767 FunctionType *FT = Callee->getFunctionType();
1768 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1769 !FT->getParamType(1)->isIntegerTy() ||
1770 !FT->getParamType(2)->isIntegerTy() ||
1771 !FT->getParamType(3)->isPointerTy() ||
1772 !FT->getReturnType()->isIntegerTy())
1775 // Get the element size and count.
1776 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1777 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1778 if (!SizeC || !CountC) return 0;
1779 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1781 // If this is writing zero records, remove the call (it's a noop).
1783 return ConstantInt::get(CI->getType(), 0);
1785 // If this is writing one byte, turn it into fputc.
1786 // This optimisation is only valid, if the return value is unused.
1787 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1788 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1789 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1790 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1797 struct FPutsOpt : public LibCallOptimization {
1798 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1799 // These optimizations require DataLayout.
1802 // Require two pointers. Also, we can't optimize if return value is used.
1803 FunctionType *FT = Callee->getFunctionType();
1804 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1805 !FT->getParamType(1)->isPointerTy() ||
1809 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1810 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1812 // Known to have no uses (see above).
1813 return EmitFWrite(CI->getArgOperand(0),
1814 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1815 CI->getArgOperand(1), B, TD, TLI);
1819 struct PutsOpt : public LibCallOptimization {
1820 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1821 // Require one fixed pointer argument and an integer/void result.
1822 FunctionType *FT = Callee->getFunctionType();
1823 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1824 !(FT->getReturnType()->isIntegerTy() ||
1825 FT->getReturnType()->isVoidTy()))
1828 // Check for a constant string.
1830 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1833 if (Str.empty() && CI->use_empty()) {
1834 // puts("") -> putchar('\n')
1835 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
1836 if (CI->use_empty() || !Res) return Res;
1837 return B.CreateIntCast(Res, CI->getType(), true);
1844 } // End anonymous namespace.
1848 class LibCallSimplifierImpl {
1849 const DataLayout *TD;
1850 const TargetLibraryInfo *TLI;
1851 const LibCallSimplifier *LCS;
1852 bool UnsafeFPShrink;
1854 // Math library call optimizations.
1859 LibCallSimplifierImpl(const DataLayout *TD, const TargetLibraryInfo *TLI,
1860 const LibCallSimplifier *LCS,
1861 bool UnsafeFPShrink = false)
1862 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
1866 this->UnsafeFPShrink = UnsafeFPShrink;
1869 Value *optimizeCall(CallInst *CI);
1870 LibCallOptimization *lookupOptimization(CallInst *CI);
1871 bool hasFloatVersion(StringRef FuncName);
1874 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
1876 SmallString<20> FloatFuncName = FuncName;
1877 FloatFuncName += 'f';
1878 if (TLI->getLibFunc(FloatFuncName, Func))
1879 return TLI->has(Func);
1883 // Fortified library call optimizations.
1884 static MemCpyChkOpt MemCpyChk;
1885 static MemMoveChkOpt MemMoveChk;
1886 static MemSetChkOpt MemSetChk;
1887 static StrCpyChkOpt StrCpyChk;
1888 static StpCpyChkOpt StpCpyChk;
1889 static StrNCpyChkOpt StrNCpyChk;
1891 // String library call optimizations.
1892 static StrCatOpt StrCat;
1893 static StrNCatOpt StrNCat;
1894 static StrChrOpt StrChr;
1895 static StrRChrOpt StrRChr;
1896 static StrCmpOpt StrCmp;
1897 static StrNCmpOpt StrNCmp;
1898 static StrCpyOpt StrCpy;
1899 static StpCpyOpt StpCpy;
1900 static StrNCpyOpt StrNCpy;
1901 static StrLenOpt StrLen;
1902 static StrPBrkOpt StrPBrk;
1903 static StrToOpt StrTo;
1904 static StrSpnOpt StrSpn;
1905 static StrCSpnOpt StrCSpn;
1906 static StrStrOpt StrStr;
1908 // Memory library call optimizations.
1909 static MemCmpOpt MemCmp;
1910 static MemCpyOpt MemCpy;
1911 static MemMoveOpt MemMove;
1912 static MemSetOpt MemSet;
1914 // Math library call optimizations.
1915 static UnaryDoubleFPOpt UnaryDoubleFP(false);
1916 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1917 static SinCosPiOpt SinCosPi;
1919 // Integer library call optimizations.
1922 static IsDigitOpt IsDigit;
1923 static IsAsciiOpt IsAscii;
1924 static ToAsciiOpt ToAscii;
1926 // Formatting and IO library call optimizations.
1927 static PrintFOpt PrintF;
1928 static SPrintFOpt SPrintF;
1929 static FPrintFOpt FPrintF;
1930 static FWriteOpt FWrite;
1931 static FPutsOpt FPuts;
1932 static PutsOpt Puts;
1934 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
1936 Function *Callee = CI->getCalledFunction();
1937 StringRef FuncName = Callee->getName();
1939 // Next check for intrinsics.
1940 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1941 switch (II->getIntrinsicID()) {
1942 case Intrinsic::pow:
1944 case Intrinsic::exp2:
1951 // Then check for known library functions.
1952 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1954 case LibFunc::strcat:
1956 case LibFunc::strncat:
1958 case LibFunc::strchr:
1960 case LibFunc::strrchr:
1962 case LibFunc::strcmp:
1964 case LibFunc::strncmp:
1966 case LibFunc::strcpy:
1968 case LibFunc::stpcpy:
1970 case LibFunc::strncpy:
1972 case LibFunc::strlen:
1974 case LibFunc::strpbrk:
1976 case LibFunc::strtol:
1977 case LibFunc::strtod:
1978 case LibFunc::strtof:
1979 case LibFunc::strtoul:
1980 case LibFunc::strtoll:
1981 case LibFunc::strtold:
1982 case LibFunc::strtoull:
1984 case LibFunc::strspn:
1986 case LibFunc::strcspn:
1988 case LibFunc::strstr:
1990 case LibFunc::memcmp:
1992 case LibFunc::memcpy:
1994 case LibFunc::memmove:
1996 case LibFunc::memset:
2002 case LibFunc::sinpif:
2003 case LibFunc::sinpi:
2004 case LibFunc::cospif:
2005 case LibFunc::cospi:
2011 case LibFunc::exp2l:
2013 case LibFunc::exp2f:
2017 case LibFunc::ffsll:
2021 case LibFunc::llabs:
2023 case LibFunc::isdigit:
2025 case LibFunc::isascii:
2027 case LibFunc::toascii:
2029 case LibFunc::printf:
2031 case LibFunc::sprintf:
2033 case LibFunc::fprintf:
2035 case LibFunc::fwrite:
2037 case LibFunc::fputs:
2043 case LibFunc::floor:
2045 case LibFunc::round:
2046 case LibFunc::nearbyint:
2047 case LibFunc::trunc:
2048 if (hasFloatVersion(FuncName))
2049 return &UnaryDoubleFP;
2052 case LibFunc::acosh:
2054 case LibFunc::asinh:
2056 case LibFunc::atanh:
2060 case LibFunc::exp10:
2061 case LibFunc::expm1:
2063 case LibFunc::log10:
2064 case LibFunc::log1p:
2072 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2073 return &UnsafeUnaryDoubleFP;
2075 case LibFunc::memcpy_chk:
2082 // Finally check for fortified library calls.
2083 if (FuncName.endswith("_chk")) {
2084 if (FuncName == "__memmove_chk")
2086 else if (FuncName == "__memset_chk")
2088 else if (FuncName == "__strcpy_chk")
2090 else if (FuncName == "__stpcpy_chk")
2092 else if (FuncName == "__strncpy_chk")
2094 else if (FuncName == "__stpncpy_chk")
2102 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
2103 LibCallOptimization *LCO = lookupOptimization(CI);
2105 IRBuilder<> Builder(CI);
2106 return LCO->optimizeCall(CI, TD, TLI, LCS, Builder);
2111 LibCallSimplifier::LibCallSimplifier(const DataLayout *TD,
2112 const TargetLibraryInfo *TLI,
2113 bool UnsafeFPShrink) {
2114 Impl = new LibCallSimplifierImpl(TD, TLI, this, UnsafeFPShrink);
2117 LibCallSimplifier::~LibCallSimplifier() {
2121 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2122 if (CI->isNoBuiltin()) return 0;
2123 return Impl->optimizeCall(CI);
2126 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2127 I->replaceAllUsesWith(With);
2128 I->eraseFromParent();
2134 // Additional cases that we need to add to this file:
2137 // * cbrt(expN(X)) -> expN(x/3)
2138 // * cbrt(sqrt(x)) -> pow(x,1/6)
2139 // * cbrt(sqrt(x)) -> pow(x,1/9)
2142 // * exp(log(x)) -> x
2145 // * log(exp(x)) -> x
2146 // * log(x**y) -> y*log(x)
2147 // * log(exp(y)) -> y*log(e)
2148 // * log(exp2(y)) -> y*log(2)
2149 // * log(exp10(y)) -> y*log(10)
2150 // * log(sqrt(x)) -> 0.5*log(x)
2151 // * log(pow(x,y)) -> y*log(x)
2153 // lround, lroundf, lroundl:
2154 // * lround(cnst) -> cnst'
2157 // * pow(exp(x),y) -> exp(x*y)
2158 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2159 // * pow(pow(x,y),z)-> pow(x,y*z)
2161 // round, roundf, roundl:
2162 // * round(cnst) -> cnst'
2165 // * signbit(cnst) -> cnst'
2166 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2168 // sqrt, sqrtf, sqrtl:
2169 // * sqrt(expN(x)) -> expN(x*0.5)
2170 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2171 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2174 // * strchr(p, 0) -> strlen(p)
2176 // * tan(atan(x)) -> x
2178 // trunc, truncf, truncl:
2179 // * trunc(cnst) -> cnst'