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"));
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 static bool ignoreCallingConv(LibFunc::Func Func) {
57 llvm_unreachable("All cases should be covered in the switch.");
60 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
61 /// value is equal or not-equal to zero.
62 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
63 for (User *U : V->users()) {
64 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
66 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
69 // Unknown instruction.
75 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
76 /// comparisons with With.
77 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
78 for (User *U : V->users()) {
79 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
80 if (IC->isEquality() && IC->getOperand(1) == With)
82 // Unknown instruction.
88 static bool callHasFloatingPointArgument(const CallInst *CI) {
89 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
91 if ((*it)->getType()->isFloatingPointTy())
97 /// \brief Check whether the overloaded unary floating point function
98 /// corresponing to \a Ty is available.
99 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
100 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
101 LibFunc::Func LongDoubleFn) {
102 switch (Ty->getTypeID()) {
103 case Type::FloatTyID:
104 return TLI->has(FloatFn);
105 case Type::DoubleTyID:
106 return TLI->has(DoubleFn);
108 return TLI->has(LongDoubleFn);
112 //===----------------------------------------------------------------------===//
113 // Fortified Library Call Optimizations
114 //===----------------------------------------------------------------------===//
116 static bool isFortifiedCallFoldable(CallInst *CI, unsigned SizeCIOp, unsigned SizeArgOp,
118 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
120 if (ConstantInt *SizeCI =
121 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
122 if (SizeCI->isAllOnesValue())
125 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
126 // If the length is 0 we don't know how long it is and so we can't
130 return SizeCI->getZExtValue() >= Len;
132 if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getArgOperand(SizeArgOp)))
133 return SizeCI->getZExtValue() >= Arg->getZExtValue();
138 Value *LibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
139 Function *Callee = CI->getCalledFunction();
140 FunctionType *FT = Callee->getFunctionType();
141 LLVMContext &Context = CI->getContext();
143 // Check if this has the right signature.
144 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
145 !FT->getParamType(0)->isPointerTy() ||
146 !FT->getParamType(1)->isPointerTy() ||
147 FT->getParamType(2) != DL->getIntPtrType(Context) ||
148 FT->getParamType(3) != DL->getIntPtrType(Context))
151 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
152 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
153 CI->getArgOperand(2), 1);
154 return CI->getArgOperand(0);
159 Value *LibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
160 Function *Callee = CI->getCalledFunction();
161 FunctionType *FT = Callee->getFunctionType();
162 LLVMContext &Context = CI->getContext();
164 // Check if this has the right signature.
165 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
166 !FT->getParamType(0)->isPointerTy() ||
167 !FT->getParamType(1)->isPointerTy() ||
168 FT->getParamType(2) != DL->getIntPtrType(Context) ||
169 FT->getParamType(3) != DL->getIntPtrType(Context))
172 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
173 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
174 CI->getArgOperand(2), 1);
175 return CI->getArgOperand(0);
180 Value *LibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
181 Function *Callee = CI->getCalledFunction();
182 FunctionType *FT = Callee->getFunctionType();
183 LLVMContext &Context = CI->getContext();
185 // Check if this has the right signature.
186 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
187 !FT->getParamType(0)->isPointerTy() ||
188 !FT->getParamType(1)->isIntegerTy() ||
189 FT->getParamType(2) != DL->getIntPtrType(Context) ||
190 FT->getParamType(3) != DL->getIntPtrType(Context))
193 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
194 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
195 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
196 return CI->getArgOperand(0);
201 Value *LibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
202 Function *Callee = CI->getCalledFunction();
203 StringRef Name = Callee->getName();
204 FunctionType *FT = Callee->getFunctionType();
205 LLVMContext &Context = CI->getContext();
207 // Check if this has the right signature.
208 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
209 FT->getParamType(0) != FT->getParamType(1) ||
210 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
211 FT->getParamType(2) != DL->getIntPtrType(Context))
214 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
215 if (Dst == Src) // __strcpy_chk(x,x) -> x
218 // If a) we don't have any length information, or b) we know this will
219 // fit then just lower to a plain strcpy. Otherwise we'll keep our
220 // strcpy_chk call which may fail at runtime if the size is too long.
221 // TODO: It might be nice to get a maximum length out of the possible
222 // string lengths for varying.
223 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
224 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
227 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
228 uint64_t Len = GetStringLength(Src);
232 // This optimization require DataLayout.
236 Value *Ret = EmitMemCpyChk(
237 Dst, Src, ConstantInt::get(DL->getIntPtrType(Context), Len),
238 CI->getArgOperand(2), B, DL, TLI);
244 Value *LibCallSimplifier::optimizeStpCpyChk(CallInst *CI, IRBuilder<> &B) {
245 Function *Callee = CI->getCalledFunction();
246 StringRef Name = Callee->getName();
247 FunctionType *FT = Callee->getFunctionType();
248 LLVMContext &Context = CI->getContext();
250 // Check if this has the right signature.
251 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
252 FT->getParamType(0) != FT->getParamType(1) ||
253 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
254 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
257 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
258 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
259 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
260 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
263 // If a) we don't have any length information, or b) we know this will
264 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
265 // stpcpy_chk call which may fail at runtime if the size is too long.
266 // TODO: It might be nice to get a maximum length out of the possible
267 // string lengths for varying.
268 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
269 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
272 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
273 uint64_t Len = GetStringLength(Src);
277 // This optimization require DataLayout.
281 Type *PT = FT->getParamType(0);
282 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
284 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
285 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
292 Value *LibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
293 Function *Callee = CI->getCalledFunction();
294 StringRef Name = Callee->getName();
295 FunctionType *FT = Callee->getFunctionType();
296 LLVMContext &Context = CI->getContext();
298 // Check if this has the right signature.
299 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
300 FT->getParamType(0) != FT->getParamType(1) ||
301 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
302 !FT->getParamType(2)->isIntegerTy() ||
303 FT->getParamType(3) != DL->getIntPtrType(Context))
306 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
308 EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
309 CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
315 //===----------------------------------------------------------------------===//
316 // String and Memory Library Call Optimizations
317 //===----------------------------------------------------------------------===//
319 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
320 Function *Callee = CI->getCalledFunction();
321 // Verify the "strcat" function prototype.
322 FunctionType *FT = Callee->getFunctionType();
323 if (FT->getNumParams() != 2||
324 FT->getReturnType() != B.getInt8PtrTy() ||
325 FT->getParamType(0) != FT->getReturnType() ||
326 FT->getParamType(1) != FT->getReturnType())
329 // Extract some information from the instruction
330 Value *Dst = CI->getArgOperand(0);
331 Value *Src = CI->getArgOperand(1);
333 // See if we can get the length of the input string.
334 uint64_t Len = GetStringLength(Src);
337 --Len; // Unbias length.
339 // Handle the simple, do-nothing case: strcat(x, "") -> x
343 // These optimizations require DataLayout.
347 return emitStrLenMemCpy(Src, Dst, Len, B);
350 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
352 // We need to find the end of the destination string. That's where the
353 // memory is to be moved to. We just generate a call to strlen.
354 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
358 // Now that we have the destination's length, we must index into the
359 // destination's pointer to get the actual memcpy destination (end of
360 // the string .. we're concatenating).
361 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
363 // We have enough information to now generate the memcpy call to do the
364 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
367 ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
371 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
372 Function *Callee = CI->getCalledFunction();
373 // Verify the "strncat" function prototype.
374 FunctionType *FT = Callee->getFunctionType();
375 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
376 FT->getParamType(0) != FT->getReturnType() ||
377 FT->getParamType(1) != FT->getReturnType() ||
378 !FT->getParamType(2)->isIntegerTy())
381 // Extract some information from the instruction
382 Value *Dst = CI->getArgOperand(0);
383 Value *Src = CI->getArgOperand(1);
386 // We don't do anything if length is not constant
387 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
388 Len = LengthArg->getZExtValue();
392 // See if we can get the length of the input string.
393 uint64_t SrcLen = GetStringLength(Src);
396 --SrcLen; // Unbias length.
398 // Handle the simple, do-nothing cases:
399 // strncat(x, "", c) -> x
400 // strncat(x, c, 0) -> x
401 if (SrcLen == 0 || Len == 0)
404 // These optimizations require DataLayout.
408 // We don't optimize this case
412 // strncat(x, s, c) -> strcat(x, s)
413 // s is constant so the strcat can be optimized further
414 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
417 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
418 Function *Callee = CI->getCalledFunction();
419 // Verify the "strchr" function prototype.
420 FunctionType *FT = Callee->getFunctionType();
421 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
422 FT->getParamType(0) != FT->getReturnType() ||
423 !FT->getParamType(1)->isIntegerTy(32))
426 Value *SrcStr = CI->getArgOperand(0);
428 // If the second operand is non-constant, see if we can compute the length
429 // of the input string and turn this into memchr.
430 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
432 // These optimizations require DataLayout.
436 uint64_t Len = GetStringLength(SrcStr);
437 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
441 SrcStr, CI->getArgOperand(1), // include nul.
442 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
445 // Otherwise, the character is a constant, see if the first argument is
446 // a string literal. If so, we can constant fold.
448 if (!getConstantStringInfo(SrcStr, Str)) {
449 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
450 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
454 // Compute the offset, make sure to handle the case when we're searching for
455 // zero (a weird way to spell strlen).
456 size_t I = (0xFF & CharC->getSExtValue()) == 0
458 : Str.find(CharC->getSExtValue());
459 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
460 return Constant::getNullValue(CI->getType());
462 // strchr(s+n,c) -> gep(s+n+i,c)
463 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
466 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
467 Function *Callee = CI->getCalledFunction();
468 // Verify the "strrchr" function prototype.
469 FunctionType *FT = Callee->getFunctionType();
470 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
471 FT->getParamType(0) != FT->getReturnType() ||
472 !FT->getParamType(1)->isIntegerTy(32))
475 Value *SrcStr = CI->getArgOperand(0);
476 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
478 // Cannot fold anything if we're not looking for a constant.
483 if (!getConstantStringInfo(SrcStr, Str)) {
484 // strrchr(s, 0) -> strchr(s, 0)
485 if (DL && CharC->isZero())
486 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
490 // Compute the offset.
491 size_t I = (0xFF & CharC->getSExtValue()) == 0
493 : Str.rfind(CharC->getSExtValue());
494 if (I == StringRef::npos) // Didn't find the char. Return null.
495 return Constant::getNullValue(CI->getType());
497 // strrchr(s+n,c) -> gep(s+n+i,c)
498 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
501 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
502 Function *Callee = CI->getCalledFunction();
503 // Verify the "strcmp" function prototype.
504 FunctionType *FT = Callee->getFunctionType();
505 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
506 FT->getParamType(0) != FT->getParamType(1) ||
507 FT->getParamType(0) != B.getInt8PtrTy())
510 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
511 if (Str1P == Str2P) // strcmp(x,x) -> 0
512 return ConstantInt::get(CI->getType(), 0);
514 StringRef Str1, Str2;
515 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
516 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
518 // strcmp(x, y) -> cnst (if both x and y are constant strings)
519 if (HasStr1 && HasStr2)
520 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
522 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
524 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
526 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
527 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
529 // strcmp(P, "x") -> memcmp(P, "x", 2)
530 uint64_t Len1 = GetStringLength(Str1P);
531 uint64_t Len2 = GetStringLength(Str2P);
533 // These optimizations require DataLayout.
537 return EmitMemCmp(Str1P, Str2P,
538 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
539 std::min(Len1, Len2)),
546 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
547 Function *Callee = CI->getCalledFunction();
548 // Verify the "strncmp" function prototype.
549 FunctionType *FT = Callee->getFunctionType();
550 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
551 FT->getParamType(0) != FT->getParamType(1) ||
552 FT->getParamType(0) != B.getInt8PtrTy() ||
553 !FT->getParamType(2)->isIntegerTy())
556 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
557 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
558 return ConstantInt::get(CI->getType(), 0);
560 // Get the length argument if it is constant.
562 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
563 Length = LengthArg->getZExtValue();
567 if (Length == 0) // strncmp(x,y,0) -> 0
568 return ConstantInt::get(CI->getType(), 0);
570 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
571 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
573 StringRef Str1, Str2;
574 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
575 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
577 // strncmp(x, y) -> cnst (if both x and y are constant strings)
578 if (HasStr1 && HasStr2) {
579 StringRef SubStr1 = Str1.substr(0, Length);
580 StringRef SubStr2 = Str2.substr(0, Length);
581 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
584 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
586 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
588 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
589 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
594 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
595 Function *Callee = CI->getCalledFunction();
596 // Verify the "strcpy" function prototype.
597 FunctionType *FT = Callee->getFunctionType();
598 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
599 FT->getParamType(0) != FT->getParamType(1) ||
600 FT->getParamType(0) != B.getInt8PtrTy())
603 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
604 if (Dst == Src) // strcpy(x,x) -> x
607 // These optimizations require DataLayout.
611 // See if we can get the length of the input string.
612 uint64_t Len = GetStringLength(Src);
616 // We have enough information to now generate the memcpy call to do the
617 // copy for us. Make a memcpy to copy the nul byte with align = 1.
618 B.CreateMemCpy(Dst, Src,
619 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
623 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
624 Function *Callee = CI->getCalledFunction();
625 // Verify the "stpcpy" function prototype.
626 FunctionType *FT = Callee->getFunctionType();
627 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
628 FT->getParamType(0) != FT->getParamType(1) ||
629 FT->getParamType(0) != B.getInt8PtrTy())
632 // These optimizations require DataLayout.
636 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
637 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
638 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
639 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
642 // See if we can get the length of the input string.
643 uint64_t Len = GetStringLength(Src);
647 Type *PT = FT->getParamType(0);
648 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
650 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
652 // We have enough information to now generate the memcpy call to do the
653 // copy for us. Make a memcpy to copy the nul byte with align = 1.
654 B.CreateMemCpy(Dst, Src, LenV, 1);
658 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
659 Function *Callee = CI->getCalledFunction();
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
662 FT->getParamType(0) != FT->getParamType(1) ||
663 FT->getParamType(0) != B.getInt8PtrTy() ||
664 !FT->getParamType(2)->isIntegerTy())
667 Value *Dst = CI->getArgOperand(0);
668 Value *Src = CI->getArgOperand(1);
669 Value *LenOp = CI->getArgOperand(2);
671 // See if we can get the length of the input string.
672 uint64_t SrcLen = GetStringLength(Src);
678 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
679 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
684 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
685 Len = LengthArg->getZExtValue();
690 return Dst; // strncpy(x, y, 0) -> x
692 // These optimizations require DataLayout.
696 // Let strncpy handle the zero padding
697 if (Len > SrcLen + 1)
700 Type *PT = FT->getParamType(0);
701 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
702 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
707 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
708 Function *Callee = CI->getCalledFunction();
709 FunctionType *FT = Callee->getFunctionType();
710 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
711 !FT->getReturnType()->isIntegerTy())
714 Value *Src = CI->getArgOperand(0);
716 // Constant folding: strlen("xyz") -> 3
717 if (uint64_t Len = GetStringLength(Src))
718 return ConstantInt::get(CI->getType(), Len - 1);
720 // strlen(x?"foo":"bars") --> x ? 3 : 4
721 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
722 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
723 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
724 if (LenTrue && LenFalse) {
725 Function *Caller = CI->getParent()->getParent();
726 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
728 "folded strlen(select) to select of constants");
729 return B.CreateSelect(SI->getCondition(),
730 ConstantInt::get(CI->getType(), LenTrue - 1),
731 ConstantInt::get(CI->getType(), LenFalse - 1));
735 // strlen(x) != 0 --> *x != 0
736 // strlen(x) == 0 --> *x == 0
737 if (isOnlyUsedInZeroEqualityComparison(CI))
738 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
743 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
744 Function *Callee = CI->getCalledFunction();
745 FunctionType *FT = Callee->getFunctionType();
746 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
747 FT->getParamType(1) != FT->getParamType(0) ||
748 FT->getReturnType() != FT->getParamType(0))
752 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
753 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
755 // strpbrk(s, "") -> NULL
756 // strpbrk("", s) -> NULL
757 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
758 return Constant::getNullValue(CI->getType());
761 if (HasS1 && HasS2) {
762 size_t I = S1.find_first_of(S2);
763 if (I == StringRef::npos) // No match.
764 return Constant::getNullValue(CI->getType());
766 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
769 // strpbrk(s, "a") -> strchr(s, 'a')
770 if (DL && HasS2 && S2.size() == 1)
771 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
776 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
777 Function *Callee = CI->getCalledFunction();
778 FunctionType *FT = Callee->getFunctionType();
779 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
780 !FT->getParamType(0)->isPointerTy() ||
781 !FT->getParamType(1)->isPointerTy())
784 Value *EndPtr = CI->getArgOperand(1);
785 if (isa<ConstantPointerNull>(EndPtr)) {
786 // With a null EndPtr, this function won't capture the main argument.
787 // It would be readonly too, except that it still may write to errno.
788 CI->addAttribute(1, Attribute::NoCapture);
794 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
795 Function *Callee = CI->getCalledFunction();
796 FunctionType *FT = Callee->getFunctionType();
797 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
798 FT->getParamType(1) != FT->getParamType(0) ||
799 !FT->getReturnType()->isIntegerTy())
803 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
804 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
806 // strspn(s, "") -> 0
807 // strspn("", s) -> 0
808 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
809 return Constant::getNullValue(CI->getType());
812 if (HasS1 && HasS2) {
813 size_t Pos = S1.find_first_not_of(S2);
814 if (Pos == StringRef::npos)
816 return ConstantInt::get(CI->getType(), Pos);
822 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
823 Function *Callee = CI->getCalledFunction();
824 FunctionType *FT = Callee->getFunctionType();
825 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
826 FT->getParamType(1) != FT->getParamType(0) ||
827 !FT->getReturnType()->isIntegerTy())
831 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
832 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
834 // strcspn("", s) -> 0
835 if (HasS1 && S1.empty())
836 return Constant::getNullValue(CI->getType());
839 if (HasS1 && HasS2) {
840 size_t Pos = S1.find_first_of(S2);
841 if (Pos == StringRef::npos)
843 return ConstantInt::get(CI->getType(), Pos);
846 // strcspn(s, "") -> strlen(s)
847 if (DL && HasS2 && S2.empty())
848 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
853 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
854 Function *Callee = CI->getCalledFunction();
855 FunctionType *FT = Callee->getFunctionType();
856 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
857 !FT->getParamType(1)->isPointerTy() ||
858 !FT->getReturnType()->isPointerTy())
861 // fold strstr(x, x) -> x.
862 if (CI->getArgOperand(0) == CI->getArgOperand(1))
863 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
865 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
866 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
867 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
870 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
874 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
875 ICmpInst *Old = cast<ICmpInst>(*UI++);
877 B.CreateICmp(Old->getPredicate(), StrNCmp,
878 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
879 replaceAllUsesWith(Old, Cmp);
884 // See if either input string is a constant string.
885 StringRef SearchStr, ToFindStr;
886 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
887 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
889 // fold strstr(x, "") -> x.
890 if (HasStr2 && ToFindStr.empty())
891 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
893 // If both strings are known, constant fold it.
894 if (HasStr1 && HasStr2) {
895 size_t Offset = SearchStr.find(ToFindStr);
897 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
898 return Constant::getNullValue(CI->getType());
900 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
901 Value *Result = CastToCStr(CI->getArgOperand(0), B);
902 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
903 return B.CreateBitCast(Result, CI->getType());
906 // fold strstr(x, "y") -> strchr(x, 'y').
907 if (HasStr2 && ToFindStr.size() == 1) {
908 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
909 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
914 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
915 Function *Callee = CI->getCalledFunction();
916 FunctionType *FT = Callee->getFunctionType();
917 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
918 !FT->getParamType(1)->isPointerTy() ||
919 !FT->getReturnType()->isIntegerTy(32))
922 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
924 if (LHS == RHS) // memcmp(s,s,x) -> 0
925 return Constant::getNullValue(CI->getType());
927 // Make sure we have a constant length.
928 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
931 uint64_t Len = LenC->getZExtValue();
933 if (Len == 0) // memcmp(s1,s2,0) -> 0
934 return Constant::getNullValue(CI->getType());
936 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
938 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
939 CI->getType(), "lhsv");
940 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
941 CI->getType(), "rhsv");
942 return B.CreateSub(LHSV, RHSV, "chardiff");
945 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
946 StringRef LHSStr, RHSStr;
947 if (getConstantStringInfo(LHS, LHSStr) &&
948 getConstantStringInfo(RHS, RHSStr)) {
949 // Make sure we're not reading out-of-bounds memory.
950 if (Len > LHSStr.size() || Len > RHSStr.size())
952 // Fold the memcmp and normalize the result. This way we get consistent
953 // results across multiple platforms.
955 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
960 return ConstantInt::get(CI->getType(), Ret);
966 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
967 Function *Callee = CI->getCalledFunction();
968 // These optimizations require DataLayout.
972 FunctionType *FT = Callee->getFunctionType();
973 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
974 !FT->getParamType(0)->isPointerTy() ||
975 !FT->getParamType(1)->isPointerTy() ||
976 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
979 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
980 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
981 CI->getArgOperand(2), 1);
982 return CI->getArgOperand(0);
985 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
986 Function *Callee = CI->getCalledFunction();
987 // These optimizations require DataLayout.
991 FunctionType *FT = Callee->getFunctionType();
992 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
993 !FT->getParamType(0)->isPointerTy() ||
994 !FT->getParamType(1)->isPointerTy() ||
995 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
998 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
999 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1000 CI->getArgOperand(2), 1);
1001 return CI->getArgOperand(0);
1004 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1005 Function *Callee = CI->getCalledFunction();
1006 // These optimizations require DataLayout.
1010 FunctionType *FT = Callee->getFunctionType();
1011 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1012 !FT->getParamType(0)->isPointerTy() ||
1013 !FT->getParamType(1)->isIntegerTy() ||
1014 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
1017 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1018 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1019 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1020 return CI->getArgOperand(0);
1023 //===----------------------------------------------------------------------===//
1024 // Math Library Optimizations
1025 //===----------------------------------------------------------------------===//
1027 //===----------------------------------------------------------------------===//
1028 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1030 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1031 bool CheckRetType) {
1032 Function *Callee = CI->getCalledFunction();
1033 FunctionType *FT = Callee->getFunctionType();
1034 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1035 !FT->getParamType(0)->isDoubleTy())
1039 // Check if all the uses for function like 'sin' are converted to float.
1040 for (User *U : CI->users()) {
1041 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1042 if (!Cast || !Cast->getType()->isFloatTy())
1047 // If this is something like 'floor((double)floatval)', convert to floorf.
1048 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1049 if (!Cast || !Cast->getOperand(0)->getType()->isFloatTy())
1052 // floor((double)floatval) -> (double)floorf(floatval)
1053 Value *V = Cast->getOperand(0);
1054 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1055 return B.CreateFPExt(V, B.getDoubleTy());
1058 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1059 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1060 Function *Callee = CI->getCalledFunction();
1061 FunctionType *FT = Callee->getFunctionType();
1062 // Just make sure this has 2 arguments of the same FP type, which match the
1064 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1065 FT->getParamType(0) != FT->getParamType(1) ||
1066 !FT->getParamType(0)->isFloatingPointTy())
1069 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1070 // we convert it to fminf.
1071 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1072 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1073 if (!Cast1 || !Cast1->getOperand(0)->getType()->isFloatTy() || !Cast2 ||
1074 !Cast2->getOperand(0)->getType()->isFloatTy())
1077 // fmin((double)floatval1, (double)floatval2)
1078 // -> (double)fmin(floatval1, floatval2)
1080 Value *V1 = Cast1->getOperand(0);
1081 Value *V2 = Cast2->getOperand(0);
1082 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1083 Callee->getAttributes());
1084 return B.CreateFPExt(V, B.getDoubleTy());
1087 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1088 Function *Callee = CI->getCalledFunction();
1089 Value *Ret = nullptr;
1090 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1091 Ret = optimizeUnaryDoubleFP(CI, B, true);
1094 FunctionType *FT = Callee->getFunctionType();
1095 // Just make sure this has 1 argument of FP type, which matches the
1097 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1098 !FT->getParamType(0)->isFloatingPointTy())
1101 // cos(-x) -> cos(x)
1102 Value *Op1 = CI->getArgOperand(0);
1103 if (BinaryOperator::isFNeg(Op1)) {
1104 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1105 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1110 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1111 Function *Callee = CI->getCalledFunction();
1113 Value *Ret = nullptr;
1114 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1115 Ret = optimizeUnaryDoubleFP(CI, B, true);
1118 FunctionType *FT = Callee->getFunctionType();
1119 // Just make sure this has 2 arguments of the same FP type, which match the
1121 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1122 FT->getParamType(0) != FT->getParamType(1) ||
1123 !FT->getParamType(0)->isFloatingPointTy())
1126 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1127 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1128 // pow(1.0, x) -> 1.0
1129 if (Op1C->isExactlyValue(1.0))
1131 // pow(2.0, x) -> exp2(x)
1132 if (Op1C->isExactlyValue(2.0) &&
1133 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1135 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1136 // pow(10.0, x) -> exp10(x)
1137 if (Op1C->isExactlyValue(10.0) &&
1138 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1140 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1141 Callee->getAttributes());
1144 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1148 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1149 return ConstantFP::get(CI->getType(), 1.0);
1151 if (Op2C->isExactlyValue(0.5) &&
1152 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1154 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1156 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1157 // This is faster than calling pow, and still handles negative zero
1158 // and negative infinity correctly.
1159 // TODO: In fast-math mode, this could be just sqrt(x).
1160 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1161 Value *Inf = ConstantFP::getInfinity(CI->getType());
1162 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1163 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1165 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1166 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1167 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1171 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1173 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1174 return B.CreateFMul(Op1, Op1, "pow2");
1175 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1176 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1180 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1181 Function *Callee = CI->getCalledFunction();
1182 Function *Caller = CI->getParent()->getParent();
1184 Value *Ret = nullptr;
1185 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1186 TLI->has(LibFunc::exp2f)) {
1187 Ret = optimizeUnaryDoubleFP(CI, B, true);
1190 FunctionType *FT = Callee->getFunctionType();
1191 // Just make sure this has 1 argument of FP type, which matches the
1193 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1194 !FT->getParamType(0)->isFloatingPointTy())
1197 Value *Op = CI->getArgOperand(0);
1198 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1199 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1200 LibFunc::Func LdExp = LibFunc::ldexpl;
1201 if (Op->getType()->isFloatTy())
1202 LdExp = LibFunc::ldexpf;
1203 else if (Op->getType()->isDoubleTy())
1204 LdExp = LibFunc::ldexp;
1206 if (TLI->has(LdExp)) {
1207 Value *LdExpArg = nullptr;
1208 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1209 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1210 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1211 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1212 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1213 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1217 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1218 if (!Op->getType()->isFloatTy())
1219 One = ConstantExpr::getFPExtend(One, Op->getType());
1221 Module *M = Caller->getParent();
1223 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1224 Op->getType(), B.getInt32Ty(), NULL);
1225 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1226 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1227 CI->setCallingConv(F->getCallingConv());
1235 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1236 Function *Callee = CI->getCalledFunction();
1238 Value *Ret = nullptr;
1239 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1240 Ret = optimizeUnaryDoubleFP(CI, B, false);
1243 FunctionType *FT = Callee->getFunctionType();
1244 // Make sure this has 1 argument of FP type which matches the result type.
1245 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1246 !FT->getParamType(0)->isFloatingPointTy())
1249 Value *Op = CI->getArgOperand(0);
1250 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1251 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1252 if (I->getOpcode() == Instruction::FMul)
1253 if (I->getOperand(0) == I->getOperand(1))
1259 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1260 Function *Callee = CI->getCalledFunction();
1262 Value *Ret = nullptr;
1263 if (UnsafeFPShrink && Callee->getName() == "sqrt" &&
1264 TLI->has(LibFunc::sqrtf)) {
1265 Ret = optimizeUnaryDoubleFP(CI, B, true);
1268 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1269 // fast-math flag decorations that are applied to FP instructions. For now,
1270 // we have to rely on the function-level unsafe-fp-math attribute to do this
1271 // optimization because there's no other way to express that the sqrt can be
1273 Function *F = CI->getParent()->getParent();
1274 if (F->hasFnAttribute("unsafe-fp-math")) {
1275 // Check for unsafe-fp-math = true.
1276 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1277 if (Attr.getValueAsString() != "true")
1280 Value *Op = CI->getArgOperand(0);
1281 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1282 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1283 // We're looking for a repeated factor in a multiplication tree,
1284 // so we can do this fold: sqrt(x * x) -> fabs(x);
1285 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1286 Value *Op0 = I->getOperand(0);
1287 Value *Op1 = I->getOperand(1);
1288 Value *RepeatOp = nullptr;
1289 Value *OtherOp = nullptr;
1291 // Simple match: the operands of the multiply are identical.
1294 // Look for a more complicated pattern: one of the operands is itself
1295 // a multiply, so search for a common factor in that multiply.
1296 // Note: We don't bother looking any deeper than this first level or for
1297 // variations of this pattern because instcombine's visitFMUL and/or the
1298 // reassociation pass should give us this form.
1299 Value *OtherMul0, *OtherMul1;
1300 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1301 // Pattern: sqrt((x * y) * z)
1302 if (OtherMul0 == OtherMul1) {
1303 // Matched: sqrt((x * x) * z)
1304 RepeatOp = OtherMul0;
1310 // Fast math flags for any created instructions should match the sqrt
1312 // FIXME: We're not checking the sqrt because it doesn't have
1313 // fast-math-flags (see earlier comment).
1314 IRBuilder<true, ConstantFolder,
1315 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1316 B.SetFastMathFlags(I->getFastMathFlags());
1317 // If we found a repeated factor, hoist it out of the square root and
1318 // replace it with the fabs of that factor.
1319 Module *M = Callee->getParent();
1320 Type *ArgType = Op->getType();
1321 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1322 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1324 // If we found a non-repeated factor, we still need to get its square
1325 // root. We then multiply that by the value that was simplified out
1326 // of the square root calculation.
1327 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1328 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1329 return B.CreateFMul(FabsCall, SqrtCall);
1338 static bool isTrigLibCall(CallInst *CI);
1339 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1340 bool UseFloat, Value *&Sin, Value *&Cos,
1343 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1345 // Make sure the prototype is as expected, otherwise the rest of the
1346 // function is probably invalid and likely to abort.
1347 if (!isTrigLibCall(CI))
1350 Value *Arg = CI->getArgOperand(0);
1351 SmallVector<CallInst *, 1> SinCalls;
1352 SmallVector<CallInst *, 1> CosCalls;
1353 SmallVector<CallInst *, 1> SinCosCalls;
1355 bool IsFloat = Arg->getType()->isFloatTy();
1357 // Look for all compatible sinpi, cospi and sincospi calls with the same
1358 // argument. If there are enough (in some sense) we can make the
1360 for (User *U : Arg->users())
1361 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1364 // It's only worthwhile if both sinpi and cospi are actually used.
1365 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1368 Value *Sin, *Cos, *SinCos;
1369 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1371 replaceTrigInsts(SinCalls, Sin);
1372 replaceTrigInsts(CosCalls, Cos);
1373 replaceTrigInsts(SinCosCalls, SinCos);
1378 static bool isTrigLibCall(CallInst *CI) {
1379 Function *Callee = CI->getCalledFunction();
1380 FunctionType *FT = Callee->getFunctionType();
1382 // We can only hope to do anything useful if we can ignore things like errno
1383 // and floating-point exceptions.
1384 bool AttributesSafe =
1385 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1387 // Other than that we need float(float) or double(double)
1388 return AttributesSafe && FT->getNumParams() == 1 &&
1389 FT->getReturnType() == FT->getParamType(0) &&
1390 (FT->getParamType(0)->isFloatTy() ||
1391 FT->getParamType(0)->isDoubleTy());
1395 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1396 SmallVectorImpl<CallInst *> &SinCalls,
1397 SmallVectorImpl<CallInst *> &CosCalls,
1398 SmallVectorImpl<CallInst *> &SinCosCalls) {
1399 CallInst *CI = dyn_cast<CallInst>(Val);
1404 Function *Callee = CI->getCalledFunction();
1405 StringRef FuncName = Callee->getName();
1407 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1411 if (Func == LibFunc::sinpif)
1412 SinCalls.push_back(CI);
1413 else if (Func == LibFunc::cospif)
1414 CosCalls.push_back(CI);
1415 else if (Func == LibFunc::sincospif_stret)
1416 SinCosCalls.push_back(CI);
1418 if (Func == LibFunc::sinpi)
1419 SinCalls.push_back(CI);
1420 else if (Func == LibFunc::cospi)
1421 CosCalls.push_back(CI);
1422 else if (Func == LibFunc::sincospi_stret)
1423 SinCosCalls.push_back(CI);
1427 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1429 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1431 replaceAllUsesWith(*I, Res);
1435 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1436 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1437 Type *ArgTy = Arg->getType();
1441 Triple T(OrigCallee->getParent()->getTargetTriple());
1443 Name = "__sincospif_stret";
1445 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1446 // x86_64 can't use {float, float} since that would be returned in both
1447 // xmm0 and xmm1, which isn't what a real struct would do.
1448 ResTy = T.getArch() == Triple::x86_64
1449 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1450 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1452 Name = "__sincospi_stret";
1453 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1456 Module *M = OrigCallee->getParent();
1457 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1458 ResTy, ArgTy, NULL);
1460 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1461 // If the argument is an instruction, it must dominate all uses so put our
1462 // sincos call there.
1463 BasicBlock::iterator Loc = ArgInst;
1464 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1466 // Otherwise (e.g. for a constant) the beginning of the function is as
1467 // good a place as any.
1468 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1469 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1472 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1474 if (SinCos->getType()->isStructTy()) {
1475 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1476 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1478 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1480 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1485 //===----------------------------------------------------------------------===//
1486 // Integer Library Call Optimizations
1487 //===----------------------------------------------------------------------===//
1489 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1490 Function *Callee = CI->getCalledFunction();
1491 FunctionType *FT = Callee->getFunctionType();
1492 // Just make sure this has 2 arguments of the same FP type, which match the
1494 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1495 !FT->getParamType(0)->isIntegerTy())
1498 Value *Op = CI->getArgOperand(0);
1501 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1502 if (CI->isZero()) // ffs(0) -> 0.
1503 return B.getInt32(0);
1504 // ffs(c) -> cttz(c)+1
1505 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1508 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1509 Type *ArgType = Op->getType();
1511 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1512 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1513 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1514 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1516 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1517 return B.CreateSelect(Cond, V, B.getInt32(0));
1520 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1521 Function *Callee = CI->getCalledFunction();
1522 FunctionType *FT = Callee->getFunctionType();
1523 // We require integer(integer) where the types agree.
1524 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1525 FT->getParamType(0) != FT->getReturnType())
1528 // abs(x) -> x >s -1 ? x : -x
1529 Value *Op = CI->getArgOperand(0);
1531 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1532 Value *Neg = B.CreateNeg(Op, "neg");
1533 return B.CreateSelect(Pos, Op, Neg);
1536 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1537 Function *Callee = CI->getCalledFunction();
1538 FunctionType *FT = Callee->getFunctionType();
1539 // We require integer(i32)
1540 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1541 !FT->getParamType(0)->isIntegerTy(32))
1544 // isdigit(c) -> (c-'0') <u 10
1545 Value *Op = CI->getArgOperand(0);
1546 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1547 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1548 return B.CreateZExt(Op, CI->getType());
1551 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1552 Function *Callee = CI->getCalledFunction();
1553 FunctionType *FT = Callee->getFunctionType();
1554 // We require integer(i32)
1555 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1556 !FT->getParamType(0)->isIntegerTy(32))
1559 // isascii(c) -> c <u 128
1560 Value *Op = CI->getArgOperand(0);
1561 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1562 return B.CreateZExt(Op, CI->getType());
1565 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1566 Function *Callee = CI->getCalledFunction();
1567 FunctionType *FT = Callee->getFunctionType();
1568 // We require i32(i32)
1569 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1570 !FT->getParamType(0)->isIntegerTy(32))
1573 // toascii(c) -> c & 0x7f
1574 return B.CreateAnd(CI->getArgOperand(0),
1575 ConstantInt::get(CI->getType(), 0x7F));
1578 //===----------------------------------------------------------------------===//
1579 // Formatting and IO Library Call Optimizations
1580 //===----------------------------------------------------------------------===//
1582 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1584 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1586 // Error reporting calls should be cold, mark them as such.
1587 // This applies even to non-builtin calls: it is only a hint and applies to
1588 // functions that the frontend might not understand as builtins.
1590 // This heuristic was suggested in:
1591 // Improving Static Branch Prediction in a Compiler
1592 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1593 // Proceedings of PACT'98, Oct. 1998, IEEE
1594 Function *Callee = CI->getCalledFunction();
1596 if (!CI->hasFnAttr(Attribute::Cold) &&
1597 isReportingError(Callee, CI, StreamArg)) {
1598 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1604 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1605 if (!ColdErrorCalls)
1608 if (!Callee || !Callee->isDeclaration())
1614 // These functions might be considered cold, but only if their stream
1615 // argument is stderr.
1617 if (StreamArg >= (int)CI->getNumArgOperands())
1619 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1622 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1623 if (!GV || !GV->isDeclaration())
1625 return GV->getName() == "stderr";
1628 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1629 // Check for a fixed format string.
1630 StringRef FormatStr;
1631 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1634 // Empty format string -> noop.
1635 if (FormatStr.empty()) // Tolerate printf's declared void.
1636 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1638 // Do not do any of the following transformations if the printf return value
1639 // is used, in general the printf return value is not compatible with either
1640 // putchar() or puts().
1641 if (!CI->use_empty())
1644 // printf("x") -> putchar('x'), even for '%'.
1645 if (FormatStr.size() == 1) {
1646 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1647 if (CI->use_empty() || !Res)
1649 return B.CreateIntCast(Res, CI->getType(), true);
1652 // printf("foo\n") --> puts("foo")
1653 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1654 FormatStr.find('%') == StringRef::npos) { // No format characters.
1655 // Create a string literal with no \n on it. We expect the constant merge
1656 // pass to be run after this pass, to merge duplicate strings.
1657 FormatStr = FormatStr.drop_back();
1658 Value *GV = B.CreateGlobalString(FormatStr, "str");
1659 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1660 return (CI->use_empty() || !NewCI)
1662 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1665 // Optimize specific format strings.
1666 // printf("%c", chr) --> putchar(chr)
1667 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1668 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1669 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1671 if (CI->use_empty() || !Res)
1673 return B.CreateIntCast(Res, CI->getType(), true);
1676 // printf("%s\n", str) --> puts(str)
1677 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1678 CI->getArgOperand(1)->getType()->isPointerTy()) {
1679 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1684 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1686 Function *Callee = CI->getCalledFunction();
1687 // Require one fixed pointer argument and an integer/void result.
1688 FunctionType *FT = Callee->getFunctionType();
1689 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1690 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1693 if (Value *V = optimizePrintFString(CI, B)) {
1697 // printf(format, ...) -> iprintf(format, ...) if no floating point
1699 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1700 Module *M = B.GetInsertBlock()->getParent()->getParent();
1701 Constant *IPrintFFn =
1702 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1703 CallInst *New = cast<CallInst>(CI->clone());
1704 New->setCalledFunction(IPrintFFn);
1711 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1712 // Check for a fixed format string.
1713 StringRef FormatStr;
1714 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1717 // If we just have a format string (nothing else crazy) transform it.
1718 if (CI->getNumArgOperands() == 2) {
1719 // Make sure there's no % in the constant array. We could try to handle
1720 // %% -> % in the future if we cared.
1721 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1722 if (FormatStr[i] == '%')
1723 return nullptr; // we found a format specifier, bail out.
1725 // These optimizations require DataLayout.
1729 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1731 CI->getArgOperand(0), CI->getArgOperand(1),
1732 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1733 FormatStr.size() + 1),
1734 1); // Copy the null byte.
1735 return ConstantInt::get(CI->getType(), FormatStr.size());
1738 // The remaining optimizations require the format string to be "%s" or "%c"
1739 // and have an extra operand.
1740 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1741 CI->getNumArgOperands() < 3)
1744 // Decode the second character of the format string.
1745 if (FormatStr[1] == 'c') {
1746 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1747 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1749 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1750 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1751 B.CreateStore(V, Ptr);
1752 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1753 B.CreateStore(B.getInt8(0), Ptr);
1755 return ConstantInt::get(CI->getType(), 1);
1758 if (FormatStr[1] == 's') {
1759 // These optimizations require DataLayout.
1763 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1764 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1767 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1771 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1772 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1774 // The sprintf result is the unincremented number of bytes in the string.
1775 return B.CreateIntCast(Len, CI->getType(), false);
1780 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1781 Function *Callee = CI->getCalledFunction();
1782 // Require two fixed pointer arguments and an integer result.
1783 FunctionType *FT = Callee->getFunctionType();
1784 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1785 !FT->getParamType(1)->isPointerTy() ||
1786 !FT->getReturnType()->isIntegerTy())
1789 if (Value *V = optimizeSPrintFString(CI, B)) {
1793 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1795 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1796 Module *M = B.GetInsertBlock()->getParent()->getParent();
1797 Constant *SIPrintFFn =
1798 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1799 CallInst *New = cast<CallInst>(CI->clone());
1800 New->setCalledFunction(SIPrintFFn);
1807 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1808 optimizeErrorReporting(CI, B, 0);
1810 // All the optimizations depend on the format string.
1811 StringRef FormatStr;
1812 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1815 // Do not do any of the following transformations if the fprintf return
1816 // value is used, in general the fprintf return value is not compatible
1817 // with fwrite(), fputc() or fputs().
1818 if (!CI->use_empty())
1821 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1822 if (CI->getNumArgOperands() == 2) {
1823 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1824 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1825 return nullptr; // We found a format specifier.
1827 // These optimizations require DataLayout.
1832 CI->getArgOperand(1),
1833 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1834 CI->getArgOperand(0), B, DL, TLI);
1837 // The remaining optimizations require the format string to be "%s" or "%c"
1838 // and have an extra operand.
1839 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1840 CI->getNumArgOperands() < 3)
1843 // Decode the second character of the format string.
1844 if (FormatStr[1] == 'c') {
1845 // fprintf(F, "%c", chr) --> fputc(chr, F)
1846 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1848 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1851 if (FormatStr[1] == 's') {
1852 // fprintf(F, "%s", str) --> fputs(str, F)
1853 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1855 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1860 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1861 Function *Callee = CI->getCalledFunction();
1862 // Require two fixed paramters as pointers and integer result.
1863 FunctionType *FT = Callee->getFunctionType();
1864 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1865 !FT->getParamType(1)->isPointerTy() ||
1866 !FT->getReturnType()->isIntegerTy())
1869 if (Value *V = optimizeFPrintFString(CI, B)) {
1873 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1874 // floating point arguments.
1875 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1876 Module *M = B.GetInsertBlock()->getParent()->getParent();
1877 Constant *FIPrintFFn =
1878 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1879 CallInst *New = cast<CallInst>(CI->clone());
1880 New->setCalledFunction(FIPrintFFn);
1887 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1888 optimizeErrorReporting(CI, B, 3);
1890 Function *Callee = CI->getCalledFunction();
1891 // Require a pointer, an integer, an integer, a pointer, returning integer.
1892 FunctionType *FT = Callee->getFunctionType();
1893 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1894 !FT->getParamType(1)->isIntegerTy() ||
1895 !FT->getParamType(2)->isIntegerTy() ||
1896 !FT->getParamType(3)->isPointerTy() ||
1897 !FT->getReturnType()->isIntegerTy())
1900 // Get the element size and count.
1901 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1902 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1903 if (!SizeC || !CountC)
1905 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1907 // If this is writing zero records, remove the call (it's a noop).
1909 return ConstantInt::get(CI->getType(), 0);
1911 // If this is writing one byte, turn it into fputc.
1912 // This optimisation is only valid, if the return value is unused.
1913 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1914 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1915 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1916 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1922 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1923 optimizeErrorReporting(CI, B, 1);
1925 Function *Callee = CI->getCalledFunction();
1927 // These optimizations require DataLayout.
1931 // Require two pointers. Also, we can't optimize if return value is used.
1932 FunctionType *FT = Callee->getFunctionType();
1933 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1934 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1937 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1938 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1942 // Known to have no uses (see above).
1944 CI->getArgOperand(0),
1945 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1946 CI->getArgOperand(1), B, DL, TLI);
1949 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1950 Function *Callee = CI->getCalledFunction();
1951 // Require one fixed pointer argument and an integer/void result.
1952 FunctionType *FT = Callee->getFunctionType();
1953 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1954 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1957 // Check for a constant string.
1959 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1962 if (Str.empty() && CI->use_empty()) {
1963 // puts("") -> putchar('\n')
1964 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
1965 if (CI->use_empty() || !Res)
1967 return B.CreateIntCast(Res, CI->getType(), true);
1973 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1975 SmallString<20> FloatFuncName = FuncName;
1976 FloatFuncName += 'f';
1977 if (TLI->getLibFunc(FloatFuncName, Func))
1978 return TLI->has(Func);
1982 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1983 if (CI->isNoBuiltin())
1987 Function *Callee = CI->getCalledFunction();
1988 StringRef FuncName = Callee->getName();
1989 IRBuilder<> Builder(CI);
1990 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1992 // Next check for intrinsics.
1993 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1994 if (!isCallingConvC)
1996 switch (II->getIntrinsicID()) {
1997 case Intrinsic::pow:
1998 return optimizePow(CI, Builder);
1999 case Intrinsic::exp2:
2000 return optimizeExp2(CI, Builder);
2001 case Intrinsic::fabs:
2002 return optimizeFabs(CI, Builder);
2003 case Intrinsic::sqrt:
2004 return optimizeSqrt(CI, Builder);
2010 // Then check for known library functions.
2011 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2012 // We never change the calling convention.
2013 if (!ignoreCallingConv(Func) && !isCallingConvC)
2016 case LibFunc::strcat:
2017 return optimizeStrCat(CI, Builder);
2018 case LibFunc::strncat:
2019 return optimizeStrNCat(CI, Builder);
2020 case LibFunc::strchr:
2021 return optimizeStrChr(CI, Builder);
2022 case LibFunc::strrchr:
2023 return optimizeStrRChr(CI, Builder);
2024 case LibFunc::strcmp:
2025 return optimizeStrCmp(CI, Builder);
2026 case LibFunc::strncmp:
2027 return optimizeStrNCmp(CI, Builder);
2028 case LibFunc::strcpy:
2029 return optimizeStrCpy(CI, Builder);
2030 case LibFunc::stpcpy:
2031 return optimizeStpCpy(CI, Builder);
2032 case LibFunc::strncpy:
2033 return optimizeStrNCpy(CI, Builder);
2034 case LibFunc::strlen:
2035 return optimizeStrLen(CI, Builder);
2036 case LibFunc::strpbrk:
2037 return optimizeStrPBrk(CI, Builder);
2038 case LibFunc::strtol:
2039 case LibFunc::strtod:
2040 case LibFunc::strtof:
2041 case LibFunc::strtoul:
2042 case LibFunc::strtoll:
2043 case LibFunc::strtold:
2044 case LibFunc::strtoull:
2045 return optimizeStrTo(CI, Builder);
2046 case LibFunc::strspn:
2047 return optimizeStrSpn(CI, Builder);
2048 case LibFunc::strcspn:
2049 return optimizeStrCSpn(CI, Builder);
2050 case LibFunc::strstr:
2051 return optimizeStrStr(CI, Builder);
2052 case LibFunc::memcmp:
2053 return optimizeMemCmp(CI, Builder);
2054 case LibFunc::memcpy:
2055 return optimizeMemCpy(CI, Builder);
2056 case LibFunc::memmove:
2057 return optimizeMemMove(CI, Builder);
2058 case LibFunc::memset:
2059 return optimizeMemSet(CI, Builder);
2063 return optimizeCos(CI, Builder);
2064 case LibFunc::sinpif:
2065 case LibFunc::sinpi:
2066 case LibFunc::cospif:
2067 case LibFunc::cospi:
2068 return optimizeSinCosPi(CI, Builder);
2072 return optimizePow(CI, Builder);
2073 case LibFunc::exp2l:
2075 case LibFunc::exp2f:
2076 return optimizeExp2(CI, Builder);
2077 case LibFunc::fabsf:
2079 case LibFunc::fabsl:
2080 return optimizeFabs(CI, Builder);
2081 case LibFunc::sqrtf:
2083 case LibFunc::sqrtl:
2084 return optimizeSqrt(CI, Builder);
2087 case LibFunc::ffsll:
2088 return optimizeFFS(CI, Builder);
2091 case LibFunc::llabs:
2092 return optimizeAbs(CI, Builder);
2093 case LibFunc::isdigit:
2094 return optimizeIsDigit(CI, Builder);
2095 case LibFunc::isascii:
2096 return optimizeIsAscii(CI, Builder);
2097 case LibFunc::toascii:
2098 return optimizeToAscii(CI, Builder);
2099 case LibFunc::printf:
2100 return optimizePrintF(CI, Builder);
2101 case LibFunc::sprintf:
2102 return optimizeSPrintF(CI, Builder);
2103 case LibFunc::fprintf:
2104 return optimizeFPrintF(CI, Builder);
2105 case LibFunc::fwrite:
2106 return optimizeFWrite(CI, Builder);
2107 case LibFunc::fputs:
2108 return optimizeFPuts(CI, Builder);
2110 return optimizePuts(CI, Builder);
2111 case LibFunc::perror:
2112 return optimizeErrorReporting(CI, Builder);
2113 case LibFunc::vfprintf:
2114 case LibFunc::fiprintf:
2115 return optimizeErrorReporting(CI, Builder, 0);
2116 case LibFunc::fputc:
2117 return optimizeErrorReporting(CI, Builder, 1);
2119 case LibFunc::floor:
2121 case LibFunc::round:
2122 case LibFunc::nearbyint:
2123 case LibFunc::trunc:
2124 if (hasFloatVersion(FuncName))
2125 return optimizeUnaryDoubleFP(CI, Builder, false);
2128 case LibFunc::acosh:
2130 case LibFunc::asinh:
2132 case LibFunc::atanh:
2136 case LibFunc::exp10:
2137 case LibFunc::expm1:
2139 case LibFunc::log10:
2140 case LibFunc::log1p:
2147 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2148 return optimizeUnaryDoubleFP(CI, Builder, true);
2152 if (hasFloatVersion(FuncName))
2153 return optimizeBinaryDoubleFP(CI, Builder);
2155 case LibFunc::memcpy_chk:
2156 return optimizeMemCpyChk(CI, Builder);
2162 if (!isCallingConvC)
2165 // Finally check for fortified library calls.
2166 if (FuncName.endswith("_chk")) {
2167 if (FuncName == "__memmove_chk")
2168 return optimizeMemMoveChk(CI, Builder);
2169 else if (FuncName == "__memset_chk")
2170 return optimizeMemSetChk(CI, Builder);
2171 else if (FuncName == "__strcpy_chk")
2172 return optimizeStrCpyChk(CI, Builder);
2173 else if (FuncName == "__stpcpy_chk")
2174 return optimizeStpCpyChk(CI, Builder);
2175 else if (FuncName == "__strncpy_chk")
2176 return optimizeStrNCpyChk(CI, Builder);
2177 else if (FuncName == "__stpncpy_chk")
2178 return optimizeStrNCpyChk(CI, Builder);
2184 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2185 const TargetLibraryInfo *TLI,
2186 bool UnsafeFPShrink) :
2189 UnsafeFPShrink(UnsafeFPShrink) {
2192 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2193 I->replaceAllUsesWith(With);
2194 I->eraseFromParent();
2198 // Additional cases that we need to add to this file:
2201 // * cbrt(expN(X)) -> expN(x/3)
2202 // * cbrt(sqrt(x)) -> pow(x,1/6)
2203 // * cbrt(sqrt(x)) -> pow(x,1/9)
2206 // * exp(log(x)) -> x
2209 // * log(exp(x)) -> x
2210 // * log(x**y) -> y*log(x)
2211 // * log(exp(y)) -> y*log(e)
2212 // * log(exp2(y)) -> y*log(2)
2213 // * log(exp10(y)) -> y*log(10)
2214 // * log(sqrt(x)) -> 0.5*log(x)
2215 // * log(pow(x,y)) -> y*log(x)
2217 // lround, lroundf, lroundl:
2218 // * lround(cnst) -> cnst'
2221 // * pow(exp(x),y) -> exp(x*y)
2222 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2223 // * pow(pow(x,y),z)-> pow(x,y*z)
2225 // round, roundf, roundl:
2226 // * round(cnst) -> cnst'
2229 // * signbit(cnst) -> cnst'
2230 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2232 // sqrt, sqrtf, sqrtl:
2233 // * sqrt(expN(x)) -> expN(x*0.5)
2234 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2235 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2238 // * tan(atan(x)) -> x
2240 // trunc, truncf, truncl:
2241 // * trunc(cnst) -> cnst'