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/Target/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) {
125 FunctionType *FT = F->getFunctionType();
126 LLVMContext &Context = F->getContext();
127 Type *PCharTy = Type::getInt8PtrTy(Context);
128 Type *SizeTTy = DL ? DL->getIntPtrType(Context) : nullptr;
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 // Fortified Library Call Optimizations
185 //===----------------------------------------------------------------------===//
187 static bool isFortifiedCallFoldable(CallInst *CI, unsigned SizeCIOp, unsigned SizeArgOp,
189 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
191 if (ConstantInt *SizeCI =
192 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
193 if (SizeCI->isAllOnesValue())
196 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
197 // If the length is 0 we don't know how long it is and so we can't
201 return SizeCI->getZExtValue() >= Len;
203 if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getArgOperand(SizeArgOp)))
204 return SizeCI->getZExtValue() >= Arg->getZExtValue();
209 Value *LibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
210 Function *Callee = CI->getCalledFunction();
211 FunctionType *FT = Callee->getFunctionType();
212 LLVMContext &Context = CI->getContext();
214 // Check if this has the right signature.
215 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
216 !FT->getParamType(0)->isPointerTy() ||
217 !FT->getParamType(1)->isPointerTy() ||
218 FT->getParamType(2) != DL->getIntPtrType(Context) ||
219 FT->getParamType(3) != DL->getIntPtrType(Context))
222 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
223 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
224 CI->getArgOperand(2), 1);
225 return CI->getArgOperand(0);
230 Value *LibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
231 Function *Callee = CI->getCalledFunction();
232 FunctionType *FT = Callee->getFunctionType();
233 LLVMContext &Context = CI->getContext();
235 // Check if this has the right signature.
236 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
237 !FT->getParamType(0)->isPointerTy() ||
238 !FT->getParamType(1)->isPointerTy() ||
239 FT->getParamType(2) != DL->getIntPtrType(Context) ||
240 FT->getParamType(3) != DL->getIntPtrType(Context))
243 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
244 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
245 CI->getArgOperand(2), 1);
246 return CI->getArgOperand(0);
251 Value *LibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
252 Function *Callee = CI->getCalledFunction();
253 FunctionType *FT = Callee->getFunctionType();
254 LLVMContext &Context = CI->getContext();
256 // Check if this has the right signature.
257 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
258 !FT->getParamType(0)->isPointerTy() ||
259 !FT->getParamType(1)->isIntegerTy() ||
260 FT->getParamType(2) != DL->getIntPtrType(Context) ||
261 FT->getParamType(3) != DL->getIntPtrType(Context))
264 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
265 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
266 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
267 return CI->getArgOperand(0);
272 Value *LibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
273 Function *Callee = CI->getCalledFunction();
274 StringRef Name = Callee->getName();
275 FunctionType *FT = Callee->getFunctionType();
276 LLVMContext &Context = CI->getContext();
278 // Check if this has the right signature.
279 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
280 FT->getParamType(0) != FT->getParamType(1) ||
281 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
282 FT->getParamType(2) != DL->getIntPtrType(Context))
285 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
286 if (Dst == Src) // __strcpy_chk(x,x) -> x
289 // If a) we don't have any length information, or b) we know this will
290 // fit then just lower to a plain strcpy. Otherwise we'll keep our
291 // strcpy_chk call which may fail at runtime if the size is too long.
292 // TODO: It might be nice to get a maximum length out of the possible
293 // string lengths for varying.
294 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
295 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
298 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
299 uint64_t Len = GetStringLength(Src);
303 // This optimization require DataLayout.
307 Value *Ret = EmitMemCpyChk(
308 Dst, Src, ConstantInt::get(DL->getIntPtrType(Context), Len),
309 CI->getArgOperand(2), B, DL, TLI);
315 Value *LibCallSimplifier::optimizeStpCpyChk(CallInst *CI, IRBuilder<> &B) {
316 Function *Callee = CI->getCalledFunction();
317 StringRef Name = Callee->getName();
318 FunctionType *FT = Callee->getFunctionType();
319 LLVMContext &Context = CI->getContext();
321 // Check if this has the right signature.
322 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
323 FT->getParamType(0) != FT->getParamType(1) ||
324 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
325 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
328 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
329 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
330 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
331 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
334 // If a) we don't have any length information, or b) we know this will
335 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
336 // stpcpy_chk call which may fail at runtime if the size is too long.
337 // TODO: It might be nice to get a maximum length out of the possible
338 // string lengths for varying.
339 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
340 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
343 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
344 uint64_t Len = GetStringLength(Src);
348 // This optimization require DataLayout.
352 Type *PT = FT->getParamType(0);
353 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
355 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
356 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
363 Value *LibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
364 Function *Callee = CI->getCalledFunction();
365 StringRef Name = Callee->getName();
366 FunctionType *FT = Callee->getFunctionType();
367 LLVMContext &Context = CI->getContext();
369 // Check if this has the right signature.
370 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
371 FT->getParamType(0) != FT->getParamType(1) ||
372 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
373 !FT->getParamType(2)->isIntegerTy() ||
374 FT->getParamType(3) != DL->getIntPtrType(Context))
377 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
379 EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
380 CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
386 //===----------------------------------------------------------------------===//
387 // String and Memory Library Call Optimizations
388 //===----------------------------------------------------------------------===//
390 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
391 Function *Callee = CI->getCalledFunction();
392 // Verify the "strcat" function prototype.
393 FunctionType *FT = Callee->getFunctionType();
394 if (FT->getNumParams() != 2||
395 FT->getReturnType() != B.getInt8PtrTy() ||
396 FT->getParamType(0) != FT->getReturnType() ||
397 FT->getParamType(1) != FT->getReturnType())
400 // Extract some information from the instruction
401 Value *Dst = CI->getArgOperand(0);
402 Value *Src = CI->getArgOperand(1);
404 // See if we can get the length of the input string.
405 uint64_t Len = GetStringLength(Src);
408 --Len; // Unbias length.
410 // Handle the simple, do-nothing case: strcat(x, "") -> x
414 // These optimizations require DataLayout.
418 return emitStrLenMemCpy(Src, Dst, Len, B);
421 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
423 // We need to find the end of the destination string. That's where the
424 // memory is to be moved to. We just generate a call to strlen.
425 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
429 // Now that we have the destination's length, we must index into the
430 // destination's pointer to get the actual memcpy destination (end of
431 // the string .. we're concatenating).
432 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
434 // We have enough information to now generate the memcpy call to do the
435 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
438 ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
442 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
443 Function *Callee = CI->getCalledFunction();
444 // Verify the "strncat" function prototype.
445 FunctionType *FT = Callee->getFunctionType();
446 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
447 FT->getParamType(0) != FT->getReturnType() ||
448 FT->getParamType(1) != FT->getReturnType() ||
449 !FT->getParamType(2)->isIntegerTy())
452 // Extract some information from the instruction
453 Value *Dst = CI->getArgOperand(0);
454 Value *Src = CI->getArgOperand(1);
457 // We don't do anything if length is not constant
458 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
459 Len = LengthArg->getZExtValue();
463 // See if we can get the length of the input string.
464 uint64_t SrcLen = GetStringLength(Src);
467 --SrcLen; // Unbias length.
469 // Handle the simple, do-nothing cases:
470 // strncat(x, "", c) -> x
471 // strncat(x, c, 0) -> x
472 if (SrcLen == 0 || Len == 0)
475 // These optimizations require DataLayout.
479 // We don't optimize this case
483 // strncat(x, s, c) -> strcat(x, s)
484 // s is constant so the strcat can be optimized further
485 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
488 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
489 Function *Callee = CI->getCalledFunction();
490 // Verify the "strchr" function prototype.
491 FunctionType *FT = Callee->getFunctionType();
492 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
493 FT->getParamType(0) != FT->getReturnType() ||
494 !FT->getParamType(1)->isIntegerTy(32))
497 Value *SrcStr = CI->getArgOperand(0);
499 // If the second operand is non-constant, see if we can compute the length
500 // of the input string and turn this into memchr.
501 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
503 // These optimizations require DataLayout.
507 uint64_t Len = GetStringLength(SrcStr);
508 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
512 SrcStr, CI->getArgOperand(1), // include nul.
513 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
516 // Otherwise, the character is a constant, see if the first argument is
517 // a string literal. If so, we can constant fold.
519 if (!getConstantStringInfo(SrcStr, Str)) {
520 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
521 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
525 // Compute the offset, make sure to handle the case when we're searching for
526 // zero (a weird way to spell strlen).
527 size_t I = (0xFF & CharC->getSExtValue()) == 0
529 : Str.find(CharC->getSExtValue());
530 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
531 return Constant::getNullValue(CI->getType());
533 // strchr(s+n,c) -> gep(s+n+i,c)
534 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
537 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
538 Function *Callee = CI->getCalledFunction();
539 // Verify the "strrchr" function prototype.
540 FunctionType *FT = Callee->getFunctionType();
541 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
542 FT->getParamType(0) != FT->getReturnType() ||
543 !FT->getParamType(1)->isIntegerTy(32))
546 Value *SrcStr = CI->getArgOperand(0);
547 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
549 // Cannot fold anything if we're not looking for a constant.
554 if (!getConstantStringInfo(SrcStr, Str)) {
555 // strrchr(s, 0) -> strchr(s, 0)
556 if (DL && CharC->isZero())
557 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
561 // Compute the offset.
562 size_t I = (0xFF & CharC->getSExtValue()) == 0
564 : Str.rfind(CharC->getSExtValue());
565 if (I == StringRef::npos) // Didn't find the char. Return null.
566 return Constant::getNullValue(CI->getType());
568 // strrchr(s+n,c) -> gep(s+n+i,c)
569 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
572 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
573 Function *Callee = CI->getCalledFunction();
574 // Verify the "strcmp" function prototype.
575 FunctionType *FT = Callee->getFunctionType();
576 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
577 FT->getParamType(0) != FT->getParamType(1) ||
578 FT->getParamType(0) != B.getInt8PtrTy())
581 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
582 if (Str1P == Str2P) // strcmp(x,x) -> 0
583 return ConstantInt::get(CI->getType(), 0);
585 StringRef Str1, Str2;
586 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
587 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
589 // strcmp(x, y) -> cnst (if both x and y are constant strings)
590 if (HasStr1 && HasStr2)
591 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
593 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
595 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
597 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
598 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
600 // strcmp(P, "x") -> memcmp(P, "x", 2)
601 uint64_t Len1 = GetStringLength(Str1P);
602 uint64_t Len2 = GetStringLength(Str2P);
604 // These optimizations require DataLayout.
608 return EmitMemCmp(Str1P, Str2P,
609 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
610 std::min(Len1, Len2)),
617 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
618 Function *Callee = CI->getCalledFunction();
619 // Verify the "strncmp" function prototype.
620 FunctionType *FT = Callee->getFunctionType();
621 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
622 FT->getParamType(0) != FT->getParamType(1) ||
623 FT->getParamType(0) != B.getInt8PtrTy() ||
624 !FT->getParamType(2)->isIntegerTy())
627 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
628 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
629 return ConstantInt::get(CI->getType(), 0);
631 // Get the length argument if it is constant.
633 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
634 Length = LengthArg->getZExtValue();
638 if (Length == 0) // strncmp(x,y,0) -> 0
639 return ConstantInt::get(CI->getType(), 0);
641 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
642 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
644 StringRef Str1, Str2;
645 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
646 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
648 // strncmp(x, y) -> cnst (if both x and y are constant strings)
649 if (HasStr1 && HasStr2) {
650 StringRef SubStr1 = Str1.substr(0, Length);
651 StringRef SubStr2 = Str2.substr(0, Length);
652 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
655 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
657 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
659 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
660 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
665 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
666 Function *Callee = CI->getCalledFunction();
668 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy, DL))
671 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
672 if (Dst == Src) // strcpy(x,x) -> x
675 // These optimizations require DataLayout.
679 // See if we can get the length of the input string.
680 uint64_t Len = GetStringLength(Src);
684 // We have enough information to now generate the memcpy call to do the
685 // copy for us. Make a memcpy to copy the nul byte with align = 1.
686 B.CreateMemCpy(Dst, Src,
687 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
691 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
692 Function *Callee = CI->getCalledFunction();
693 // Verify the "stpcpy" function prototype.
694 FunctionType *FT = Callee->getFunctionType();
696 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy, DL))
699 // These optimizations require DataLayout.
703 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
704 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
705 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
706 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
709 // See if we can get the length of the input string.
710 uint64_t Len = GetStringLength(Src);
714 Type *PT = FT->getParamType(0);
715 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
717 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
719 // We have enough information to now generate the memcpy call to do the
720 // copy for us. Make a memcpy to copy the nul byte with align = 1.
721 B.CreateMemCpy(Dst, Src, LenV, 1);
725 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
726 Function *Callee = CI->getCalledFunction();
727 FunctionType *FT = Callee->getFunctionType();
729 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy, DL))
732 Value *Dst = CI->getArgOperand(0);
733 Value *Src = CI->getArgOperand(1);
734 Value *LenOp = CI->getArgOperand(2);
736 // See if we can get the length of the input string.
737 uint64_t SrcLen = GetStringLength(Src);
743 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
744 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
749 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
750 Len = LengthArg->getZExtValue();
755 return Dst; // strncpy(x, y, 0) -> x
757 // These optimizations require DataLayout.
761 // Let strncpy handle the zero padding
762 if (Len > SrcLen + 1)
765 Type *PT = FT->getParamType(0);
766 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
767 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
772 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
773 Function *Callee = CI->getCalledFunction();
774 FunctionType *FT = Callee->getFunctionType();
775 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
776 !FT->getReturnType()->isIntegerTy())
779 Value *Src = CI->getArgOperand(0);
781 // Constant folding: strlen("xyz") -> 3
782 if (uint64_t Len = GetStringLength(Src))
783 return ConstantInt::get(CI->getType(), Len - 1);
785 // strlen(x?"foo":"bars") --> x ? 3 : 4
786 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
787 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
788 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
789 if (LenTrue && LenFalse) {
790 Function *Caller = CI->getParent()->getParent();
791 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
793 "folded strlen(select) to select of constants");
794 return B.CreateSelect(SI->getCondition(),
795 ConstantInt::get(CI->getType(), LenTrue - 1),
796 ConstantInt::get(CI->getType(), LenFalse - 1));
800 // strlen(x) != 0 --> *x != 0
801 // strlen(x) == 0 --> *x == 0
802 if (isOnlyUsedInZeroEqualityComparison(CI))
803 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
808 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
809 Function *Callee = CI->getCalledFunction();
810 FunctionType *FT = Callee->getFunctionType();
811 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
812 FT->getParamType(1) != FT->getParamType(0) ||
813 FT->getReturnType() != FT->getParamType(0))
817 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
818 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
820 // strpbrk(s, "") -> nullptr
821 // strpbrk("", s) -> nullptr
822 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
823 return Constant::getNullValue(CI->getType());
826 if (HasS1 && HasS2) {
827 size_t I = S1.find_first_of(S2);
828 if (I == StringRef::npos) // No match.
829 return Constant::getNullValue(CI->getType());
831 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
834 // strpbrk(s, "a") -> strchr(s, 'a')
835 if (DL && HasS2 && S2.size() == 1)
836 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
841 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
842 Function *Callee = CI->getCalledFunction();
843 FunctionType *FT = Callee->getFunctionType();
844 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
845 !FT->getParamType(0)->isPointerTy() ||
846 !FT->getParamType(1)->isPointerTy())
849 Value *EndPtr = CI->getArgOperand(1);
850 if (isa<ConstantPointerNull>(EndPtr)) {
851 // With a null EndPtr, this function won't capture the main argument.
852 // It would be readonly too, except that it still may write to errno.
853 CI->addAttribute(1, Attribute::NoCapture);
859 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
860 Function *Callee = CI->getCalledFunction();
861 FunctionType *FT = Callee->getFunctionType();
862 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
863 FT->getParamType(1) != FT->getParamType(0) ||
864 !FT->getReturnType()->isIntegerTy())
868 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
869 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
871 // strspn(s, "") -> 0
872 // strspn("", s) -> 0
873 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
874 return Constant::getNullValue(CI->getType());
877 if (HasS1 && HasS2) {
878 size_t Pos = S1.find_first_not_of(S2);
879 if (Pos == StringRef::npos)
881 return ConstantInt::get(CI->getType(), Pos);
887 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
888 Function *Callee = CI->getCalledFunction();
889 FunctionType *FT = Callee->getFunctionType();
890 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
891 FT->getParamType(1) != FT->getParamType(0) ||
892 !FT->getReturnType()->isIntegerTy())
896 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
897 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
899 // strcspn("", s) -> 0
900 if (HasS1 && S1.empty())
901 return Constant::getNullValue(CI->getType());
904 if (HasS1 && HasS2) {
905 size_t Pos = S1.find_first_of(S2);
906 if (Pos == StringRef::npos)
908 return ConstantInt::get(CI->getType(), Pos);
911 // strcspn(s, "") -> strlen(s)
912 if (DL && HasS2 && S2.empty())
913 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
918 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
919 Function *Callee = CI->getCalledFunction();
920 FunctionType *FT = Callee->getFunctionType();
921 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
922 !FT->getParamType(1)->isPointerTy() ||
923 !FT->getReturnType()->isPointerTy())
926 // fold strstr(x, x) -> x.
927 if (CI->getArgOperand(0) == CI->getArgOperand(1))
928 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
930 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
931 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
932 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
935 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
939 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
940 ICmpInst *Old = cast<ICmpInst>(*UI++);
942 B.CreateICmp(Old->getPredicate(), StrNCmp,
943 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
944 replaceAllUsesWith(Old, Cmp);
949 // See if either input string is a constant string.
950 StringRef SearchStr, ToFindStr;
951 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
952 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
954 // fold strstr(x, "") -> x.
955 if (HasStr2 && ToFindStr.empty())
956 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
958 // If both strings are known, constant fold it.
959 if (HasStr1 && HasStr2) {
960 size_t Offset = SearchStr.find(ToFindStr);
962 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
963 return Constant::getNullValue(CI->getType());
965 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
966 Value *Result = CastToCStr(CI->getArgOperand(0), B);
967 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
968 return B.CreateBitCast(Result, CI->getType());
971 // fold strstr(x, "y") -> strchr(x, 'y').
972 if (HasStr2 && ToFindStr.size() == 1) {
973 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
974 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
979 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
980 Function *Callee = CI->getCalledFunction();
981 FunctionType *FT = Callee->getFunctionType();
982 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
983 !FT->getParamType(1)->isPointerTy() ||
984 !FT->getReturnType()->isIntegerTy(32))
987 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
989 if (LHS == RHS) // memcmp(s,s,x) -> 0
990 return Constant::getNullValue(CI->getType());
992 // Make sure we have a constant length.
993 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
996 uint64_t Len = LenC->getZExtValue();
998 if (Len == 0) // memcmp(s1,s2,0) -> 0
999 return Constant::getNullValue(CI->getType());
1001 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1003 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
1004 CI->getType(), "lhsv");
1005 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
1006 CI->getType(), "rhsv");
1007 return B.CreateSub(LHSV, RHSV, "chardiff");
1010 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1011 StringRef LHSStr, RHSStr;
1012 if (getConstantStringInfo(LHS, LHSStr) &&
1013 getConstantStringInfo(RHS, RHSStr)) {
1014 // Make sure we're not reading out-of-bounds memory.
1015 if (Len > LHSStr.size() || Len > RHSStr.size())
1017 // Fold the memcmp and normalize the result. This way we get consistent
1018 // results across multiple platforms.
1020 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1025 return ConstantInt::get(CI->getType(), Ret);
1031 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
1032 Function *Callee = CI->getCalledFunction();
1033 // These optimizations require DataLayout.
1037 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy, DL))
1040 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1041 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1042 CI->getArgOperand(2), 1);
1043 return CI->getArgOperand(0);
1046 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
1047 Function *Callee = CI->getCalledFunction();
1048 // These optimizations require DataLayout.
1052 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove, DL))
1055 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1056 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1057 CI->getArgOperand(2), 1);
1058 return CI->getArgOperand(0);
1061 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1062 Function *Callee = CI->getCalledFunction();
1063 // These optimizations require DataLayout.
1067 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset, DL))
1070 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1071 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1072 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1073 return CI->getArgOperand(0);
1076 //===----------------------------------------------------------------------===//
1077 // Math Library Optimizations
1078 //===----------------------------------------------------------------------===//
1080 /// Return a variant of Val with float type.
1081 /// Currently this works in two cases: If Val is an FPExtension of a float
1082 /// value to something bigger, simply return the operand.
1083 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1084 /// loss of precision do so.
1085 static Value *valueHasFloatPrecision(Value *Val) {
1086 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1087 Value *Op = Cast->getOperand(0);
1088 if (Op->getType()->isFloatTy())
1091 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1092 APFloat F = Const->getValueAPF();
1094 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1097 return ConstantFP::get(Const->getContext(), F);
1102 //===----------------------------------------------------------------------===//
1103 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1105 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1106 bool CheckRetType) {
1107 Function *Callee = CI->getCalledFunction();
1108 FunctionType *FT = Callee->getFunctionType();
1109 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1110 !FT->getParamType(0)->isDoubleTy())
1114 // Check if all the uses for function like 'sin' are converted to float.
1115 for (User *U : CI->users()) {
1116 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1117 if (!Cast || !Cast->getType()->isFloatTy())
1122 // If this is something like 'floor((double)floatval)', convert to floorf.
1123 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1127 // floor((double)floatval) -> (double)floorf(floatval)
1128 if (Callee->isIntrinsic()) {
1129 Module *M = CI->getParent()->getParent()->getParent();
1130 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
1131 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1132 V = B.CreateCall(F, V);
1134 // The call is a library call rather than an intrinsic.
1135 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1138 return B.CreateFPExt(V, B.getDoubleTy());
1141 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1142 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1143 Function *Callee = CI->getCalledFunction();
1144 FunctionType *FT = Callee->getFunctionType();
1145 // Just make sure this has 2 arguments of the same FP type, which match the
1147 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1148 FT->getParamType(0) != FT->getParamType(1) ||
1149 !FT->getParamType(0)->isFloatingPointTy())
1152 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1153 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1154 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1157 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1161 // fmin((double)floatval1, (double)floatval2)
1162 // -> (double)fminf(floatval1, floatval2)
1163 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1164 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1165 Callee->getAttributes());
1166 return B.CreateFPExt(V, B.getDoubleTy());
1169 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1170 Function *Callee = CI->getCalledFunction();
1171 Value *Ret = nullptr;
1172 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1173 Ret = optimizeUnaryDoubleFP(CI, B, true);
1176 FunctionType *FT = Callee->getFunctionType();
1177 // Just make sure this has 1 argument of FP type, which matches the
1179 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1180 !FT->getParamType(0)->isFloatingPointTy())
1183 // cos(-x) -> cos(x)
1184 Value *Op1 = CI->getArgOperand(0);
1185 if (BinaryOperator::isFNeg(Op1)) {
1186 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1187 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1192 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1193 Function *Callee = CI->getCalledFunction();
1195 Value *Ret = nullptr;
1196 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1197 Ret = optimizeUnaryDoubleFP(CI, B, true);
1200 FunctionType *FT = Callee->getFunctionType();
1201 // Just make sure this has 2 arguments of the same FP type, which match the
1203 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1204 FT->getParamType(0) != FT->getParamType(1) ||
1205 !FT->getParamType(0)->isFloatingPointTy())
1208 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1209 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1210 // pow(1.0, x) -> 1.0
1211 if (Op1C->isExactlyValue(1.0))
1213 // pow(2.0, x) -> exp2(x)
1214 if (Op1C->isExactlyValue(2.0) &&
1215 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1217 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1218 // pow(10.0, x) -> exp10(x)
1219 if (Op1C->isExactlyValue(10.0) &&
1220 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1222 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1223 Callee->getAttributes());
1226 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1230 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1231 return ConstantFP::get(CI->getType(), 1.0);
1233 if (Op2C->isExactlyValue(0.5) &&
1234 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1236 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1238 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1239 // This is faster than calling pow, and still handles negative zero
1240 // and negative infinity correctly.
1241 // TODO: In fast-math mode, this could be just sqrt(x).
1242 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1243 Value *Inf = ConstantFP::getInfinity(CI->getType());
1244 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1245 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1247 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1248 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1249 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1253 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1255 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1256 return B.CreateFMul(Op1, Op1, "pow2");
1257 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1258 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1262 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1263 Function *Callee = CI->getCalledFunction();
1264 Function *Caller = CI->getParent()->getParent();
1266 Value *Ret = nullptr;
1267 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1268 TLI->has(LibFunc::exp2f)) {
1269 Ret = optimizeUnaryDoubleFP(CI, B, true);
1272 FunctionType *FT = Callee->getFunctionType();
1273 // Just make sure this has 1 argument of FP type, which matches the
1275 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1276 !FT->getParamType(0)->isFloatingPointTy())
1279 Value *Op = CI->getArgOperand(0);
1280 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1281 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1282 LibFunc::Func LdExp = LibFunc::ldexpl;
1283 if (Op->getType()->isFloatTy())
1284 LdExp = LibFunc::ldexpf;
1285 else if (Op->getType()->isDoubleTy())
1286 LdExp = LibFunc::ldexp;
1288 if (TLI->has(LdExp)) {
1289 Value *LdExpArg = nullptr;
1290 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1291 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1292 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1293 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1294 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1295 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1299 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1300 if (!Op->getType()->isFloatTy())
1301 One = ConstantExpr::getFPExtend(One, Op->getType());
1303 Module *M = Caller->getParent();
1305 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1306 Op->getType(), B.getInt32Ty(), nullptr);
1307 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1308 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1309 CI->setCallingConv(F->getCallingConv());
1317 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1318 Function *Callee = CI->getCalledFunction();
1320 Value *Ret = nullptr;
1321 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1322 Ret = optimizeUnaryDoubleFP(CI, B, false);
1325 FunctionType *FT = Callee->getFunctionType();
1326 // Make sure this has 1 argument of FP type which matches the result type.
1327 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1328 !FT->getParamType(0)->isFloatingPointTy())
1331 Value *Op = CI->getArgOperand(0);
1332 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1333 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1334 if (I->getOpcode() == Instruction::FMul)
1335 if (I->getOperand(0) == I->getOperand(1))
1341 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1342 Function *Callee = CI->getCalledFunction();
1344 Value *Ret = nullptr;
1345 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1346 Callee->getIntrinsicID() == Intrinsic::sqrt))
1347 Ret = optimizeUnaryDoubleFP(CI, B, true);
1349 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1350 // fast-math flag decorations that are applied to FP instructions. For now,
1351 // we have to rely on the function-level unsafe-fp-math attribute to do this
1352 // optimization because there's no other way to express that the sqrt can be
1354 Function *F = CI->getParent()->getParent();
1355 if (F->hasFnAttribute("unsafe-fp-math")) {
1356 // Check for unsafe-fp-math = true.
1357 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1358 if (Attr.getValueAsString() != "true")
1361 Value *Op = CI->getArgOperand(0);
1362 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1363 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1364 // We're looking for a repeated factor in a multiplication tree,
1365 // so we can do this fold: sqrt(x * x) -> fabs(x);
1366 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1367 Value *Op0 = I->getOperand(0);
1368 Value *Op1 = I->getOperand(1);
1369 Value *RepeatOp = nullptr;
1370 Value *OtherOp = nullptr;
1372 // Simple match: the operands of the multiply are identical.
1375 // Look for a more complicated pattern: one of the operands is itself
1376 // a multiply, so search for a common factor in that multiply.
1377 // Note: We don't bother looking any deeper than this first level or for
1378 // variations of this pattern because instcombine's visitFMUL and/or the
1379 // reassociation pass should give us this form.
1380 Value *OtherMul0, *OtherMul1;
1381 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1382 // Pattern: sqrt((x * y) * z)
1383 if (OtherMul0 == OtherMul1) {
1384 // Matched: sqrt((x * x) * z)
1385 RepeatOp = OtherMul0;
1391 // Fast math flags for any created instructions should match the sqrt
1393 // FIXME: We're not checking the sqrt because it doesn't have
1394 // fast-math-flags (see earlier comment).
1395 IRBuilder<true, ConstantFolder,
1396 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1397 B.SetFastMathFlags(I->getFastMathFlags());
1398 // If we found a repeated factor, hoist it out of the square root and
1399 // replace it with the fabs of that factor.
1400 Module *M = Callee->getParent();
1401 Type *ArgType = Op->getType();
1402 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1403 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1405 // If we found a non-repeated factor, we still need to get its square
1406 // root. We then multiply that by the value that was simplified out
1407 // of the square root calculation.
1408 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1409 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1410 return B.CreateFMul(FabsCall, SqrtCall);
1419 static bool isTrigLibCall(CallInst *CI);
1420 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1421 bool UseFloat, Value *&Sin, Value *&Cos,
1424 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1426 // Make sure the prototype is as expected, otherwise the rest of the
1427 // function is probably invalid and likely to abort.
1428 if (!isTrigLibCall(CI))
1431 Value *Arg = CI->getArgOperand(0);
1432 SmallVector<CallInst *, 1> SinCalls;
1433 SmallVector<CallInst *, 1> CosCalls;
1434 SmallVector<CallInst *, 1> SinCosCalls;
1436 bool IsFloat = Arg->getType()->isFloatTy();
1438 // Look for all compatible sinpi, cospi and sincospi calls with the same
1439 // argument. If there are enough (in some sense) we can make the
1441 for (User *U : Arg->users())
1442 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1445 // It's only worthwhile if both sinpi and cospi are actually used.
1446 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1449 Value *Sin, *Cos, *SinCos;
1450 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1452 replaceTrigInsts(SinCalls, Sin);
1453 replaceTrigInsts(CosCalls, Cos);
1454 replaceTrigInsts(SinCosCalls, SinCos);
1459 static bool isTrigLibCall(CallInst *CI) {
1460 Function *Callee = CI->getCalledFunction();
1461 FunctionType *FT = Callee->getFunctionType();
1463 // We can only hope to do anything useful if we can ignore things like errno
1464 // and floating-point exceptions.
1465 bool AttributesSafe =
1466 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1468 // Other than that we need float(float) or double(double)
1469 return AttributesSafe && FT->getNumParams() == 1 &&
1470 FT->getReturnType() == FT->getParamType(0) &&
1471 (FT->getParamType(0)->isFloatTy() ||
1472 FT->getParamType(0)->isDoubleTy());
1476 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1477 SmallVectorImpl<CallInst *> &SinCalls,
1478 SmallVectorImpl<CallInst *> &CosCalls,
1479 SmallVectorImpl<CallInst *> &SinCosCalls) {
1480 CallInst *CI = dyn_cast<CallInst>(Val);
1485 Function *Callee = CI->getCalledFunction();
1486 StringRef FuncName = Callee->getName();
1488 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1492 if (Func == LibFunc::sinpif)
1493 SinCalls.push_back(CI);
1494 else if (Func == LibFunc::cospif)
1495 CosCalls.push_back(CI);
1496 else if (Func == LibFunc::sincospif_stret)
1497 SinCosCalls.push_back(CI);
1499 if (Func == LibFunc::sinpi)
1500 SinCalls.push_back(CI);
1501 else if (Func == LibFunc::cospi)
1502 CosCalls.push_back(CI);
1503 else if (Func == LibFunc::sincospi_stret)
1504 SinCosCalls.push_back(CI);
1508 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1510 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1512 replaceAllUsesWith(*I, Res);
1516 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1517 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1518 Type *ArgTy = Arg->getType();
1522 Triple T(OrigCallee->getParent()->getTargetTriple());
1524 Name = "__sincospif_stret";
1526 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1527 // x86_64 can't use {float, float} since that would be returned in both
1528 // xmm0 and xmm1, which isn't what a real struct would do.
1529 ResTy = T.getArch() == Triple::x86_64
1530 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1531 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1533 Name = "__sincospi_stret";
1534 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1537 Module *M = OrigCallee->getParent();
1538 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1539 ResTy, ArgTy, nullptr);
1541 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1542 // If the argument is an instruction, it must dominate all uses so put our
1543 // sincos call there.
1544 BasicBlock::iterator Loc = ArgInst;
1545 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1547 // Otherwise (e.g. for a constant) the beginning of the function is as
1548 // good a place as any.
1549 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1550 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1553 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1555 if (SinCos->getType()->isStructTy()) {
1556 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1557 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1559 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1561 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1566 //===----------------------------------------------------------------------===//
1567 // Integer Library Call Optimizations
1568 //===----------------------------------------------------------------------===//
1570 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1571 Function *Callee = CI->getCalledFunction();
1572 FunctionType *FT = Callee->getFunctionType();
1573 // Just make sure this has 2 arguments of the same FP type, which match the
1575 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1576 !FT->getParamType(0)->isIntegerTy())
1579 Value *Op = CI->getArgOperand(0);
1582 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1583 if (CI->isZero()) // ffs(0) -> 0.
1584 return B.getInt32(0);
1585 // ffs(c) -> cttz(c)+1
1586 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1589 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1590 Type *ArgType = Op->getType();
1592 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1593 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1594 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1595 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1597 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1598 return B.CreateSelect(Cond, V, B.getInt32(0));
1601 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1602 Function *Callee = CI->getCalledFunction();
1603 FunctionType *FT = Callee->getFunctionType();
1604 // We require integer(integer) where the types agree.
1605 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1606 FT->getParamType(0) != FT->getReturnType())
1609 // abs(x) -> x >s -1 ? x : -x
1610 Value *Op = CI->getArgOperand(0);
1612 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1613 Value *Neg = B.CreateNeg(Op, "neg");
1614 return B.CreateSelect(Pos, Op, Neg);
1617 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1618 Function *Callee = CI->getCalledFunction();
1619 FunctionType *FT = Callee->getFunctionType();
1620 // We require integer(i32)
1621 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1622 !FT->getParamType(0)->isIntegerTy(32))
1625 // isdigit(c) -> (c-'0') <u 10
1626 Value *Op = CI->getArgOperand(0);
1627 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1628 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1629 return B.CreateZExt(Op, CI->getType());
1632 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1633 Function *Callee = CI->getCalledFunction();
1634 FunctionType *FT = Callee->getFunctionType();
1635 // We require integer(i32)
1636 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1637 !FT->getParamType(0)->isIntegerTy(32))
1640 // isascii(c) -> c <u 128
1641 Value *Op = CI->getArgOperand(0);
1642 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1643 return B.CreateZExt(Op, CI->getType());
1646 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1647 Function *Callee = CI->getCalledFunction();
1648 FunctionType *FT = Callee->getFunctionType();
1649 // We require i32(i32)
1650 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1651 !FT->getParamType(0)->isIntegerTy(32))
1654 // toascii(c) -> c & 0x7f
1655 return B.CreateAnd(CI->getArgOperand(0),
1656 ConstantInt::get(CI->getType(), 0x7F));
1659 //===----------------------------------------------------------------------===//
1660 // Formatting and IO Library Call Optimizations
1661 //===----------------------------------------------------------------------===//
1663 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1665 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1667 // Error reporting calls should be cold, mark them as such.
1668 // This applies even to non-builtin calls: it is only a hint and applies to
1669 // functions that the frontend might not understand as builtins.
1671 // This heuristic was suggested in:
1672 // Improving Static Branch Prediction in a Compiler
1673 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1674 // Proceedings of PACT'98, Oct. 1998, IEEE
1675 Function *Callee = CI->getCalledFunction();
1677 if (!CI->hasFnAttr(Attribute::Cold) &&
1678 isReportingError(Callee, CI, StreamArg)) {
1679 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1685 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1686 if (!ColdErrorCalls)
1689 if (!Callee || !Callee->isDeclaration())
1695 // These functions might be considered cold, but only if their stream
1696 // argument is stderr.
1698 if (StreamArg >= (int)CI->getNumArgOperands())
1700 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1703 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1704 if (!GV || !GV->isDeclaration())
1706 return GV->getName() == "stderr";
1709 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1710 // Check for a fixed format string.
1711 StringRef FormatStr;
1712 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1715 // Empty format string -> noop.
1716 if (FormatStr.empty()) // Tolerate printf's declared void.
1717 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1719 // Do not do any of the following transformations if the printf return value
1720 // is used, in general the printf return value is not compatible with either
1721 // putchar() or puts().
1722 if (!CI->use_empty())
1725 // printf("x") -> putchar('x'), even for '%'.
1726 if (FormatStr.size() == 1) {
1727 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1728 if (CI->use_empty() || !Res)
1730 return B.CreateIntCast(Res, CI->getType(), true);
1733 // printf("foo\n") --> puts("foo")
1734 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1735 FormatStr.find('%') == StringRef::npos) { // No format characters.
1736 // Create a string literal with no \n on it. We expect the constant merge
1737 // pass to be run after this pass, to merge duplicate strings.
1738 FormatStr = FormatStr.drop_back();
1739 Value *GV = B.CreateGlobalString(FormatStr, "str");
1740 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1741 return (CI->use_empty() || !NewCI)
1743 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1746 // Optimize specific format strings.
1747 // printf("%c", chr) --> putchar(chr)
1748 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1749 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1750 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1752 if (CI->use_empty() || !Res)
1754 return B.CreateIntCast(Res, CI->getType(), true);
1757 // printf("%s\n", str) --> puts(str)
1758 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1759 CI->getArgOperand(1)->getType()->isPointerTy()) {
1760 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1765 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1767 Function *Callee = CI->getCalledFunction();
1768 // Require one fixed pointer argument and an integer/void result.
1769 FunctionType *FT = Callee->getFunctionType();
1770 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1771 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1774 if (Value *V = optimizePrintFString(CI, B)) {
1778 // printf(format, ...) -> iprintf(format, ...) if no floating point
1780 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1781 Module *M = B.GetInsertBlock()->getParent()->getParent();
1782 Constant *IPrintFFn =
1783 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1784 CallInst *New = cast<CallInst>(CI->clone());
1785 New->setCalledFunction(IPrintFFn);
1792 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1793 // Check for a fixed format string.
1794 StringRef FormatStr;
1795 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1798 // If we just have a format string (nothing else crazy) transform it.
1799 if (CI->getNumArgOperands() == 2) {
1800 // Make sure there's no % in the constant array. We could try to handle
1801 // %% -> % in the future if we cared.
1802 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1803 if (FormatStr[i] == '%')
1804 return nullptr; // we found a format specifier, bail out.
1806 // These optimizations require DataLayout.
1810 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1812 CI->getArgOperand(0), CI->getArgOperand(1),
1813 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1814 FormatStr.size() + 1),
1815 1); // Copy the null byte.
1816 return ConstantInt::get(CI->getType(), FormatStr.size());
1819 // The remaining optimizations require the format string to be "%s" or "%c"
1820 // and have an extra operand.
1821 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1822 CI->getNumArgOperands() < 3)
1825 // Decode the second character of the format string.
1826 if (FormatStr[1] == 'c') {
1827 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1828 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1830 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1831 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1832 B.CreateStore(V, Ptr);
1833 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1834 B.CreateStore(B.getInt8(0), Ptr);
1836 return ConstantInt::get(CI->getType(), 1);
1839 if (FormatStr[1] == 's') {
1840 // These optimizations require DataLayout.
1844 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1845 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1848 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1852 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1853 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1855 // The sprintf result is the unincremented number of bytes in the string.
1856 return B.CreateIntCast(Len, CI->getType(), false);
1861 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1862 Function *Callee = CI->getCalledFunction();
1863 // Require two fixed pointer arguments and an integer result.
1864 FunctionType *FT = Callee->getFunctionType();
1865 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1866 !FT->getParamType(1)->isPointerTy() ||
1867 !FT->getReturnType()->isIntegerTy())
1870 if (Value *V = optimizeSPrintFString(CI, B)) {
1874 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1876 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1877 Module *M = B.GetInsertBlock()->getParent()->getParent();
1878 Constant *SIPrintFFn =
1879 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1880 CallInst *New = cast<CallInst>(CI->clone());
1881 New->setCalledFunction(SIPrintFFn);
1888 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1889 optimizeErrorReporting(CI, B, 0);
1891 // All the optimizations depend on the format string.
1892 StringRef FormatStr;
1893 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1896 // Do not do any of the following transformations if the fprintf return
1897 // value is used, in general the fprintf return value is not compatible
1898 // with fwrite(), fputc() or fputs().
1899 if (!CI->use_empty())
1902 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1903 if (CI->getNumArgOperands() == 2) {
1904 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1905 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1906 return nullptr; // We found a format specifier.
1908 // These optimizations require DataLayout.
1913 CI->getArgOperand(1),
1914 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1915 CI->getArgOperand(0), B, DL, TLI);
1918 // The remaining optimizations require the format string to be "%s" or "%c"
1919 // and have an extra operand.
1920 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1921 CI->getNumArgOperands() < 3)
1924 // Decode the second character of the format string.
1925 if (FormatStr[1] == 'c') {
1926 // fprintf(F, "%c", chr) --> fputc(chr, F)
1927 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1929 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1932 if (FormatStr[1] == 's') {
1933 // fprintf(F, "%s", str) --> fputs(str, F)
1934 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1936 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1941 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1942 Function *Callee = CI->getCalledFunction();
1943 // Require two fixed paramters as pointers and integer result.
1944 FunctionType *FT = Callee->getFunctionType();
1945 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1946 !FT->getParamType(1)->isPointerTy() ||
1947 !FT->getReturnType()->isIntegerTy())
1950 if (Value *V = optimizeFPrintFString(CI, B)) {
1954 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1955 // floating point arguments.
1956 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1957 Module *M = B.GetInsertBlock()->getParent()->getParent();
1958 Constant *FIPrintFFn =
1959 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1960 CallInst *New = cast<CallInst>(CI->clone());
1961 New->setCalledFunction(FIPrintFFn);
1968 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1969 optimizeErrorReporting(CI, B, 3);
1971 Function *Callee = CI->getCalledFunction();
1972 // Require a pointer, an integer, an integer, a pointer, returning integer.
1973 FunctionType *FT = Callee->getFunctionType();
1974 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1975 !FT->getParamType(1)->isIntegerTy() ||
1976 !FT->getParamType(2)->isIntegerTy() ||
1977 !FT->getParamType(3)->isPointerTy() ||
1978 !FT->getReturnType()->isIntegerTy())
1981 // Get the element size and count.
1982 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1983 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1984 if (!SizeC || !CountC)
1986 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1988 // If this is writing zero records, remove the call (it's a noop).
1990 return ConstantInt::get(CI->getType(), 0);
1992 // If this is writing one byte, turn it into fputc.
1993 // This optimisation is only valid, if the return value is unused.
1994 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1995 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1996 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1997 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2003 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2004 optimizeErrorReporting(CI, B, 1);
2006 Function *Callee = CI->getCalledFunction();
2008 // These optimizations require DataLayout.
2012 // Require two pointers. Also, we can't optimize if return value is used.
2013 FunctionType *FT = Callee->getFunctionType();
2014 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2015 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2018 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2019 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2023 // Known to have no uses (see above).
2025 CI->getArgOperand(0),
2026 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
2027 CI->getArgOperand(1), B, DL, TLI);
2030 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2031 Function *Callee = CI->getCalledFunction();
2032 // Require one fixed pointer argument and an integer/void result.
2033 FunctionType *FT = Callee->getFunctionType();
2034 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2035 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2038 // Check for a constant string.
2040 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2043 if (Str.empty() && CI->use_empty()) {
2044 // puts("") -> putchar('\n')
2045 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
2046 if (CI->use_empty() || !Res)
2048 return B.CreateIntCast(Res, CI->getType(), true);
2054 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2056 SmallString<20> FloatFuncName = FuncName;
2057 FloatFuncName += 'f';
2058 if (TLI->getLibFunc(FloatFuncName, Func))
2059 return TLI->has(Func);
2063 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2064 IRBuilder<> &Builder) {
2066 Function *Callee = CI->getCalledFunction();
2067 StringRef FuncName = Callee->getName();
2069 // Check for string/memory library functions.
2070 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2071 // Make sure we never change the calling convention.
2072 assert((ignoreCallingConv(Func) ||
2073 CI->getCallingConv() == llvm::CallingConv::C) &&
2074 "Optimizing string/memory libcall would change the calling convention");
2076 case LibFunc::strcat:
2077 return optimizeStrCat(CI, Builder);
2078 case LibFunc::strncat:
2079 return optimizeStrNCat(CI, Builder);
2080 case LibFunc::strchr:
2081 return optimizeStrChr(CI, Builder);
2082 case LibFunc::strrchr:
2083 return optimizeStrRChr(CI, Builder);
2084 case LibFunc::strcmp:
2085 return optimizeStrCmp(CI, Builder);
2086 case LibFunc::strncmp:
2087 return optimizeStrNCmp(CI, Builder);
2088 case LibFunc::strcpy:
2089 return optimizeStrCpy(CI, Builder);
2090 case LibFunc::stpcpy:
2091 return optimizeStpCpy(CI, Builder);
2092 case LibFunc::strncpy:
2093 return optimizeStrNCpy(CI, Builder);
2094 case LibFunc::strlen:
2095 return optimizeStrLen(CI, Builder);
2096 case LibFunc::strpbrk:
2097 return optimizeStrPBrk(CI, Builder);
2098 case LibFunc::strtol:
2099 case LibFunc::strtod:
2100 case LibFunc::strtof:
2101 case LibFunc::strtoul:
2102 case LibFunc::strtoll:
2103 case LibFunc::strtold:
2104 case LibFunc::strtoull:
2105 return optimizeStrTo(CI, Builder);
2106 case LibFunc::strspn:
2107 return optimizeStrSpn(CI, Builder);
2108 case LibFunc::strcspn:
2109 return optimizeStrCSpn(CI, Builder);
2110 case LibFunc::strstr:
2111 return optimizeStrStr(CI, Builder);
2112 case LibFunc::memcmp:
2113 return optimizeMemCmp(CI, Builder);
2114 case LibFunc::memcpy:
2115 return optimizeMemCpy(CI, Builder);
2116 case LibFunc::memmove:
2117 return optimizeMemMove(CI, Builder);
2118 case LibFunc::memset:
2119 return optimizeMemSet(CI, Builder);
2127 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2128 if (CI->isNoBuiltin())
2132 Function *Callee = CI->getCalledFunction();
2133 StringRef FuncName = Callee->getName();
2134 IRBuilder<> Builder(CI);
2135 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2137 // Command-line parameter overrides function attribute.
2138 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2139 UnsafeFPShrink = EnableUnsafeFPShrink;
2140 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2141 // FIXME: This is the same problem as described in optimizeSqrt().
2142 // If calls gain access to IR-level FMF, then use that instead of a
2143 // function attribute.
2145 // Check for unsafe-fp-math = true.
2146 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2147 if (Attr.getValueAsString() == "true")
2148 UnsafeFPShrink = true;
2151 // First, check for intrinsics.
2152 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2153 if (!isCallingConvC)
2155 switch (II->getIntrinsicID()) {
2156 case Intrinsic::pow:
2157 return optimizePow(CI, Builder);
2158 case Intrinsic::exp2:
2159 return optimizeExp2(CI, Builder);
2160 case Intrinsic::fabs:
2161 return optimizeFabs(CI, Builder);
2162 case Intrinsic::sqrt:
2163 return optimizeSqrt(CI, Builder);
2169 // Then check for known library functions.
2170 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2171 // We never change the calling convention.
2172 if (!ignoreCallingConv(Func) && !isCallingConvC)
2174 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2180 return optimizeCos(CI, Builder);
2181 case LibFunc::sinpif:
2182 case LibFunc::sinpi:
2183 case LibFunc::cospif:
2184 case LibFunc::cospi:
2185 return optimizeSinCosPi(CI, Builder);
2189 return optimizePow(CI, Builder);
2190 case LibFunc::exp2l:
2192 case LibFunc::exp2f:
2193 return optimizeExp2(CI, Builder);
2194 case LibFunc::fabsf:
2196 case LibFunc::fabsl:
2197 return optimizeFabs(CI, Builder);
2198 case LibFunc::sqrtf:
2200 case LibFunc::sqrtl:
2201 return optimizeSqrt(CI, Builder);
2204 case LibFunc::ffsll:
2205 return optimizeFFS(CI, Builder);
2208 case LibFunc::llabs:
2209 return optimizeAbs(CI, Builder);
2210 case LibFunc::isdigit:
2211 return optimizeIsDigit(CI, Builder);
2212 case LibFunc::isascii:
2213 return optimizeIsAscii(CI, Builder);
2214 case LibFunc::toascii:
2215 return optimizeToAscii(CI, Builder);
2216 case LibFunc::printf:
2217 return optimizePrintF(CI, Builder);
2218 case LibFunc::sprintf:
2219 return optimizeSPrintF(CI, Builder);
2220 case LibFunc::fprintf:
2221 return optimizeFPrintF(CI, Builder);
2222 case LibFunc::fwrite:
2223 return optimizeFWrite(CI, Builder);
2224 case LibFunc::fputs:
2225 return optimizeFPuts(CI, Builder);
2227 return optimizePuts(CI, Builder);
2228 case LibFunc::perror:
2229 return optimizeErrorReporting(CI, Builder);
2230 case LibFunc::vfprintf:
2231 case LibFunc::fiprintf:
2232 return optimizeErrorReporting(CI, Builder, 0);
2233 case LibFunc::fputc:
2234 return optimizeErrorReporting(CI, Builder, 1);
2236 case LibFunc::floor:
2238 case LibFunc::round:
2239 case LibFunc::nearbyint:
2240 case LibFunc::trunc:
2241 if (hasFloatVersion(FuncName))
2242 return optimizeUnaryDoubleFP(CI, Builder, false);
2245 case LibFunc::acosh:
2247 case LibFunc::asinh:
2249 case LibFunc::atanh:
2253 case LibFunc::exp10:
2254 case LibFunc::expm1:
2256 case LibFunc::log10:
2257 case LibFunc::log1p:
2264 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2265 return optimizeUnaryDoubleFP(CI, Builder, true);
2267 case LibFunc::copysign:
2270 if (hasFloatVersion(FuncName))
2271 return optimizeBinaryDoubleFP(CI, Builder);
2273 case LibFunc::memcpy_chk:
2274 return optimizeMemCpyChk(CI, Builder);
2275 case LibFunc::memmove_chk:
2276 return optimizeMemMoveChk(CI, Builder);
2277 case LibFunc::memset_chk:
2278 return optimizeMemSetChk(CI, Builder);
2279 case LibFunc::strcpy_chk:
2280 return optimizeStrCpyChk(CI, Builder);
2281 case LibFunc::stpcpy_chk:
2282 return optimizeStpCpyChk(CI, Builder);
2283 case LibFunc::stpncpy_chk:
2284 case LibFunc::strncpy_chk:
2285 return optimizeStrNCpyChk(CI, Builder);
2294 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2295 const TargetLibraryInfo *TLI) :
2298 UnsafeFPShrink(false) {
2301 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2302 I->replaceAllUsesWith(With);
2303 I->eraseFromParent();
2307 // Additional cases that we need to add to this file:
2310 // * cbrt(expN(X)) -> expN(x/3)
2311 // * cbrt(sqrt(x)) -> pow(x,1/6)
2312 // * cbrt(sqrt(x)) -> pow(x,1/9)
2315 // * exp(log(x)) -> x
2318 // * log(exp(x)) -> x
2319 // * log(x**y) -> y*log(x)
2320 // * log(exp(y)) -> y*log(e)
2321 // * log(exp2(y)) -> y*log(2)
2322 // * log(exp10(y)) -> y*log(10)
2323 // * log(sqrt(x)) -> 0.5*log(x)
2324 // * log(pow(x,y)) -> y*log(x)
2326 // lround, lroundf, lroundl:
2327 // * lround(cnst) -> cnst'
2330 // * pow(exp(x),y) -> exp(x*y)
2331 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2332 // * pow(pow(x,y),z)-> pow(x,y*z)
2334 // round, roundf, roundl:
2335 // * round(cnst) -> cnst'
2338 // * signbit(cnst) -> cnst'
2339 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2341 // sqrt, sqrtf, sqrtl:
2342 // * sqrt(expN(x)) -> expN(x*0.5)
2343 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2344 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2347 // * tan(atan(x)) -> x
2349 // trunc, truncf, truncl:
2350 // * trunc(cnst) -> cnst'