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/DiagnosticInfo.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
37 using namespace PatternMatch;
40 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 static bool ignoreCallingConv(LibFunc::Func Func) {
64 llvm_unreachable("All cases should be covered in the switch.");
67 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
68 /// value is equal or not-equal to zero.
69 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
70 for (User *U : V->users()) {
71 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
73 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
76 // Unknown instruction.
82 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
83 /// comparisons with With.
84 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
85 for (User *U : V->users()) {
86 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
87 if (IC->isEquality() && IC->getOperand(1) == With)
89 // Unknown instruction.
95 static bool callHasFloatingPointArgument(const CallInst *CI) {
96 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
98 if ((*it)->getType()->isFloatingPointTy())
104 /// \brief Check whether the overloaded unary floating point function
105 /// corresponing to \a Ty is available.
106 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
107 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
108 LibFunc::Func LongDoubleFn) {
109 switch (Ty->getTypeID()) {
110 case Type::FloatTyID:
111 return TLI->has(FloatFn);
112 case Type::DoubleTyID:
113 return TLI->has(DoubleFn);
115 return TLI->has(LongDoubleFn);
119 /// \brief Returns whether \p F matches the signature expected for the
120 /// string/memory copying library function \p Func.
121 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
122 /// Their fortified (_chk) counterparts are also accepted.
123 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
124 const DataLayout &DL = F->getParent()->getDataLayout();
125 FunctionType *FT = F->getFunctionType();
126 LLVMContext &Context = F->getContext();
127 Type *PCharTy = Type::getInt8PtrTy(Context);
128 Type *SizeTTy = DL.getIntPtrType(Context);
129 unsigned NumParams = FT->getNumParams();
131 // All string libfuncs return the same type as the first parameter.
132 if (FT->getReturnType() != FT->getParamType(0))
137 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
138 case LibFunc::stpncpy_chk:
139 case LibFunc::strncpy_chk:
140 --NumParams; // fallthrough
141 case LibFunc::stpncpy:
142 case LibFunc::strncpy: {
143 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
144 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
148 case LibFunc::strcpy_chk:
149 case LibFunc::stpcpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpcpy:
152 case LibFunc::strcpy: {
153 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy)
158 case LibFunc::memmove_chk:
159 case LibFunc::memcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::memmove:
162 case LibFunc::memcpy: {
163 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
164 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
168 case LibFunc::memset_chk:
169 --NumParams; // fallthrough
170 case LibFunc::memset: {
171 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
177 // If this is a fortified libcall, the last parameter is a size_t.
178 if (NumParams == FT->getNumParams() - 1)
179 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
183 //===----------------------------------------------------------------------===//
184 // String and Memory Library Call Optimizations
185 //===----------------------------------------------------------------------===//
187 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
188 Function *Callee = CI->getCalledFunction();
189 // Verify the "strcat" function prototype.
190 FunctionType *FT = Callee->getFunctionType();
191 if (FT->getNumParams() != 2||
192 FT->getReturnType() != B.getInt8PtrTy() ||
193 FT->getParamType(0) != FT->getReturnType() ||
194 FT->getParamType(1) != FT->getReturnType())
197 // Extract some information from the instruction
198 Value *Dst = CI->getArgOperand(0);
199 Value *Src = CI->getArgOperand(1);
201 // See if we can get the length of the input string.
202 uint64_t Len = GetStringLength(Src);
205 --Len; // Unbias length.
207 // Handle the simple, do-nothing case: strcat(x, "") -> x
211 return emitStrLenMemCpy(Src, Dst, Len, B);
214 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
216 // We need to find the end of the destination string. That's where the
217 // memory is to be moved to. We just generate a call to strlen.
218 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
222 // Now that we have the destination's length, we must index into the
223 // destination's pointer to get the actual memcpy destination (end of
224 // the string .. we're concatenating).
225 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
227 // We have enough information to now generate the memcpy call to do the
228 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
229 B.CreateMemCpy(CpyDst, Src,
230 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
235 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
236 Function *Callee = CI->getCalledFunction();
237 // Verify the "strncat" function prototype.
238 FunctionType *FT = Callee->getFunctionType();
239 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
240 FT->getParamType(0) != FT->getReturnType() ||
241 FT->getParamType(1) != FT->getReturnType() ||
242 !FT->getParamType(2)->isIntegerTy())
245 // Extract some information from the instruction
246 Value *Dst = CI->getArgOperand(0);
247 Value *Src = CI->getArgOperand(1);
250 // We don't do anything if length is not constant
251 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
252 Len = LengthArg->getZExtValue();
256 // See if we can get the length of the input string.
257 uint64_t SrcLen = GetStringLength(Src);
260 --SrcLen; // Unbias length.
262 // Handle the simple, do-nothing cases:
263 // strncat(x, "", c) -> x
264 // strncat(x, c, 0) -> x
265 if (SrcLen == 0 || Len == 0)
268 // We don't optimize this case
272 // strncat(x, s, c) -> strcat(x, s)
273 // s is constant so the strcat can be optimized further
274 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
277 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
278 Function *Callee = CI->getCalledFunction();
279 // Verify the "strchr" function prototype.
280 FunctionType *FT = Callee->getFunctionType();
281 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
282 FT->getParamType(0) != FT->getReturnType() ||
283 !FT->getParamType(1)->isIntegerTy(32))
286 Value *SrcStr = CI->getArgOperand(0);
288 // If the second operand is non-constant, see if we can compute the length
289 // of the input string and turn this into memchr.
290 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
292 uint64_t Len = GetStringLength(SrcStr);
293 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
296 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
297 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
301 // Otherwise, the character is a constant, see if the first argument is
302 // a string literal. If so, we can constant fold.
304 if (!getConstantStringInfo(SrcStr, Str)) {
305 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
306 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
310 // Compute the offset, make sure to handle the case when we're searching for
311 // zero (a weird way to spell strlen).
312 size_t I = (0xFF & CharC->getSExtValue()) == 0
314 : Str.find(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
316 return Constant::getNullValue(CI->getType());
318 // strchr(s+n,c) -> gep(s+n+i,c)
319 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
322 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
323 Function *Callee = CI->getCalledFunction();
324 // Verify the "strrchr" function prototype.
325 FunctionType *FT = Callee->getFunctionType();
326 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
327 FT->getParamType(0) != FT->getReturnType() ||
328 !FT->getParamType(1)->isIntegerTy(32))
331 Value *SrcStr = CI->getArgOperand(0);
332 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
334 // Cannot fold anything if we're not looking for a constant.
339 if (!getConstantStringInfo(SrcStr, Str)) {
340 // strrchr(s, 0) -> strchr(s, 0)
342 return EmitStrChr(SrcStr, '\0', B, TLI);
346 // Compute the offset.
347 size_t I = (0xFF & CharC->getSExtValue()) == 0
349 : Str.rfind(CharC->getSExtValue());
350 if (I == StringRef::npos) // Didn't find the char. Return null.
351 return Constant::getNullValue(CI->getType());
353 // strrchr(s+n,c) -> gep(s+n+i,c)
354 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
357 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
358 Function *Callee = CI->getCalledFunction();
359 // Verify the "strcmp" function prototype.
360 FunctionType *FT = Callee->getFunctionType();
361 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
362 FT->getParamType(0) != FT->getParamType(1) ||
363 FT->getParamType(0) != B.getInt8PtrTy())
366 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
367 if (Str1P == Str2P) // strcmp(x,x) -> 0
368 return ConstantInt::get(CI->getType(), 0);
370 StringRef Str1, Str2;
371 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
372 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
374 // strcmp(x, y) -> cnst (if both x and y are constant strings)
375 if (HasStr1 && HasStr2)
376 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
378 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
380 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
382 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
383 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
385 // strcmp(P, "x") -> memcmp(P, "x", 2)
386 uint64_t Len1 = GetStringLength(Str1P);
387 uint64_t Len2 = GetStringLength(Str2P);
389 return EmitMemCmp(Str1P, Str2P,
390 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
391 std::min(Len1, Len2)),
398 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
399 Function *Callee = CI->getCalledFunction();
400 // Verify the "strncmp" function prototype.
401 FunctionType *FT = Callee->getFunctionType();
402 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
403 FT->getParamType(0) != FT->getParamType(1) ||
404 FT->getParamType(0) != B.getInt8PtrTy() ||
405 !FT->getParamType(2)->isIntegerTy())
408 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
409 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
410 return ConstantInt::get(CI->getType(), 0);
412 // Get the length argument if it is constant.
414 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
415 Length = LengthArg->getZExtValue();
419 if (Length == 0) // strncmp(x,y,0) -> 0
420 return ConstantInt::get(CI->getType(), 0);
422 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
423 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
425 StringRef Str1, Str2;
426 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
427 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
429 // strncmp(x, y) -> cnst (if both x and y are constant strings)
430 if (HasStr1 && HasStr2) {
431 StringRef SubStr1 = Str1.substr(0, Length);
432 StringRef SubStr2 = Str2.substr(0, Length);
433 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
436 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
438 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
440 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
441 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
446 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
447 Function *Callee = CI->getCalledFunction();
449 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
452 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
453 if (Dst == Src) // strcpy(x,x) -> x
456 // See if we can get the length of the input string.
457 uint64_t Len = GetStringLength(Src);
461 // We have enough information to now generate the memcpy call to do the
462 // copy for us. Make a memcpy to copy the nul byte with align = 1.
463 B.CreateMemCpy(Dst, Src,
464 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
468 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
469 Function *Callee = CI->getCalledFunction();
470 // Verify the "stpcpy" function prototype.
471 FunctionType *FT = Callee->getFunctionType();
473 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
476 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
477 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
478 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
479 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
482 // See if we can get the length of the input string.
483 uint64_t Len = GetStringLength(Src);
487 Type *PT = FT->getParamType(0);
488 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
490 B.CreateGEP(Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
492 // We have enough information to now generate the memcpy call to do the
493 // copy for us. Make a memcpy to copy the nul byte with align = 1.
494 B.CreateMemCpy(Dst, Src, LenV, 1);
498 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
499 Function *Callee = CI->getCalledFunction();
500 FunctionType *FT = Callee->getFunctionType();
502 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
505 Value *Dst = CI->getArgOperand(0);
506 Value *Src = CI->getArgOperand(1);
507 Value *LenOp = CI->getArgOperand(2);
509 // See if we can get the length of the input string.
510 uint64_t SrcLen = GetStringLength(Src);
516 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
517 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
522 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
523 Len = LengthArg->getZExtValue();
528 return Dst; // strncpy(x, y, 0) -> x
530 // Let strncpy handle the zero padding
531 if (Len > SrcLen + 1)
534 Type *PT = FT->getParamType(0);
535 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
536 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
541 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
542 Function *Callee = CI->getCalledFunction();
543 FunctionType *FT = Callee->getFunctionType();
544 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
545 !FT->getReturnType()->isIntegerTy())
548 Value *Src = CI->getArgOperand(0);
550 // Constant folding: strlen("xyz") -> 3
551 if (uint64_t Len = GetStringLength(Src))
552 return ConstantInt::get(CI->getType(), Len - 1);
554 // strlen(x?"foo":"bars") --> x ? 3 : 4
555 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
556 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
557 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
558 if (LenTrue && LenFalse) {
559 Function *Caller = CI->getParent()->getParent();
560 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
562 "folded strlen(select) to select of constants");
563 return B.CreateSelect(SI->getCondition(),
564 ConstantInt::get(CI->getType(), LenTrue - 1),
565 ConstantInt::get(CI->getType(), LenFalse - 1));
569 // strlen(x) != 0 --> *x != 0
570 // strlen(x) == 0 --> *x == 0
571 if (isOnlyUsedInZeroEqualityComparison(CI))
572 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
577 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
578 Function *Callee = CI->getCalledFunction();
579 FunctionType *FT = Callee->getFunctionType();
580 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
581 FT->getParamType(1) != FT->getParamType(0) ||
582 FT->getReturnType() != FT->getParamType(0))
586 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
587 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
589 // strpbrk(s, "") -> nullptr
590 // strpbrk("", s) -> nullptr
591 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
592 return Constant::getNullValue(CI->getType());
595 if (HasS1 && HasS2) {
596 size_t I = S1.find_first_of(S2);
597 if (I == StringRef::npos) // No match.
598 return Constant::getNullValue(CI->getType());
600 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
603 // strpbrk(s, "a") -> strchr(s, 'a')
604 if (HasS2 && S2.size() == 1)
605 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
610 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
611 Function *Callee = CI->getCalledFunction();
612 FunctionType *FT = Callee->getFunctionType();
613 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
614 !FT->getParamType(0)->isPointerTy() ||
615 !FT->getParamType(1)->isPointerTy())
618 Value *EndPtr = CI->getArgOperand(1);
619 if (isa<ConstantPointerNull>(EndPtr)) {
620 // With a null EndPtr, this function won't capture the main argument.
621 // It would be readonly too, except that it still may write to errno.
622 CI->addAttribute(1, Attribute::NoCapture);
628 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
629 Function *Callee = CI->getCalledFunction();
630 FunctionType *FT = Callee->getFunctionType();
631 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
632 FT->getParamType(1) != FT->getParamType(0) ||
633 !FT->getReturnType()->isIntegerTy())
637 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
638 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
640 // strspn(s, "") -> 0
641 // strspn("", s) -> 0
642 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
643 return Constant::getNullValue(CI->getType());
646 if (HasS1 && HasS2) {
647 size_t Pos = S1.find_first_not_of(S2);
648 if (Pos == StringRef::npos)
650 return ConstantInt::get(CI->getType(), Pos);
656 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
657 Function *Callee = CI->getCalledFunction();
658 FunctionType *FT = Callee->getFunctionType();
659 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
660 FT->getParamType(1) != FT->getParamType(0) ||
661 !FT->getReturnType()->isIntegerTy())
665 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
666 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
668 // strcspn("", s) -> 0
669 if (HasS1 && S1.empty())
670 return Constant::getNullValue(CI->getType());
673 if (HasS1 && HasS2) {
674 size_t Pos = S1.find_first_of(S2);
675 if (Pos == StringRef::npos)
677 return ConstantInt::get(CI->getType(), Pos);
680 // strcspn(s, "") -> strlen(s)
681 if (HasS2 && S2.empty())
682 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
687 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
688 Function *Callee = CI->getCalledFunction();
689 FunctionType *FT = Callee->getFunctionType();
690 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
691 !FT->getParamType(1)->isPointerTy() ||
692 !FT->getReturnType()->isPointerTy())
695 // fold strstr(x, x) -> x.
696 if (CI->getArgOperand(0) == CI->getArgOperand(1))
697 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
699 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
700 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
701 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
704 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
708 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
709 ICmpInst *Old = cast<ICmpInst>(*UI++);
711 B.CreateICmp(Old->getPredicate(), StrNCmp,
712 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
713 replaceAllUsesWith(Old, Cmp);
718 // See if either input string is a constant string.
719 StringRef SearchStr, ToFindStr;
720 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
721 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
723 // fold strstr(x, "") -> x.
724 if (HasStr2 && ToFindStr.empty())
725 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
727 // If both strings are known, constant fold it.
728 if (HasStr1 && HasStr2) {
729 size_t Offset = SearchStr.find(ToFindStr);
731 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
732 return Constant::getNullValue(CI->getType());
734 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
735 Value *Result = CastToCStr(CI->getArgOperand(0), B);
736 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
737 return B.CreateBitCast(Result, CI->getType());
740 // fold strstr(x, "y") -> strchr(x, 'y').
741 if (HasStr2 && ToFindStr.size() == 1) {
742 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
743 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
748 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
749 Function *Callee = CI->getCalledFunction();
750 FunctionType *FT = Callee->getFunctionType();
751 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
752 !FT->getParamType(1)->isPointerTy() ||
753 !FT->getReturnType()->isIntegerTy(32))
756 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
758 if (LHS == RHS) // memcmp(s,s,x) -> 0
759 return Constant::getNullValue(CI->getType());
761 // Make sure we have a constant length.
762 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
765 uint64_t Len = LenC->getZExtValue();
767 if (Len == 0) // memcmp(s1,s2,0) -> 0
768 return Constant::getNullValue(CI->getType());
770 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
772 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
773 CI->getType(), "lhsv");
774 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
775 CI->getType(), "rhsv");
776 return B.CreateSub(LHSV, RHSV, "chardiff");
779 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
780 StringRef LHSStr, RHSStr;
781 if (getConstantStringInfo(LHS, LHSStr) &&
782 getConstantStringInfo(RHS, RHSStr)) {
783 // Make sure we're not reading out-of-bounds memory.
784 if (Len > LHSStr.size() || Len > RHSStr.size())
786 // Fold the memcmp and normalize the result. This way we get consistent
787 // results across multiple platforms.
789 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
794 return ConstantInt::get(CI->getType(), Ret);
800 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
801 Function *Callee = CI->getCalledFunction();
803 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
806 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
807 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
808 CI->getArgOperand(2), 1);
809 return CI->getArgOperand(0);
812 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
813 Function *Callee = CI->getCalledFunction();
815 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
818 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
819 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
820 CI->getArgOperand(2), 1);
821 return CI->getArgOperand(0);
824 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
825 Function *Callee = CI->getCalledFunction();
827 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
830 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
831 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
832 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
833 return CI->getArgOperand(0);
836 //===----------------------------------------------------------------------===//
837 // Math Library Optimizations
838 //===----------------------------------------------------------------------===//
840 /// Return a variant of Val with float type.
841 /// Currently this works in two cases: If Val is an FPExtension of a float
842 /// value to something bigger, simply return the operand.
843 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
844 /// loss of precision do so.
845 static Value *valueHasFloatPrecision(Value *Val) {
846 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
847 Value *Op = Cast->getOperand(0);
848 if (Op->getType()->isFloatTy())
851 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
852 APFloat F = Const->getValueAPF();
854 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
857 return ConstantFP::get(Const->getContext(), F);
862 //===----------------------------------------------------------------------===//
863 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
865 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
867 Function *Callee = CI->getCalledFunction();
868 FunctionType *FT = Callee->getFunctionType();
869 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
870 !FT->getParamType(0)->isDoubleTy())
874 // Check if all the uses for function like 'sin' are converted to float.
875 for (User *U : CI->users()) {
876 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
877 if (!Cast || !Cast->getType()->isFloatTy())
882 // If this is something like 'floor((double)floatval)', convert to floorf.
883 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
887 // floor((double)floatval) -> (double)floorf(floatval)
888 if (Callee->isIntrinsic()) {
889 Module *M = CI->getParent()->getParent()->getParent();
890 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
891 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
892 V = B.CreateCall(F, V);
894 // The call is a library call rather than an intrinsic.
895 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
898 return B.CreateFPExt(V, B.getDoubleTy());
901 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
902 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
903 Function *Callee = CI->getCalledFunction();
904 FunctionType *FT = Callee->getFunctionType();
905 // Just make sure this has 2 arguments of the same FP type, which match the
907 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
908 FT->getParamType(0) != FT->getParamType(1) ||
909 !FT->getParamType(0)->isFloatingPointTy())
912 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
913 // or fmin(1.0, (double)floatval), then we convert it to fminf.
914 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
917 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
921 // fmin((double)floatval1, (double)floatval2)
922 // -> (double)fminf(floatval1, floatval2)
923 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
924 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
925 Callee->getAttributes());
926 return B.CreateFPExt(V, B.getDoubleTy());
929 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
930 Function *Callee = CI->getCalledFunction();
931 Value *Ret = nullptr;
932 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
933 Ret = optimizeUnaryDoubleFP(CI, B, true);
936 FunctionType *FT = Callee->getFunctionType();
937 // Just make sure this has 1 argument of FP type, which matches the
939 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
940 !FT->getParamType(0)->isFloatingPointTy())
944 Value *Op1 = CI->getArgOperand(0);
945 if (BinaryOperator::isFNeg(Op1)) {
946 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
947 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
952 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
953 Function *Callee = CI->getCalledFunction();
955 Value *Ret = nullptr;
956 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
957 Ret = optimizeUnaryDoubleFP(CI, B, true);
960 FunctionType *FT = Callee->getFunctionType();
961 // Just make sure this has 2 arguments of the same FP type, which match the
963 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
964 FT->getParamType(0) != FT->getParamType(1) ||
965 !FT->getParamType(0)->isFloatingPointTy())
968 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
969 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
970 // pow(1.0, x) -> 1.0
971 if (Op1C->isExactlyValue(1.0))
973 // pow(2.0, x) -> exp2(x)
974 if (Op1C->isExactlyValue(2.0) &&
975 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
977 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
978 // pow(10.0, x) -> exp10(x)
979 if (Op1C->isExactlyValue(10.0) &&
980 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
982 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
983 Callee->getAttributes());
986 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
990 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
991 return ConstantFP::get(CI->getType(), 1.0);
993 if (Op2C->isExactlyValue(0.5) &&
994 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
996 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
998 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
999 // This is faster than calling pow, and still handles negative zero
1000 // and negative infinity correctly.
1001 // TODO: In fast-math mode, this could be just sqrt(x).
1002 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1003 Value *Inf = ConstantFP::getInfinity(CI->getType());
1004 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1005 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1007 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1008 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1009 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1013 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1015 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1016 return B.CreateFMul(Op1, Op1, "pow2");
1017 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1018 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1022 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1023 Function *Callee = CI->getCalledFunction();
1024 Function *Caller = CI->getParent()->getParent();
1026 Value *Ret = nullptr;
1027 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1028 TLI->has(LibFunc::exp2f)) {
1029 Ret = optimizeUnaryDoubleFP(CI, B, true);
1032 FunctionType *FT = Callee->getFunctionType();
1033 // Just make sure this has 1 argument of FP type, which matches the
1035 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1036 !FT->getParamType(0)->isFloatingPointTy())
1039 Value *Op = CI->getArgOperand(0);
1040 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1041 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1042 LibFunc::Func LdExp = LibFunc::ldexpl;
1043 if (Op->getType()->isFloatTy())
1044 LdExp = LibFunc::ldexpf;
1045 else if (Op->getType()->isDoubleTy())
1046 LdExp = LibFunc::ldexp;
1048 if (TLI->has(LdExp)) {
1049 Value *LdExpArg = nullptr;
1050 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1051 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1052 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1053 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1054 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1055 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1059 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1060 if (!Op->getType()->isFloatTy())
1061 One = ConstantExpr::getFPExtend(One, Op->getType());
1063 Module *M = Caller->getParent();
1065 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1066 Op->getType(), B.getInt32Ty(), nullptr);
1067 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1068 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1069 CI->setCallingConv(F->getCallingConv());
1077 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1078 Function *Callee = CI->getCalledFunction();
1080 Value *Ret = nullptr;
1081 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1082 Ret = optimizeUnaryDoubleFP(CI, B, false);
1085 FunctionType *FT = Callee->getFunctionType();
1086 // Make sure this has 1 argument of FP type which matches the result type.
1087 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1088 !FT->getParamType(0)->isFloatingPointTy())
1091 Value *Op = CI->getArgOperand(0);
1092 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1093 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1094 if (I->getOpcode() == Instruction::FMul)
1095 if (I->getOperand(0) == I->getOperand(1))
1101 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1102 Function *Callee = CI->getCalledFunction();
1104 Value *Ret = nullptr;
1105 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1106 Callee->getIntrinsicID() == Intrinsic::sqrt))
1107 Ret = optimizeUnaryDoubleFP(CI, B, true);
1109 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1110 // fast-math flag decorations that are applied to FP instructions. For now,
1111 // we have to rely on the function-level unsafe-fp-math attribute to do this
1112 // optimization because there's no other way to express that the sqrt can be
1114 Function *F = CI->getParent()->getParent();
1115 if (F->hasFnAttribute("unsafe-fp-math")) {
1116 // Check for unsafe-fp-math = true.
1117 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1118 if (Attr.getValueAsString() != "true")
1121 Value *Op = CI->getArgOperand(0);
1122 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1123 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1124 // We're looking for a repeated factor in a multiplication tree,
1125 // so we can do this fold: sqrt(x * x) -> fabs(x);
1126 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1127 Value *Op0 = I->getOperand(0);
1128 Value *Op1 = I->getOperand(1);
1129 Value *RepeatOp = nullptr;
1130 Value *OtherOp = nullptr;
1132 // Simple match: the operands of the multiply are identical.
1135 // Look for a more complicated pattern: one of the operands is itself
1136 // a multiply, so search for a common factor in that multiply.
1137 // Note: We don't bother looking any deeper than this first level or for
1138 // variations of this pattern because instcombine's visitFMUL and/or the
1139 // reassociation pass should give us this form.
1140 Value *OtherMul0, *OtherMul1;
1141 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1142 // Pattern: sqrt((x * y) * z)
1143 if (OtherMul0 == OtherMul1) {
1144 // Matched: sqrt((x * x) * z)
1145 RepeatOp = OtherMul0;
1151 // Fast math flags for any created instructions should match the sqrt
1153 // FIXME: We're not checking the sqrt because it doesn't have
1154 // fast-math-flags (see earlier comment).
1155 IRBuilder<true, ConstantFolder,
1156 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1157 B.SetFastMathFlags(I->getFastMathFlags());
1158 // If we found a repeated factor, hoist it out of the square root and
1159 // replace it with the fabs of that factor.
1160 Module *M = Callee->getParent();
1161 Type *ArgType = Op->getType();
1162 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1163 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1165 // If we found a non-repeated factor, we still need to get its square
1166 // root. We then multiply that by the value that was simplified out
1167 // of the square root calculation.
1168 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1169 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1170 return B.CreateFMul(FabsCall, SqrtCall);
1179 static bool isTrigLibCall(CallInst *CI);
1180 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1181 bool UseFloat, Value *&Sin, Value *&Cos,
1184 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1186 // Make sure the prototype is as expected, otherwise the rest of the
1187 // function is probably invalid and likely to abort.
1188 if (!isTrigLibCall(CI))
1191 Value *Arg = CI->getArgOperand(0);
1192 SmallVector<CallInst *, 1> SinCalls;
1193 SmallVector<CallInst *, 1> CosCalls;
1194 SmallVector<CallInst *, 1> SinCosCalls;
1196 bool IsFloat = Arg->getType()->isFloatTy();
1198 // Look for all compatible sinpi, cospi and sincospi calls with the same
1199 // argument. If there are enough (in some sense) we can make the
1201 for (User *U : Arg->users())
1202 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1205 // It's only worthwhile if both sinpi and cospi are actually used.
1206 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1209 Value *Sin, *Cos, *SinCos;
1210 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1212 replaceTrigInsts(SinCalls, Sin);
1213 replaceTrigInsts(CosCalls, Cos);
1214 replaceTrigInsts(SinCosCalls, SinCos);
1219 static bool isTrigLibCall(CallInst *CI) {
1220 Function *Callee = CI->getCalledFunction();
1221 FunctionType *FT = Callee->getFunctionType();
1223 // We can only hope to do anything useful if we can ignore things like errno
1224 // and floating-point exceptions.
1225 bool AttributesSafe =
1226 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1228 // Other than that we need float(float) or double(double)
1229 return AttributesSafe && FT->getNumParams() == 1 &&
1230 FT->getReturnType() == FT->getParamType(0) &&
1231 (FT->getParamType(0)->isFloatTy() ||
1232 FT->getParamType(0)->isDoubleTy());
1236 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1237 SmallVectorImpl<CallInst *> &SinCalls,
1238 SmallVectorImpl<CallInst *> &CosCalls,
1239 SmallVectorImpl<CallInst *> &SinCosCalls) {
1240 CallInst *CI = dyn_cast<CallInst>(Val);
1245 Function *Callee = CI->getCalledFunction();
1246 StringRef FuncName = Callee->getName();
1248 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1252 if (Func == LibFunc::sinpif)
1253 SinCalls.push_back(CI);
1254 else if (Func == LibFunc::cospif)
1255 CosCalls.push_back(CI);
1256 else if (Func == LibFunc::sincospif_stret)
1257 SinCosCalls.push_back(CI);
1259 if (Func == LibFunc::sinpi)
1260 SinCalls.push_back(CI);
1261 else if (Func == LibFunc::cospi)
1262 CosCalls.push_back(CI);
1263 else if (Func == LibFunc::sincospi_stret)
1264 SinCosCalls.push_back(CI);
1268 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1270 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1272 replaceAllUsesWith(*I, Res);
1276 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1277 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1278 Type *ArgTy = Arg->getType();
1282 Triple T(OrigCallee->getParent()->getTargetTriple());
1284 Name = "__sincospif_stret";
1286 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1287 // x86_64 can't use {float, float} since that would be returned in both
1288 // xmm0 and xmm1, which isn't what a real struct would do.
1289 ResTy = T.getArch() == Triple::x86_64
1290 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1291 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1293 Name = "__sincospi_stret";
1294 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1297 Module *M = OrigCallee->getParent();
1298 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1299 ResTy, ArgTy, nullptr);
1301 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1302 // If the argument is an instruction, it must dominate all uses so put our
1303 // sincos call there.
1304 BasicBlock::iterator Loc = ArgInst;
1305 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1307 // Otherwise (e.g. for a constant) the beginning of the function is as
1308 // good a place as any.
1309 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1310 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1313 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1315 if (SinCos->getType()->isStructTy()) {
1316 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1317 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1319 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1321 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1326 //===----------------------------------------------------------------------===//
1327 // Integer Library Call Optimizations
1328 //===----------------------------------------------------------------------===//
1330 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1331 Function *Callee = CI->getCalledFunction();
1332 FunctionType *FT = Callee->getFunctionType();
1333 // Just make sure this has 2 arguments of the same FP type, which match the
1335 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1336 !FT->getParamType(0)->isIntegerTy())
1339 Value *Op = CI->getArgOperand(0);
1342 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1343 if (CI->isZero()) // ffs(0) -> 0.
1344 return B.getInt32(0);
1345 // ffs(c) -> cttz(c)+1
1346 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1349 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1350 Type *ArgType = Op->getType();
1352 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1353 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1354 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1355 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1357 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1358 return B.CreateSelect(Cond, V, B.getInt32(0));
1361 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1362 Function *Callee = CI->getCalledFunction();
1363 FunctionType *FT = Callee->getFunctionType();
1364 // We require integer(integer) where the types agree.
1365 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1366 FT->getParamType(0) != FT->getReturnType())
1369 // abs(x) -> x >s -1 ? x : -x
1370 Value *Op = CI->getArgOperand(0);
1372 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1373 Value *Neg = B.CreateNeg(Op, "neg");
1374 return B.CreateSelect(Pos, Op, Neg);
1377 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1378 Function *Callee = CI->getCalledFunction();
1379 FunctionType *FT = Callee->getFunctionType();
1380 // We require integer(i32)
1381 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1382 !FT->getParamType(0)->isIntegerTy(32))
1385 // isdigit(c) -> (c-'0') <u 10
1386 Value *Op = CI->getArgOperand(0);
1387 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1388 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1389 return B.CreateZExt(Op, CI->getType());
1392 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1393 Function *Callee = CI->getCalledFunction();
1394 FunctionType *FT = Callee->getFunctionType();
1395 // We require integer(i32)
1396 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1397 !FT->getParamType(0)->isIntegerTy(32))
1400 // isascii(c) -> c <u 128
1401 Value *Op = CI->getArgOperand(0);
1402 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1403 return B.CreateZExt(Op, CI->getType());
1406 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1407 Function *Callee = CI->getCalledFunction();
1408 FunctionType *FT = Callee->getFunctionType();
1409 // We require i32(i32)
1410 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1411 !FT->getParamType(0)->isIntegerTy(32))
1414 // toascii(c) -> c & 0x7f
1415 return B.CreateAnd(CI->getArgOperand(0),
1416 ConstantInt::get(CI->getType(), 0x7F));
1419 //===----------------------------------------------------------------------===//
1420 // Formatting and IO Library Call Optimizations
1421 //===----------------------------------------------------------------------===//
1423 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1425 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1427 // Error reporting calls should be cold, mark them as such.
1428 // This applies even to non-builtin calls: it is only a hint and applies to
1429 // functions that the frontend might not understand as builtins.
1431 // This heuristic was suggested in:
1432 // Improving Static Branch Prediction in a Compiler
1433 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1434 // Proceedings of PACT'98, Oct. 1998, IEEE
1435 Function *Callee = CI->getCalledFunction();
1437 if (!CI->hasFnAttr(Attribute::Cold) &&
1438 isReportingError(Callee, CI, StreamArg)) {
1439 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1445 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1446 if (!ColdErrorCalls)
1449 if (!Callee || !Callee->isDeclaration())
1455 // These functions might be considered cold, but only if their stream
1456 // argument is stderr.
1458 if (StreamArg >= (int)CI->getNumArgOperands())
1460 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1463 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1464 if (!GV || !GV->isDeclaration())
1466 return GV->getName() == "stderr";
1469 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1470 // Check for a fixed format string.
1471 StringRef FormatStr;
1472 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1475 // Empty format string -> noop.
1476 if (FormatStr.empty()) // Tolerate printf's declared void.
1477 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1479 // Do not do any of the following transformations if the printf return value
1480 // is used, in general the printf return value is not compatible with either
1481 // putchar() or puts().
1482 if (!CI->use_empty())
1485 // printf("x") -> putchar('x'), even for '%'.
1486 if (FormatStr.size() == 1) {
1487 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1488 if (CI->use_empty() || !Res)
1490 return B.CreateIntCast(Res, CI->getType(), true);
1493 // printf("foo\n") --> puts("foo")
1494 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1495 FormatStr.find('%') == StringRef::npos) { // No format characters.
1496 // Create a string literal with no \n on it. We expect the constant merge
1497 // pass to be run after this pass, to merge duplicate strings.
1498 FormatStr = FormatStr.drop_back();
1499 Value *GV = B.CreateGlobalString(FormatStr, "str");
1500 Value *NewCI = EmitPutS(GV, B, TLI);
1501 return (CI->use_empty() || !NewCI)
1503 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1506 // Optimize specific format strings.
1507 // printf("%c", chr) --> putchar(chr)
1508 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1509 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1510 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1512 if (CI->use_empty() || !Res)
1514 return B.CreateIntCast(Res, CI->getType(), true);
1517 // printf("%s\n", str) --> puts(str)
1518 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1519 CI->getArgOperand(1)->getType()->isPointerTy()) {
1520 return EmitPutS(CI->getArgOperand(1), B, TLI);
1525 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1527 Function *Callee = CI->getCalledFunction();
1528 // Require one fixed pointer argument and an integer/void result.
1529 FunctionType *FT = Callee->getFunctionType();
1530 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1531 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1534 if (Value *V = optimizePrintFString(CI, B)) {
1538 // printf(format, ...) -> iprintf(format, ...) if no floating point
1540 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1541 Module *M = B.GetInsertBlock()->getParent()->getParent();
1542 Constant *IPrintFFn =
1543 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1544 CallInst *New = cast<CallInst>(CI->clone());
1545 New->setCalledFunction(IPrintFFn);
1552 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1553 // Check for a fixed format string.
1554 StringRef FormatStr;
1555 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1558 // If we just have a format string (nothing else crazy) transform it.
1559 if (CI->getNumArgOperands() == 2) {
1560 // Make sure there's no % in the constant array. We could try to handle
1561 // %% -> % in the future if we cared.
1562 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1563 if (FormatStr[i] == '%')
1564 return nullptr; // we found a format specifier, bail out.
1566 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1567 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1568 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1569 FormatStr.size() + 1),
1570 1); // Copy the null byte.
1571 return ConstantInt::get(CI->getType(), FormatStr.size());
1574 // The remaining optimizations require the format string to be "%s" or "%c"
1575 // and have an extra operand.
1576 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1577 CI->getNumArgOperands() < 3)
1580 // Decode the second character of the format string.
1581 if (FormatStr[1] == 'c') {
1582 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1583 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1585 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1586 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1587 B.CreateStore(V, Ptr);
1588 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1589 B.CreateStore(B.getInt8(0), Ptr);
1591 return ConstantInt::get(CI->getType(), 1);
1594 if (FormatStr[1] == 's') {
1595 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1596 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1599 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1603 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1604 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1606 // The sprintf result is the unincremented number of bytes in the string.
1607 return B.CreateIntCast(Len, CI->getType(), false);
1612 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1613 Function *Callee = CI->getCalledFunction();
1614 // Require two fixed pointer arguments and an integer result.
1615 FunctionType *FT = Callee->getFunctionType();
1616 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1617 !FT->getParamType(1)->isPointerTy() ||
1618 !FT->getReturnType()->isIntegerTy())
1621 if (Value *V = optimizeSPrintFString(CI, B)) {
1625 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1627 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1628 Module *M = B.GetInsertBlock()->getParent()->getParent();
1629 Constant *SIPrintFFn =
1630 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1631 CallInst *New = cast<CallInst>(CI->clone());
1632 New->setCalledFunction(SIPrintFFn);
1639 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1640 optimizeErrorReporting(CI, B, 0);
1642 // All the optimizations depend on the format string.
1643 StringRef FormatStr;
1644 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1647 // Do not do any of the following transformations if the fprintf return
1648 // value is used, in general the fprintf return value is not compatible
1649 // with fwrite(), fputc() or fputs().
1650 if (!CI->use_empty())
1653 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1654 if (CI->getNumArgOperands() == 2) {
1655 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1656 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1657 return nullptr; // We found a format specifier.
1660 CI->getArgOperand(1),
1661 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1662 CI->getArgOperand(0), B, DL, TLI);
1665 // The remaining optimizations require the format string to be "%s" or "%c"
1666 // and have an extra operand.
1667 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1668 CI->getNumArgOperands() < 3)
1671 // Decode the second character of the format string.
1672 if (FormatStr[1] == 'c') {
1673 // fprintf(F, "%c", chr) --> fputc(chr, F)
1674 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1676 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1679 if (FormatStr[1] == 's') {
1680 // fprintf(F, "%s", str) --> fputs(str, F)
1681 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1683 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1688 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1689 Function *Callee = CI->getCalledFunction();
1690 // Require two fixed paramters as pointers and integer result.
1691 FunctionType *FT = Callee->getFunctionType();
1692 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1693 !FT->getParamType(1)->isPointerTy() ||
1694 !FT->getReturnType()->isIntegerTy())
1697 if (Value *V = optimizeFPrintFString(CI, B)) {
1701 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1702 // floating point arguments.
1703 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1704 Module *M = B.GetInsertBlock()->getParent()->getParent();
1705 Constant *FIPrintFFn =
1706 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1707 CallInst *New = cast<CallInst>(CI->clone());
1708 New->setCalledFunction(FIPrintFFn);
1715 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1716 optimizeErrorReporting(CI, B, 3);
1718 Function *Callee = CI->getCalledFunction();
1719 // Require a pointer, an integer, an integer, a pointer, returning integer.
1720 FunctionType *FT = Callee->getFunctionType();
1721 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1722 !FT->getParamType(1)->isIntegerTy() ||
1723 !FT->getParamType(2)->isIntegerTy() ||
1724 !FT->getParamType(3)->isPointerTy() ||
1725 !FT->getReturnType()->isIntegerTy())
1728 // Get the element size and count.
1729 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1730 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1731 if (!SizeC || !CountC)
1733 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1735 // If this is writing zero records, remove the call (it's a noop).
1737 return ConstantInt::get(CI->getType(), 0);
1739 // If this is writing one byte, turn it into fputc.
1740 // This optimisation is only valid, if the return value is unused.
1741 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1742 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1743 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1744 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1750 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1751 optimizeErrorReporting(CI, B, 1);
1753 Function *Callee = CI->getCalledFunction();
1755 // Require two pointers. Also, we can't optimize if return value is used.
1756 FunctionType *FT = Callee->getFunctionType();
1757 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1758 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1761 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1762 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1766 // Known to have no uses (see above).
1768 CI->getArgOperand(0),
1769 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1770 CI->getArgOperand(1), B, DL, TLI);
1773 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1774 Function *Callee = CI->getCalledFunction();
1775 // Require one fixed pointer argument and an integer/void result.
1776 FunctionType *FT = Callee->getFunctionType();
1777 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1778 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1781 // Check for a constant string.
1783 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1786 if (Str.empty() && CI->use_empty()) {
1787 // puts("") -> putchar('\n')
1788 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1789 if (CI->use_empty() || !Res)
1791 return B.CreateIntCast(Res, CI->getType(), true);
1797 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1799 SmallString<20> FloatFuncName = FuncName;
1800 FloatFuncName += 'f';
1801 if (TLI->getLibFunc(FloatFuncName, Func))
1802 return TLI->has(Func);
1806 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1807 IRBuilder<> &Builder) {
1809 Function *Callee = CI->getCalledFunction();
1810 StringRef FuncName = Callee->getName();
1812 // Check for string/memory library functions.
1813 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1814 // Make sure we never change the calling convention.
1815 assert((ignoreCallingConv(Func) ||
1816 CI->getCallingConv() == llvm::CallingConv::C) &&
1817 "Optimizing string/memory libcall would change the calling convention");
1819 case LibFunc::strcat:
1820 return optimizeStrCat(CI, Builder);
1821 case LibFunc::strncat:
1822 return optimizeStrNCat(CI, Builder);
1823 case LibFunc::strchr:
1824 return optimizeStrChr(CI, Builder);
1825 case LibFunc::strrchr:
1826 return optimizeStrRChr(CI, Builder);
1827 case LibFunc::strcmp:
1828 return optimizeStrCmp(CI, Builder);
1829 case LibFunc::strncmp:
1830 return optimizeStrNCmp(CI, Builder);
1831 case LibFunc::strcpy:
1832 return optimizeStrCpy(CI, Builder);
1833 case LibFunc::stpcpy:
1834 return optimizeStpCpy(CI, Builder);
1835 case LibFunc::strncpy:
1836 return optimizeStrNCpy(CI, Builder);
1837 case LibFunc::strlen:
1838 return optimizeStrLen(CI, Builder);
1839 case LibFunc::strpbrk:
1840 return optimizeStrPBrk(CI, Builder);
1841 case LibFunc::strtol:
1842 case LibFunc::strtod:
1843 case LibFunc::strtof:
1844 case LibFunc::strtoul:
1845 case LibFunc::strtoll:
1846 case LibFunc::strtold:
1847 case LibFunc::strtoull:
1848 return optimizeStrTo(CI, Builder);
1849 case LibFunc::strspn:
1850 return optimizeStrSpn(CI, Builder);
1851 case LibFunc::strcspn:
1852 return optimizeStrCSpn(CI, Builder);
1853 case LibFunc::strstr:
1854 return optimizeStrStr(CI, Builder);
1855 case LibFunc::memcmp:
1856 return optimizeMemCmp(CI, Builder);
1857 case LibFunc::memcpy:
1858 return optimizeMemCpy(CI, Builder);
1859 case LibFunc::memmove:
1860 return optimizeMemMove(CI, Builder);
1861 case LibFunc::memset:
1862 return optimizeMemSet(CI, Builder);
1870 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1871 if (CI->isNoBuiltin())
1875 Function *Callee = CI->getCalledFunction();
1876 StringRef FuncName = Callee->getName();
1877 IRBuilder<> Builder(CI);
1878 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1880 // Command-line parameter overrides function attribute.
1881 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1882 UnsafeFPShrink = EnableUnsafeFPShrink;
1883 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
1884 // FIXME: This is the same problem as described in optimizeSqrt().
1885 // If calls gain access to IR-level FMF, then use that instead of a
1886 // function attribute.
1888 // Check for unsafe-fp-math = true.
1889 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
1890 if (Attr.getValueAsString() == "true")
1891 UnsafeFPShrink = true;
1894 // First, check for intrinsics.
1895 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1896 if (!isCallingConvC)
1898 switch (II->getIntrinsicID()) {
1899 case Intrinsic::pow:
1900 return optimizePow(CI, Builder);
1901 case Intrinsic::exp2:
1902 return optimizeExp2(CI, Builder);
1903 case Intrinsic::fabs:
1904 return optimizeFabs(CI, Builder);
1905 case Intrinsic::sqrt:
1906 return optimizeSqrt(CI, Builder);
1912 // Also try to simplify calls to fortified library functions.
1913 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
1914 // Try to further simplify the result.
1915 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
1916 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
1917 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
1918 // If we were able to further simplify, remove the now redundant call.
1919 SimplifiedCI->replaceAllUsesWith(V);
1920 SimplifiedCI->eraseFromParent();
1923 return SimplifiedFortifiedCI;
1926 // Then check for known library functions.
1927 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1928 // We never change the calling convention.
1929 if (!ignoreCallingConv(Func) && !isCallingConvC)
1931 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
1937 return optimizeCos(CI, Builder);
1938 case LibFunc::sinpif:
1939 case LibFunc::sinpi:
1940 case LibFunc::cospif:
1941 case LibFunc::cospi:
1942 return optimizeSinCosPi(CI, Builder);
1946 return optimizePow(CI, Builder);
1947 case LibFunc::exp2l:
1949 case LibFunc::exp2f:
1950 return optimizeExp2(CI, Builder);
1951 case LibFunc::fabsf:
1953 case LibFunc::fabsl:
1954 return optimizeFabs(CI, Builder);
1955 case LibFunc::sqrtf:
1957 case LibFunc::sqrtl:
1958 return optimizeSqrt(CI, Builder);
1961 case LibFunc::ffsll:
1962 return optimizeFFS(CI, Builder);
1965 case LibFunc::llabs:
1966 return optimizeAbs(CI, Builder);
1967 case LibFunc::isdigit:
1968 return optimizeIsDigit(CI, Builder);
1969 case LibFunc::isascii:
1970 return optimizeIsAscii(CI, Builder);
1971 case LibFunc::toascii:
1972 return optimizeToAscii(CI, Builder);
1973 case LibFunc::printf:
1974 return optimizePrintF(CI, Builder);
1975 case LibFunc::sprintf:
1976 return optimizeSPrintF(CI, Builder);
1977 case LibFunc::fprintf:
1978 return optimizeFPrintF(CI, Builder);
1979 case LibFunc::fwrite:
1980 return optimizeFWrite(CI, Builder);
1981 case LibFunc::fputs:
1982 return optimizeFPuts(CI, Builder);
1984 return optimizePuts(CI, Builder);
1985 case LibFunc::perror:
1986 return optimizeErrorReporting(CI, Builder);
1987 case LibFunc::vfprintf:
1988 case LibFunc::fiprintf:
1989 return optimizeErrorReporting(CI, Builder, 0);
1990 case LibFunc::fputc:
1991 return optimizeErrorReporting(CI, Builder, 1);
1993 case LibFunc::floor:
1995 case LibFunc::round:
1996 case LibFunc::nearbyint:
1997 case LibFunc::trunc:
1998 if (hasFloatVersion(FuncName))
1999 return optimizeUnaryDoubleFP(CI, Builder, false);
2002 case LibFunc::acosh:
2004 case LibFunc::asinh:
2006 case LibFunc::atanh:
2010 case LibFunc::exp10:
2011 case LibFunc::expm1:
2013 case LibFunc::log10:
2014 case LibFunc::log1p:
2021 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2022 return optimizeUnaryDoubleFP(CI, Builder, true);
2024 case LibFunc::copysign:
2027 if (hasFloatVersion(FuncName))
2028 return optimizeBinaryDoubleFP(CI, Builder);
2037 LibCallSimplifier::LibCallSimplifier(
2038 const DataLayout &DL, const TargetLibraryInfo *TLI,
2039 function_ref<void(Instruction *, Value *)> Replacer)
2040 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2041 Replacer(Replacer) {}
2043 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2044 // Indirect through the replacer used in this instance.
2048 /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2050 I->replaceAllUsesWith(With);
2051 I->eraseFromParent();
2055 // Additional cases that we need to add to this file:
2058 // * cbrt(expN(X)) -> expN(x/3)
2059 // * cbrt(sqrt(x)) -> pow(x,1/6)
2060 // * cbrt(sqrt(x)) -> pow(x,1/9)
2063 // * exp(log(x)) -> x
2066 // * log(exp(x)) -> x
2067 // * log(x**y) -> y*log(x)
2068 // * log(exp(y)) -> y*log(e)
2069 // * log(exp2(y)) -> y*log(2)
2070 // * log(exp10(y)) -> y*log(10)
2071 // * log(sqrt(x)) -> 0.5*log(x)
2072 // * log(pow(x,y)) -> y*log(x)
2074 // lround, lroundf, lroundl:
2075 // * lround(cnst) -> cnst'
2078 // * pow(exp(x),y) -> exp(x*y)
2079 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2080 // * pow(pow(x,y),z)-> pow(x,y*z)
2082 // round, roundf, roundl:
2083 // * round(cnst) -> cnst'
2086 // * signbit(cnst) -> cnst'
2087 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2089 // sqrt, sqrtf, sqrtl:
2090 // * sqrt(expN(x)) -> expN(x*0.5)
2091 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2092 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2095 // * tan(atan(x)) -> x
2097 // trunc, truncf, truncl:
2098 // * trunc(cnst) -> cnst'
2102 //===----------------------------------------------------------------------===//
2103 // Fortified Library Call Optimizations
2104 //===----------------------------------------------------------------------===//
2106 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2110 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2112 if (ConstantInt *ObjSizeCI =
2113 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2114 if (ObjSizeCI->isAllOnesValue())
2116 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2117 if (OnlyLowerUnknownSize)
2120 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2121 // If the length is 0 we don't know how long it is and so we can't
2122 // remove the check.
2125 return ObjSizeCI->getZExtValue() >= Len;
2127 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2128 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2133 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2134 Function *Callee = CI->getCalledFunction();
2136 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2139 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2140 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2141 CI->getArgOperand(2), 1);
2142 return CI->getArgOperand(0);
2147 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2148 Function *Callee = CI->getCalledFunction();
2150 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2153 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2154 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2155 CI->getArgOperand(2), 1);
2156 return CI->getArgOperand(0);
2161 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2162 Function *Callee = CI->getCalledFunction();
2164 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2167 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2168 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2169 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2170 return CI->getArgOperand(0);
2175 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2177 LibFunc::Func Func) {
2178 Function *Callee = CI->getCalledFunction();
2179 StringRef Name = Callee->getName();
2180 const DataLayout &DL = CI->getModule()->getDataLayout();
2182 if (!checkStringCopyLibFuncSignature(Callee, Func))
2185 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2186 *ObjSize = CI->getArgOperand(2);
2188 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2189 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2190 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2191 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
2194 // If a) we don't have any length information, or b) we know this will
2195 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2196 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2197 // TODO: It might be nice to get a maximum length out of the possible
2198 // string lengths for varying.
2199 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
2200 Value *Ret = EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2202 } else if (!OnlyLowerUnknownSize) {
2203 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2204 uint64_t Len = GetStringLength(Src);
2208 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2209 Value *LenV = ConstantInt::get(SizeTTy, Len);
2210 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2211 // If the function was an __stpcpy_chk, and we were able to fold it into
2212 // a __memcpy_chk, we still need to return the correct end pointer.
2213 if (Ret && Func == LibFunc::stpcpy_chk)
2214 return B.CreateGEP(Dst, ConstantInt::get(SizeTTy, Len - 1));
2220 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2222 LibFunc::Func Func) {
2223 Function *Callee = CI->getCalledFunction();
2224 StringRef Name = Callee->getName();
2226 if (!checkStringCopyLibFuncSignature(Callee, Func))
2228 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2229 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2230 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2236 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2237 if (CI->isNoBuiltin())
2241 Function *Callee = CI->getCalledFunction();
2242 StringRef FuncName = Callee->getName();
2243 IRBuilder<> Builder(CI);
2244 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2246 // First, check that this is a known library functions.
2247 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func))
2250 // We never change the calling convention.
2251 if (!ignoreCallingConv(Func) && !isCallingConvC)
2255 case LibFunc::memcpy_chk:
2256 return optimizeMemCpyChk(CI, Builder);
2257 case LibFunc::memmove_chk:
2258 return optimizeMemMoveChk(CI, Builder);
2259 case LibFunc::memset_chk:
2260 return optimizeMemSetChk(CI, Builder);
2261 case LibFunc::stpcpy_chk:
2262 case LibFunc::strcpy_chk:
2263 return optimizeStrpCpyChk(CI, Builder, Func);
2264 case LibFunc::stpncpy_chk:
2265 case LibFunc::strncpy_chk:
2266 return optimizeStrpNCpyChk(CI, Builder, Func);
2273 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2274 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2275 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}