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 file implements the library calls simplifier. It does not implement
11 // any pass, but can't be used by other passes to do simplifications.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Transforms/Utils/BuildLibCalls.h"
38 using namespace PatternMatch;
41 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::desc("Enable unsafe double to float "
44 "shrinking for math lib calls"));
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static bool ignoreCallingConv(LibFunc Func) {
52 return Func == LibFunc_abs || Func == LibFunc_labs ||
53 Func == LibFunc_llabs || Func == LibFunc_strlen;
56 static bool isCallingConvCCompatible(CallInst *CI) {
57 switch(CI->getCallingConv()) {
60 case llvm::CallingConv::C:
62 case llvm::CallingConv::ARM_APCS:
63 case llvm::CallingConv::ARM_AAPCS:
64 case llvm::CallingConv::ARM_AAPCS_VFP: {
66 // The iOS ABI diverges from the standard in some cases, so for now don't
67 // try to simplify those calls.
68 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
71 auto *FuncTy = CI->getFunctionType();
73 if (!FuncTy->getReturnType()->isPointerTy() &&
74 !FuncTy->getReturnType()->isIntegerTy() &&
75 !FuncTy->getReturnType()->isVoidTy())
78 for (auto Param : FuncTy->params()) {
79 if (!Param->isPointerTy() && !Param->isIntegerTy())
88 /// Return true if it is only used in equality comparisons with With.
89 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
90 for (User *U : V->users()) {
91 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
92 if (IC->isEquality() && IC->getOperand(1) == With)
94 // Unknown instruction.
100 static bool callHasFloatingPointArgument(const CallInst *CI) {
101 return any_of(CI->operands(), [](const Use &OI) {
102 return OI->getType()->isFloatingPointTy();
106 static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
107 if (Base < 2 || Base > 36)
108 // handle special zero base
113 std::string nptr = Str.str();
115 long long int Result = strtoll(nptr.c_str(), &End, Base);
119 // if we assume all possible target locales are ASCII supersets,
120 // then if strtoll successfully parses a number on the host,
121 // it will also successfully parse the same way on the target
125 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
128 return ConstantInt::get(CI->getType(), Result);
131 static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
132 const TargetLibraryInfo *TLI) {
133 CallInst *FOpen = dyn_cast<CallInst>(File);
137 Function *InnerCallee = FOpen->getCalledFunction();
142 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
143 Func != LibFunc_fopen)
146 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
147 if (PointerMayBeCaptured(File, true, true))
153 //===----------------------------------------------------------------------===//
154 // String and Memory Library Call Optimizations
155 //===----------------------------------------------------------------------===//
157 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
158 // Extract some information from the instruction
159 Value *Dst = CI->getArgOperand(0);
160 Value *Src = CI->getArgOperand(1);
162 // See if we can get the length of the input string.
163 uint64_t Len = GetStringLength(Src);
166 --Len; // Unbias length.
168 // Handle the simple, do-nothing case: strcat(x, "") -> x
172 return emitStrLenMemCpy(Src, Dst, Len, B);
175 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
177 // We need to find the end of the destination string. That's where the
178 // memory is to be moved to. We just generate a call to strlen.
179 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
183 // Now that we have the destination's length, we must index into the
184 // destination's pointer to get the actual memcpy destination (end of
185 // the string .. we're concatenating).
186 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
188 // We have enough information to now generate the memcpy call to do the
189 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
190 B.CreateMemCpy(CpyDst, 1, Src, 1,
191 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
195 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
196 // Extract some information from the instruction.
197 Value *Dst = CI->getArgOperand(0);
198 Value *Src = CI->getArgOperand(1);
201 // We don't do anything if length is not constant.
202 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
203 Len = LengthArg->getZExtValue();
207 // See if we can get the length of the input string.
208 uint64_t SrcLen = GetStringLength(Src);
211 --SrcLen; // Unbias length.
213 // Handle the simple, do-nothing cases:
214 // strncat(x, "", c) -> x
215 // strncat(x, c, 0) -> x
216 if (SrcLen == 0 || Len == 0)
219 // We don't optimize this case.
223 // strncat(x, s, c) -> strcat(x, s)
224 // s is constant so the strcat can be optimized further.
225 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
228 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
229 Function *Callee = CI->getCalledFunction();
230 FunctionType *FT = Callee->getFunctionType();
231 Value *SrcStr = CI->getArgOperand(0);
233 // If the second operand is non-constant, see if we can compute the length
234 // of the input string and turn this into memchr.
235 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
237 uint64_t Len = GetStringLength(SrcStr);
238 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
241 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
242 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
246 // Otherwise, the character is a constant, see if the first argument is
247 // a string literal. If so, we can constant fold.
249 if (!getConstantStringInfo(SrcStr, Str)) {
250 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
251 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
256 // Compute the offset, make sure to handle the case when we're searching for
257 // zero (a weird way to spell strlen).
258 size_t I = (0xFF & CharC->getSExtValue()) == 0
260 : Str.find(CharC->getSExtValue());
261 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
262 return Constant::getNullValue(CI->getType());
264 // strchr(s+n,c) -> gep(s+n+i,c)
265 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
268 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
269 Value *SrcStr = CI->getArgOperand(0);
270 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
272 // Cannot fold anything if we're not looking for a constant.
277 if (!getConstantStringInfo(SrcStr, Str)) {
278 // strrchr(s, 0) -> strchr(s, 0)
280 return emitStrChr(SrcStr, '\0', B, TLI);
284 // Compute the offset.
285 size_t I = (0xFF & CharC->getSExtValue()) == 0
287 : Str.rfind(CharC->getSExtValue());
288 if (I == StringRef::npos) // Didn't find the char. Return null.
289 return Constant::getNullValue(CI->getType());
291 // strrchr(s+n,c) -> gep(s+n+i,c)
292 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
295 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
296 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
297 if (Str1P == Str2P) // strcmp(x,x) -> 0
298 return ConstantInt::get(CI->getType(), 0);
300 StringRef Str1, Str2;
301 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
302 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
304 // strcmp(x, y) -> cnst (if both x and y are constant strings)
305 if (HasStr1 && HasStr2)
306 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
308 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
310 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
312 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
313 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
315 // strcmp(P, "x") -> memcmp(P, "x", 2)
316 uint64_t Len1 = GetStringLength(Str1P);
317 uint64_t Len2 = GetStringLength(Str2P);
319 return emitMemCmp(Str1P, Str2P,
320 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
321 std::min(Len1, Len2)),
328 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
329 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
330 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
331 return ConstantInt::get(CI->getType(), 0);
333 // Get the length argument if it is constant.
335 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
336 Length = LengthArg->getZExtValue();
340 if (Length == 0) // strncmp(x,y,0) -> 0
341 return ConstantInt::get(CI->getType(), 0);
343 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
344 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
346 StringRef Str1, Str2;
347 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
348 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
350 // strncmp(x, y) -> cnst (if both x and y are constant strings)
351 if (HasStr1 && HasStr2) {
352 StringRef SubStr1 = Str1.substr(0, Length);
353 StringRef SubStr2 = Str2.substr(0, Length);
354 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
357 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
359 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
361 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
362 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
367 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
368 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
369 if (Dst == Src) // strcpy(x,x) -> x
372 // See if we can get the length of the input string.
373 uint64_t Len = GetStringLength(Src);
377 // We have enough information to now generate the memcpy call to do the
378 // copy for us. Make a memcpy to copy the nul byte with align = 1.
379 B.CreateMemCpy(Dst, 1, Src, 1,
380 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
384 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
385 Function *Callee = CI->getCalledFunction();
386 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
387 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
388 Value *StrLen = emitStrLen(Src, B, DL, TLI);
389 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
392 // See if we can get the length of the input string.
393 uint64_t Len = GetStringLength(Src);
397 Type *PT = Callee->getFunctionType()->getParamType(0);
398 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
399 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
400 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
402 // We have enough information to now generate the memcpy call to do the
403 // copy for us. Make a memcpy to copy the nul byte with align = 1.
404 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
408 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
409 Function *Callee = CI->getCalledFunction();
410 Value *Dst = CI->getArgOperand(0);
411 Value *Src = CI->getArgOperand(1);
412 Value *LenOp = CI->getArgOperand(2);
414 // See if we can get the length of the input string.
415 uint64_t SrcLen = GetStringLength(Src);
421 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
422 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
427 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
428 Len = LengthArg->getZExtValue();
433 return Dst; // strncpy(x, y, 0) -> x
435 // Let strncpy handle the zero padding
436 if (Len > SrcLen + 1)
439 Type *PT = Callee->getFunctionType()->getParamType(0);
440 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
441 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
446 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
448 Value *Src = CI->getArgOperand(0);
450 // Constant folding: strlen("xyz") -> 3
451 if (uint64_t Len = GetStringLength(Src, CharSize))
452 return ConstantInt::get(CI->getType(), Len - 1);
454 // If s is a constant pointer pointing to a string literal, we can fold
455 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
456 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
457 // We only try to simplify strlen when the pointer s points to an array
458 // of i8. Otherwise, we would need to scale the offset x before doing the
459 // subtraction. This will make the optimization more complex, and it's not
460 // very useful because calling strlen for a pointer of other types is
462 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
463 if (!isGEPBasedOnPointerToString(GEP, CharSize))
466 ConstantDataArraySlice Slice;
467 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
468 uint64_t NullTermIdx;
469 if (Slice.Array == nullptr) {
472 NullTermIdx = ~((uint64_t)0);
473 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
474 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
479 // If the string does not have '\0', leave it to strlen to compute
481 if (NullTermIdx == ~((uint64_t)0))
485 Value *Offset = GEP->getOperand(2);
486 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
487 Known.Zero.flipAllBits();
489 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
491 // KnownZero's bits are flipped, so zeros in KnownZero now represent
492 // bits known to be zeros in Offset, and ones in KnowZero represent
493 // bits unknown in Offset. Therefore, Offset is known to be in range
494 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
495 // unsigned-less-than NullTermIdx.
497 // If Offset is not provably in the range [0, NullTermIdx], we can still
498 // optimize if we can prove that the program has undefined behavior when
499 // Offset is outside that range. That is the case when GEP->getOperand(0)
500 // is a pointer to an object whose memory extent is NullTermIdx+1.
501 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
502 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
503 NullTermIdx == ArrSize - 1)) {
504 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
505 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
513 // strlen(x?"foo":"bars") --> x ? 3 : 4
514 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
515 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
516 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
517 if (LenTrue && LenFalse) {
519 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
520 << "folded strlen(select) to select of constants";
522 return B.CreateSelect(SI->getCondition(),
523 ConstantInt::get(CI->getType(), LenTrue - 1),
524 ConstantInt::get(CI->getType(), LenFalse - 1));
528 // strlen(x) != 0 --> *x != 0
529 // strlen(x) == 0 --> *x == 0
530 if (isOnlyUsedInZeroEqualityComparison(CI))
531 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
536 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
537 return optimizeStringLength(CI, B, 8);
540 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
541 Module &M = *CI->getModule();
542 unsigned WCharSize = TLI->getWCharSize(M) * 8;
543 // We cannot perform this optimization without wchar_size metadata.
547 return optimizeStringLength(CI, B, WCharSize);
550 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
552 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
553 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
555 // strpbrk(s, "") -> nullptr
556 // strpbrk("", s) -> nullptr
557 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
558 return Constant::getNullValue(CI->getType());
561 if (HasS1 && HasS2) {
562 size_t I = S1.find_first_of(S2);
563 if (I == StringRef::npos) // No match.
564 return Constant::getNullValue(CI->getType());
566 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
570 // strpbrk(s, "a") -> strchr(s, 'a')
571 if (HasS2 && S2.size() == 1)
572 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
577 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
578 Value *EndPtr = CI->getArgOperand(1);
579 if (isa<ConstantPointerNull>(EndPtr)) {
580 // With a null EndPtr, this function won't capture the main argument.
581 // It would be readonly too, except that it still may write to errno.
582 CI->addParamAttr(0, Attribute::NoCapture);
588 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
590 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
591 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
593 // strspn(s, "") -> 0
594 // strspn("", s) -> 0
595 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
596 return Constant::getNullValue(CI->getType());
599 if (HasS1 && HasS2) {
600 size_t Pos = S1.find_first_not_of(S2);
601 if (Pos == StringRef::npos)
603 return ConstantInt::get(CI->getType(), Pos);
609 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
611 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
612 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
614 // strcspn("", s) -> 0
615 if (HasS1 && S1.empty())
616 return Constant::getNullValue(CI->getType());
619 if (HasS1 && HasS2) {
620 size_t Pos = S1.find_first_of(S2);
621 if (Pos == StringRef::npos)
623 return ConstantInt::get(CI->getType(), Pos);
626 // strcspn(s, "") -> strlen(s)
627 if (HasS2 && S2.empty())
628 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
633 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
634 // fold strstr(x, x) -> x.
635 if (CI->getArgOperand(0) == CI->getArgOperand(1))
636 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
638 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
639 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
640 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
643 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
647 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
648 ICmpInst *Old = cast<ICmpInst>(*UI++);
650 B.CreateICmp(Old->getPredicate(), StrNCmp,
651 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
652 replaceAllUsesWith(Old, Cmp);
657 // See if either input string is a constant string.
658 StringRef SearchStr, ToFindStr;
659 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
660 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
662 // fold strstr(x, "") -> x.
663 if (HasStr2 && ToFindStr.empty())
664 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
666 // If both strings are known, constant fold it.
667 if (HasStr1 && HasStr2) {
668 size_t Offset = SearchStr.find(ToFindStr);
670 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
671 return Constant::getNullValue(CI->getType());
673 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
674 Value *Result = castToCStr(CI->getArgOperand(0), B);
675 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
676 return B.CreateBitCast(Result, CI->getType());
679 // fold strstr(x, "y") -> strchr(x, 'y').
680 if (HasStr2 && ToFindStr.size() == 1) {
681 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
682 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
687 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
688 Value *SrcStr = CI->getArgOperand(0);
689 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
690 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
692 // memchr(x, y, 0) -> null
693 if (LenC && LenC->isZero())
694 return Constant::getNullValue(CI->getType());
696 // From now on we need at least constant length and string.
698 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
701 // Truncate the string to LenC. If Str is smaller than LenC we will still only
702 // scan the string, as reading past the end of it is undefined and we can just
703 // return null if we don't find the char.
704 Str = Str.substr(0, LenC->getZExtValue());
706 // If the char is variable but the input str and length are not we can turn
707 // this memchr call into a simple bit field test. Of course this only works
708 // when the return value is only checked against null.
710 // It would be really nice to reuse switch lowering here but we can't change
711 // the CFG at this point.
713 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
714 // after bounds check.
715 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
717 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
718 reinterpret_cast<const unsigned char *>(Str.end()));
720 // Make sure the bit field we're about to create fits in a register on the
722 // FIXME: On a 64 bit architecture this prevents us from using the
723 // interesting range of alpha ascii chars. We could do better by emitting
724 // two bitfields or shifting the range by 64 if no lower chars are used.
725 if (!DL.fitsInLegalInteger(Max + 1))
728 // For the bit field use a power-of-2 type with at least 8 bits to avoid
729 // creating unnecessary illegal types.
730 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
732 // Now build the bit field.
733 APInt Bitfield(Width, 0);
735 Bitfield.setBit((unsigned char)C);
736 Value *BitfieldC = B.getInt(Bitfield);
738 // First check that the bit field access is within bounds.
739 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
740 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
743 // Create code that checks if the given bit is set in the field.
744 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
745 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
747 // Finally merge both checks and cast to pointer type. The inttoptr
748 // implicitly zexts the i1 to intptr type.
749 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
752 // Check if all arguments are constants. If so, we can constant fold.
756 // Compute the offset.
757 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
758 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
759 return Constant::getNullValue(CI->getType());
761 // memchr(s+n,c,l) -> gep(s+n+i,c)
762 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
765 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
766 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
768 if (LHS == RHS) // memcmp(s,s,x) -> 0
769 return Constant::getNullValue(CI->getType());
771 // Make sure we have a constant length.
772 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
776 uint64_t Len = LenC->getZExtValue();
777 if (Len == 0) // memcmp(s1,s2,0) -> 0
778 return Constant::getNullValue(CI->getType());
780 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
782 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
783 CI->getType(), "lhsv");
784 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
785 CI->getType(), "rhsv");
786 return B.CreateSub(LHSV, RHSV, "chardiff");
789 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
790 // TODO: The case where both inputs are constants does not need to be limited
791 // to legal integers or equality comparison. See block below this.
792 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
793 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
794 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
796 // First, see if we can fold either argument to a constant.
797 Value *LHSV = nullptr;
798 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
799 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
800 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
802 Value *RHSV = nullptr;
803 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
804 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
805 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
808 // Don't generate unaligned loads. If either source is constant data,
809 // alignment doesn't matter for that source because there is no load.
810 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
811 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
814 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
815 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
819 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
820 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
822 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
826 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
827 // TODO: This is limited to i8 arrays.
828 StringRef LHSStr, RHSStr;
829 if (getConstantStringInfo(LHS, LHSStr) &&
830 getConstantStringInfo(RHS, RHSStr)) {
831 // Make sure we're not reading out-of-bounds memory.
832 if (Len > LHSStr.size() || Len > RHSStr.size())
834 // Fold the memcmp and normalize the result. This way we get consistent
835 // results across multiple platforms.
837 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
842 return ConstantInt::get(CI->getType(), Ret);
848 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
849 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
850 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
851 CI->getArgOperand(2));
852 return CI->getArgOperand(0);
855 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
856 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
857 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
858 CI->getArgOperand(2));
859 return CI->getArgOperand(0);
862 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
863 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
864 const TargetLibraryInfo &TLI) {
865 // This has to be a memset of zeros (bzero).
866 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
867 if (!FillValue || FillValue->getZExtValue() != 0)
870 // TODO: We should handle the case where the malloc has more than one use.
871 // This is necessary to optimize common patterns such as when the result of
872 // the malloc is checked against null or when a memset intrinsic is used in
873 // place of a memset library call.
874 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
875 if (!Malloc || !Malloc->hasOneUse())
878 // Is the inner call really malloc()?
879 Function *InnerCallee = Malloc->getCalledFunction();
884 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
885 Func != LibFunc_malloc)
888 // The memset must cover the same number of bytes that are malloc'd.
889 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
892 // Replace the malloc with a calloc. We need the data layout to know what the
893 // actual size of a 'size_t' parameter is.
894 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
895 const DataLayout &DL = Malloc->getModule()->getDataLayout();
896 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
897 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
898 Malloc->getArgOperand(0), Malloc->getAttributes(),
903 Malloc->replaceAllUsesWith(Calloc);
904 Malloc->eraseFromParent();
909 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
910 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
913 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
914 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
915 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
916 return CI->getArgOperand(0);
919 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
920 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
921 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
926 //===----------------------------------------------------------------------===//
927 // Math Library Optimizations
928 //===----------------------------------------------------------------------===//
930 /// Return a variant of Val with float type.
931 /// Currently this works in two cases: If Val is an FPExtension of a float
932 /// value to something bigger, simply return the operand.
933 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
934 /// loss of precision do so.
935 static Value *valueHasFloatPrecision(Value *Val) {
936 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
937 Value *Op = Cast->getOperand(0);
938 if (Op->getType()->isFloatTy())
941 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
942 APFloat F = Const->getValueAPF();
944 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
947 return ConstantFP::get(Const->getContext(), F);
952 /// Shrink double -> float for unary functions like 'floor'.
953 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
955 Function *Callee = CI->getCalledFunction();
956 // We know this libcall has a valid prototype, but we don't know which.
957 if (!CI->getType()->isDoubleTy())
961 // Check if all the uses for function like 'sin' are converted to float.
962 for (User *U : CI->users()) {
963 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
964 if (!Cast || !Cast->getType()->isFloatTy())
969 // If this is something like 'floor((double)floatval)', convert to floorf.
970 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
974 // If call isn't an intrinsic, check that it isn't within a function with the
975 // same name as the float version of this call.
977 // e.g. inline float expf(float val) { return (float) exp((double) val); }
979 // A similar such definition exists in the MinGW-w64 math.h header file which
980 // when compiled with -O2 -ffast-math causes the generation of infinite loops
981 // where expf is called.
982 if (!Callee->isIntrinsic()) {
983 const Function *F = CI->getFunction();
984 StringRef FName = F->getName();
985 StringRef CalleeName = Callee->getName();
986 if ((FName.size() == (CalleeName.size() + 1)) &&
987 (FName.back() == 'f') &&
988 FName.startswith(CalleeName))
992 // Propagate fast-math flags from the existing call to the new call.
993 IRBuilder<>::FastMathFlagGuard Guard(B);
994 B.setFastMathFlags(CI->getFastMathFlags());
996 // floor((double)floatval) -> (double)floorf(floatval)
997 if (Callee->isIntrinsic()) {
998 Module *M = CI->getModule();
999 Intrinsic::ID IID = Callee->getIntrinsicID();
1000 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1001 V = B.CreateCall(F, V);
1003 // The call is a library call rather than an intrinsic.
1004 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1007 return B.CreateFPExt(V, B.getDoubleTy());
1010 // Replace a libcall \p CI with a call to intrinsic \p IID
1011 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1012 // Propagate fast-math flags from the existing call to the new call.
1013 IRBuilder<>::FastMathFlagGuard Guard(B);
1014 B.setFastMathFlags(CI->getFastMathFlags());
1016 Module *M = CI->getModule();
1017 Value *V = CI->getArgOperand(0);
1018 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1019 CallInst *NewCall = B.CreateCall(F, V);
1020 NewCall->takeName(CI);
1024 /// Shrink double -> float for binary functions like 'fmin/fmax'.
1025 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1026 Function *Callee = CI->getCalledFunction();
1027 // We know this libcall has a valid prototype, but we don't know which.
1028 if (!CI->getType()->isDoubleTy())
1031 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1032 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1033 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1036 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1040 // Propagate fast-math flags from the existing call to the new call.
1041 IRBuilder<>::FastMathFlagGuard Guard(B);
1042 B.setFastMathFlags(CI->getFastMathFlags());
1044 // fmin((double)floatval1, (double)floatval2)
1045 // -> (double)fminf(floatval1, floatval2)
1046 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1047 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1048 Callee->getAttributes());
1049 return B.CreateFPExt(V, B.getDoubleTy());
1052 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1053 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1057 // Propagate fast-math flags from the existing call to new instructions.
1058 IRBuilder<>::FastMathFlagGuard Guard(B);
1059 B.setFastMathFlags(CI->getFastMathFlags());
1062 if (CI->getNumArgOperands() == 1) {
1063 Value *Op = CI->getArgOperand(0);
1064 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1065 Real = B.CreateExtractValue(Op, 0, "real");
1066 Imag = B.CreateExtractValue(Op, 1, "imag");
1068 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1069 Real = CI->getArgOperand(0);
1070 Imag = CI->getArgOperand(1);
1073 Value *RealReal = B.CreateFMul(Real, Real);
1074 Value *ImagImag = B.CreateFMul(Imag, Imag);
1076 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1078 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1081 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1082 Function *Callee = CI->getCalledFunction();
1083 Value *Ret = nullptr;
1084 StringRef Name = Callee->getName();
1085 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1086 Ret = optimizeUnaryDoubleFP(CI, B, true);
1088 // cos(-x) -> cos(x)
1089 Value *Op1 = CI->getArgOperand(0);
1090 if (BinaryOperator::isFNeg(Op1)) {
1091 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1092 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1097 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1098 // Multiplications calculated using Addition Chains.
1099 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1101 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1103 if (InnerChain[Exp])
1104 return InnerChain[Exp];
1106 static const unsigned AddChain[33][2] = {
1108 {0, 0}, // Unused (base case = pow1).
1109 {1, 1}, // Unused (pre-computed).
1110 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1111 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1112 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1113 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1114 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1117 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1118 getPow(InnerChain, AddChain[Exp][1], B));
1119 return InnerChain[Exp];
1122 /// Use square root in place of pow(x, +/-0.5).
1123 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1124 // TODO: There is some subset of 'fast' under which these transforms should
1129 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1130 Type *Ty = Pow->getType();
1132 const APFloat *ExpoF;
1133 if (!match(Expo, m_APFloat(ExpoF)) ||
1134 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1137 // If errno is never set, then use the intrinsic for sqrt().
1138 if (Pow->hasFnAttr(Attribute::ReadNone)) {
1139 Function *SqrtFn = Intrinsic::getDeclaration(Pow->getModule(),
1140 Intrinsic::sqrt, Ty);
1141 Sqrt = B.CreateCall(SqrtFn, Base);
1143 // Otherwise, use the libcall for sqrt().
1144 else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
1145 // TODO: We also should check that the target can in fact lower the sqrt()
1146 // libcall. We currently have no way to ask this question, so we ask if
1147 // the target has a sqrt() libcall, which is not exactly the same.
1148 Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt), B,
1149 Pow->getCalledFunction()->getAttributes());
1153 // If the exponent is negative, then get the reciprocal.
1154 if (ExpoF->isNegative())
1155 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
1160 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1161 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1162 Function *Callee = Pow->getCalledFunction();
1163 AttributeList Attrs = Callee->getAttributes();
1164 StringRef Name = Callee->getName();
1165 Module *Module = Pow->getModule();
1166 Type *Ty = Pow->getType();
1167 Value *Shrunk = nullptr;
1170 if (UnsafeFPShrink &&
1171 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1172 Shrunk = optimizeUnaryDoubleFP(Pow, B, true);
1174 // Propagate the math semantics from the call to any created instructions.
1175 IRBuilder<>::FastMathFlagGuard Guard(B);
1176 B.setFastMathFlags(Pow->getFastMathFlags());
1178 // Evaluate special cases related to the base.
1180 // pow(1.0, x) -> 1.0
1181 if (match(Base, m_SpecificFP(1.0)))
1184 // pow(2.0, x) -> exp2(x)
1185 if (match(Base, m_SpecificFP(2.0))) {
1186 Value *Exp2 = Intrinsic::getDeclaration(Module, Intrinsic::exp2, Ty);
1187 return B.CreateCall(Exp2, Expo, "exp2");
1190 // pow(10.0, x) -> exp10(x)
1191 if (ConstantFP *BaseC = dyn_cast<ConstantFP>(Base))
1192 // There's no exp10 intrinsic yet, but, maybe, some day there shall be one.
1193 if (BaseC->isExactlyValue(10.0) &&
1194 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1195 return emitUnaryFloatFnCall(Expo, TLI->getName(LibFunc_exp10), B, Attrs);
1197 // pow(exp(x), y) -> exp(x * y)
1198 // pow(exp2(x), y) -> exp2(x * y)
1199 // We enable these only with fast-math. Besides rounding differences, the
1200 // transformation changes overflow and underflow behavior quite dramatically.
1201 // Example: x = 1000, y = 0.001.
1202 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1203 auto *BaseFn = dyn_cast<CallInst>(Base);
1204 if (BaseFn && BaseFn->isFast() && Pow->isFast()) {
1206 Function *CalleeFn = BaseFn->getCalledFunction();
1207 if (CalleeFn && TLI->getLibFunc(CalleeFn->getName(), LibFn) &&
1208 (LibFn == LibFunc_exp || LibFn == LibFunc_exp2) && TLI->has(LibFn)) {
1209 IRBuilder<>::FastMathFlagGuard Guard(B);
1210 B.setFastMathFlags(Pow->getFastMathFlags());
1212 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1213 return emitUnaryFloatFnCall(FMul, CalleeFn->getName(), B,
1214 CalleeFn->getAttributes());
1218 // Evaluate special cases related to the exponent.
1220 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1223 ConstantFP *ExpoC = dyn_cast<ConstantFP>(Expo);
1227 // pow(x, -1.0) -> 1.0 / x
1228 if (ExpoC->isExactlyValue(-1.0))
1229 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1231 // pow(x, 0.0) -> 1.0
1232 if (ExpoC->getValueAPF().isZero())
1233 return ConstantFP::get(Ty, 1.0);
1236 if (ExpoC->isExactlyValue(1.0))
1239 // pow(x, 2.0) -> x * x
1240 if (ExpoC->isExactlyValue(2.0))
1241 return B.CreateFMul(Base, Base, "square");
1243 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
1244 if (ExpoC->isExactlyValue(0.5) &&
1245 hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl)) {
1246 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1247 // This is faster than calling pow(), and still handles -0.0 and
1248 // negative infinity correctly.
1249 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1250 Value *PosInf = ConstantFP::getInfinity(Ty);
1251 Value *NegInf = ConstantFP::getInfinity(Ty, true);
1253 // TODO: As above, we should lower to the sqrt() intrinsic if the pow() is
1254 // an intrinsic, to match errno semantics.
1255 Value *Sqrt = emitUnaryFloatFnCall(Base, TLI->getName(LibFunc_sqrt),
1257 Function *FAbsFn = Intrinsic::getDeclaration(Module, Intrinsic::fabs, Ty);
1258 Value *FAbs = B.CreateCall(FAbsFn, Sqrt, "abs");
1259 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1260 Sqrt = B.CreateSelect(FCmp, PosInf, FAbs);
1264 // pow(x, n) -> x * x * x * ....
1265 if (Pow->isFast()) {
1266 APFloat ExpoA = abs(ExpoC->getValueAPF());
1267 // We limit to a max of 7 fmul(s). Thus the maximum exponent is 32.
1268 // This transformation applies to integer exponents only.
1269 if (!ExpoA.isInteger() ||
1271 (APFloat(ExpoA.getSemantics(), 32.0)) == APFloat::cmpGreaterThan)
1274 // We will memoize intermediate products of the Addition Chain.
1275 Value *InnerChain[33] = {nullptr};
1276 InnerChain[1] = Base;
1277 InnerChain[2] = B.CreateFMul(Base, Base, "square");
1279 // We cannot readily convert a non-double type (like float) to a double.
1280 // So we first convert it to something which could be converted to double.
1281 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1282 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
1284 // If the exponent is negative, then get the reciprocal.
1285 if (ExpoC->isNegative())
1286 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
1293 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1294 Function *Callee = CI->getCalledFunction();
1295 Value *Ret = nullptr;
1296 StringRef Name = Callee->getName();
1297 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1298 Ret = optimizeUnaryDoubleFP(CI, B, true);
1300 Value *Op = CI->getArgOperand(0);
1301 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1302 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1303 LibFunc LdExp = LibFunc_ldexpl;
1304 if (Op->getType()->isFloatTy())
1305 LdExp = LibFunc_ldexpf;
1306 else if (Op->getType()->isDoubleTy())
1307 LdExp = LibFunc_ldexp;
1309 if (TLI->has(LdExp)) {
1310 Value *LdExpArg = nullptr;
1311 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1312 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1313 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1314 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1315 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1316 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1320 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1321 if (!Op->getType()->isFloatTy())
1322 One = ConstantExpr::getFPExtend(One, Op->getType());
1324 Module *M = CI->getModule();
1326 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1327 Op->getType(), B.getInt32Ty());
1328 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1329 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1330 CI->setCallingConv(F->getCallingConv());
1338 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1339 Function *Callee = CI->getCalledFunction();
1340 // If we can shrink the call to a float function rather than a double
1341 // function, do that first.
1342 StringRef Name = Callee->getName();
1343 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1344 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1347 IRBuilder<>::FastMathFlagGuard Guard(B);
1350 // If the call is 'fast', then anything we create here will also be 'fast'.
1353 // At a minimum, no-nans-fp-math must be true.
1354 if (!CI->hasNoNaNs())
1356 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1357 // "Ideally, fmax would be sensitive to the sign of zero, for example
1358 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1359 // might be impractical."
1360 FMF.setNoSignedZeros();
1363 B.setFastMathFlags(FMF);
1365 // We have a relaxed floating-point environment. We can ignore NaN-handling
1366 // and transform to a compare and select. We do not have to consider errno or
1367 // exceptions, because fmin/fmax do not have those.
1368 Value *Op0 = CI->getArgOperand(0);
1369 Value *Op1 = CI->getArgOperand(1);
1370 Value *Cmp = Callee->getName().startswith("fmin") ?
1371 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1372 return B.CreateSelect(Cmp, Op0, Op1);
1375 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1376 Function *Callee = CI->getCalledFunction();
1377 Value *Ret = nullptr;
1378 StringRef Name = Callee->getName();
1379 if (UnsafeFPShrink && hasFloatVersion(Name))
1380 Ret = optimizeUnaryDoubleFP(CI, B, true);
1384 Value *Op1 = CI->getArgOperand(0);
1385 auto *OpC = dyn_cast<CallInst>(Op1);
1387 // The earlier call must also be 'fast' in order to do these transforms.
1388 if (!OpC || !OpC->isFast())
1391 // log(pow(x,y)) -> y*log(x)
1392 // This is only applicable to log, log2, log10.
1393 if (Name != "log" && Name != "log2" && Name != "log10")
1396 IRBuilder<>::FastMathFlagGuard Guard(B);
1399 B.setFastMathFlags(FMF);
1402 Function *F = OpC->getCalledFunction();
1403 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1404 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1405 return B.CreateFMul(OpC->getArgOperand(1),
1406 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1407 Callee->getAttributes()), "mul");
1409 // log(exp2(y)) -> y*log(2)
1410 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1411 TLI->has(Func) && Func == LibFunc_exp2)
1412 return B.CreateFMul(
1413 OpC->getArgOperand(0),
1414 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1415 Callee->getName(), B, Callee->getAttributes()),
1420 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1421 Function *Callee = CI->getCalledFunction();
1422 Value *Ret = nullptr;
1423 // TODO: Once we have a way (other than checking for the existince of the
1424 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1426 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1427 Callee->getIntrinsicID() == Intrinsic::sqrt))
1428 Ret = optimizeUnaryDoubleFP(CI, B, true);
1433 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1434 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
1437 // We're looking for a repeated factor in a multiplication tree,
1438 // so we can do this fold: sqrt(x * x) -> fabs(x);
1439 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1440 Value *Op0 = I->getOperand(0);
1441 Value *Op1 = I->getOperand(1);
1442 Value *RepeatOp = nullptr;
1443 Value *OtherOp = nullptr;
1445 // Simple match: the operands of the multiply are identical.
1448 // Look for a more complicated pattern: one of the operands is itself
1449 // a multiply, so search for a common factor in that multiply.
1450 // Note: We don't bother looking any deeper than this first level or for
1451 // variations of this pattern because instcombine's visitFMUL and/or the
1452 // reassociation pass should give us this form.
1453 Value *OtherMul0, *OtherMul1;
1454 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1455 // Pattern: sqrt((x * y) * z)
1456 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
1457 // Matched: sqrt((x * x) * z)
1458 RepeatOp = OtherMul0;
1466 // Fast math flags for any created instructions should match the sqrt
1468 IRBuilder<>::FastMathFlagGuard Guard(B);
1469 B.setFastMathFlags(I->getFastMathFlags());
1471 // If we found a repeated factor, hoist it out of the square root and
1472 // replace it with the fabs of that factor.
1473 Module *M = Callee->getParent();
1474 Type *ArgType = I->getType();
1475 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1476 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1478 // If we found a non-repeated factor, we still need to get its square
1479 // root. We then multiply that by the value that was simplified out
1480 // of the square root calculation.
1481 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1482 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1483 return B.CreateFMul(FabsCall, SqrtCall);
1488 // TODO: Generalize to handle any trig function and its inverse.
1489 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1490 Function *Callee = CI->getCalledFunction();
1491 Value *Ret = nullptr;
1492 StringRef Name = Callee->getName();
1493 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1494 Ret = optimizeUnaryDoubleFP(CI, B, true);
1496 Value *Op1 = CI->getArgOperand(0);
1497 auto *OpC = dyn_cast<CallInst>(Op1);
1501 // Both calls must be 'fast' in order to remove them.
1502 if (!CI->isFast() || !OpC->isFast())
1505 // tan(atan(x)) -> x
1506 // tanf(atanf(x)) -> x
1507 // tanl(atanl(x)) -> x
1509 Function *F = OpC->getCalledFunction();
1510 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1511 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1512 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1513 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1514 Ret = OpC->getArgOperand(0);
1518 static bool isTrigLibCall(CallInst *CI) {
1519 // We can only hope to do anything useful if we can ignore things like errno
1520 // and floating-point exceptions.
1521 // We already checked the prototype.
1522 return CI->hasFnAttr(Attribute::NoUnwind) &&
1523 CI->hasFnAttr(Attribute::ReadNone);
1526 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1527 bool UseFloat, Value *&Sin, Value *&Cos,
1529 Type *ArgTy = Arg->getType();
1533 Triple T(OrigCallee->getParent()->getTargetTriple());
1535 Name = "__sincospif_stret";
1537 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1538 // x86_64 can't use {float, float} since that would be returned in both
1539 // xmm0 and xmm1, which isn't what a real struct would do.
1540 ResTy = T.getArch() == Triple::x86_64
1541 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1542 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
1544 Name = "__sincospi_stret";
1545 ResTy = StructType::get(ArgTy, ArgTy);
1548 Module *M = OrigCallee->getParent();
1549 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1552 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1553 // If the argument is an instruction, it must dominate all uses so put our
1554 // sincos call there.
1555 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1557 // Otherwise (e.g. for a constant) the beginning of the function is as
1558 // good a place as any.
1559 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1560 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1563 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1565 if (SinCos->getType()->isStructTy()) {
1566 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1567 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1569 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1571 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1576 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1577 // Make sure the prototype is as expected, otherwise the rest of the
1578 // function is probably invalid and likely to abort.
1579 if (!isTrigLibCall(CI))
1582 Value *Arg = CI->getArgOperand(0);
1583 SmallVector<CallInst *, 1> SinCalls;
1584 SmallVector<CallInst *, 1> CosCalls;
1585 SmallVector<CallInst *, 1> SinCosCalls;
1587 bool IsFloat = Arg->getType()->isFloatTy();
1589 // Look for all compatible sinpi, cospi and sincospi calls with the same
1590 // argument. If there are enough (in some sense) we can make the
1592 Function *F = CI->getFunction();
1593 for (User *U : Arg->users())
1594 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1596 // It's only worthwhile if both sinpi and cospi are actually used.
1597 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1600 Value *Sin, *Cos, *SinCos;
1601 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1603 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1605 for (CallInst *C : Calls)
1606 replaceAllUsesWith(C, Res);
1609 replaceTrigInsts(SinCalls, Sin);
1610 replaceTrigInsts(CosCalls, Cos);
1611 replaceTrigInsts(SinCosCalls, SinCos);
1616 void LibCallSimplifier::classifyArgUse(
1617 Value *Val, Function *F, bool IsFloat,
1618 SmallVectorImpl<CallInst *> &SinCalls,
1619 SmallVectorImpl<CallInst *> &CosCalls,
1620 SmallVectorImpl<CallInst *> &SinCosCalls) {
1621 CallInst *CI = dyn_cast<CallInst>(Val);
1626 // Don't consider calls in other functions.
1627 if (CI->getFunction() != F)
1630 Function *Callee = CI->getCalledFunction();
1632 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1637 if (Func == LibFunc_sinpif)
1638 SinCalls.push_back(CI);
1639 else if (Func == LibFunc_cospif)
1640 CosCalls.push_back(CI);
1641 else if (Func == LibFunc_sincospif_stret)
1642 SinCosCalls.push_back(CI);
1644 if (Func == LibFunc_sinpi)
1645 SinCalls.push_back(CI);
1646 else if (Func == LibFunc_cospi)
1647 CosCalls.push_back(CI);
1648 else if (Func == LibFunc_sincospi_stret)
1649 SinCosCalls.push_back(CI);
1653 //===----------------------------------------------------------------------===//
1654 // Integer Library Call Optimizations
1655 //===----------------------------------------------------------------------===//
1657 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1658 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1659 Value *Op = CI->getArgOperand(0);
1660 Type *ArgType = Op->getType();
1661 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1662 Intrinsic::cttz, ArgType);
1663 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1664 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1665 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1667 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1668 return B.CreateSelect(Cond, V, B.getInt32(0));
1671 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1672 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1673 Value *Op = CI->getArgOperand(0);
1674 Type *ArgType = Op->getType();
1675 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1676 Intrinsic::ctlz, ArgType);
1677 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1678 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1680 return B.CreateIntCast(V, CI->getType(), false);
1683 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1684 // abs(x) -> x <s 0 ? -x : x
1685 // The negation has 'nsw' because abs of INT_MIN is undefined.
1686 Value *X = CI->getArgOperand(0);
1687 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1688 Value *NegX = B.CreateNSWNeg(X, "neg");
1689 return B.CreateSelect(IsNeg, NegX, X);
1692 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1693 // isdigit(c) -> (c-'0') <u 10
1694 Value *Op = CI->getArgOperand(0);
1695 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1696 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1697 return B.CreateZExt(Op, CI->getType());
1700 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1701 // isascii(c) -> c <u 128
1702 Value *Op = CI->getArgOperand(0);
1703 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1704 return B.CreateZExt(Op, CI->getType());
1707 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1708 // toascii(c) -> c & 0x7f
1709 return B.CreateAnd(CI->getArgOperand(0),
1710 ConstantInt::get(CI->getType(), 0x7F));
1713 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1715 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1718 return convertStrToNumber(CI, Str, 10);
1721 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1723 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1726 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1729 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1730 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1736 //===----------------------------------------------------------------------===//
1737 // Formatting and IO Library Call Optimizations
1738 //===----------------------------------------------------------------------===//
1740 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1742 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1744 Function *Callee = CI->getCalledFunction();
1745 // Error reporting calls should be cold, mark them as such.
1746 // This applies even to non-builtin calls: it is only a hint and applies to
1747 // functions that the frontend might not understand as builtins.
1749 // This heuristic was suggested in:
1750 // Improving Static Branch Prediction in a Compiler
1751 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1752 // Proceedings of PACT'98, Oct. 1998, IEEE
1753 if (!CI->hasFnAttr(Attribute::Cold) &&
1754 isReportingError(Callee, CI, StreamArg)) {
1755 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
1761 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1762 if (!Callee || !Callee->isDeclaration())
1768 // These functions might be considered cold, but only if their stream
1769 // argument is stderr.
1771 if (StreamArg >= (int)CI->getNumArgOperands())
1773 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1776 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1777 if (!GV || !GV->isDeclaration())
1779 return GV->getName() == "stderr";
1782 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1783 // Check for a fixed format string.
1784 StringRef FormatStr;
1785 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1788 // Empty format string -> noop.
1789 if (FormatStr.empty()) // Tolerate printf's declared void.
1790 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1792 // Do not do any of the following transformations if the printf return value
1793 // is used, in general the printf return value is not compatible with either
1794 // putchar() or puts().
1795 if (!CI->use_empty())
1798 // printf("x") -> putchar('x'), even for "%" and "%%".
1799 if (FormatStr.size() == 1 || FormatStr == "%%")
1800 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1802 // printf("%s", "a") --> putchar('a')
1803 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1805 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1807 if (ChrStr.size() != 1)
1809 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1812 // printf("foo\n") --> puts("foo")
1813 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1814 FormatStr.find('%') == StringRef::npos) { // No format characters.
1815 // Create a string literal with no \n on it. We expect the constant merge
1816 // pass to be run after this pass, to merge duplicate strings.
1817 FormatStr = FormatStr.drop_back();
1818 Value *GV = B.CreateGlobalString(FormatStr, "str");
1819 return emitPutS(GV, B, TLI);
1822 // Optimize specific format strings.
1823 // printf("%c", chr) --> putchar(chr)
1824 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1825 CI->getArgOperand(1)->getType()->isIntegerTy())
1826 return emitPutChar(CI->getArgOperand(1), B, TLI);
1828 // printf("%s\n", str) --> puts(str)
1829 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1830 CI->getArgOperand(1)->getType()->isPointerTy())
1831 return emitPutS(CI->getArgOperand(1), B, TLI);
1835 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1837 Function *Callee = CI->getCalledFunction();
1838 FunctionType *FT = Callee->getFunctionType();
1839 if (Value *V = optimizePrintFString(CI, B)) {
1843 // printf(format, ...) -> iprintf(format, ...) if no floating point
1845 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
1846 Module *M = B.GetInsertBlock()->getParent()->getParent();
1847 Constant *IPrintFFn =
1848 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1849 CallInst *New = cast<CallInst>(CI->clone());
1850 New->setCalledFunction(IPrintFFn);
1857 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1858 // Check for a fixed format string.
1859 StringRef FormatStr;
1860 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1863 // If we just have a format string (nothing else crazy) transform it.
1864 if (CI->getNumArgOperands() == 2) {
1865 // Make sure there's no % in the constant array. We could try to handle
1866 // %% -> % in the future if we cared.
1867 if (FormatStr.find('%') != StringRef::npos)
1868 return nullptr; // we found a format specifier, bail out.
1870 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1871 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
1872 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1873 FormatStr.size() + 1)); // Copy the null byte.
1874 return ConstantInt::get(CI->getType(), FormatStr.size());
1877 // The remaining optimizations require the format string to be "%s" or "%c"
1878 // and have an extra operand.
1879 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1880 CI->getNumArgOperands() < 3)
1883 // Decode the second character of the format string.
1884 if (FormatStr[1] == 'c') {
1885 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1886 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1888 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1889 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1890 B.CreateStore(V, Ptr);
1891 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1892 B.CreateStore(B.getInt8(0), Ptr);
1894 return ConstantInt::get(CI->getType(), 1);
1897 if (FormatStr[1] == 's') {
1898 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1899 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1902 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1906 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1907 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
1909 // The sprintf result is the unincremented number of bytes in the string.
1910 return B.CreateIntCast(Len, CI->getType(), false);
1915 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1916 Function *Callee = CI->getCalledFunction();
1917 FunctionType *FT = Callee->getFunctionType();
1918 if (Value *V = optimizeSPrintFString(CI, B)) {
1922 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1924 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
1925 Module *M = B.GetInsertBlock()->getParent()->getParent();
1926 Constant *SIPrintFFn =
1927 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1928 CallInst *New = cast<CallInst>(CI->clone());
1929 New->setCalledFunction(SIPrintFFn);
1936 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
1937 // Check for a fixed format string.
1938 StringRef FormatStr;
1939 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
1943 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1947 uint64_t N = Size->getZExtValue();
1949 // If we just have a format string (nothing else crazy) transform it.
1950 if (CI->getNumArgOperands() == 3) {
1951 // Make sure there's no % in the constant array. We could try to handle
1952 // %% -> % in the future if we cared.
1953 if (FormatStr.find('%') != StringRef::npos)
1954 return nullptr; // we found a format specifier, bail out.
1957 return ConstantInt::get(CI->getType(), FormatStr.size());
1958 else if (N < FormatStr.size() + 1)
1961 // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
1964 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
1965 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1966 FormatStr.size() + 1)); // Copy the null byte.
1967 return ConstantInt::get(CI->getType(), FormatStr.size());
1970 // The remaining optimizations require the format string to be "%s" or "%c"
1971 // and have an extra operand.
1972 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
1973 CI->getNumArgOperands() == 4) {
1975 // Decode the second character of the format string.
1976 if (FormatStr[1] == 'c') {
1978 return ConstantInt::get(CI->getType(), 1);
1982 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1983 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
1985 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
1986 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1987 B.CreateStore(V, Ptr);
1988 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1989 B.CreateStore(B.getInt8(0), Ptr);
1991 return ConstantInt::get(CI->getType(), 1);
1994 if (FormatStr[1] == 's') {
1995 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
1997 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2001 return ConstantInt::get(CI->getType(), Str.size());
2002 else if (N < Str.size() + 1)
2005 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2006 ConstantInt::get(CI->getType(), Str.size() + 1));
2008 // The snprintf result is the unincremented number of bytes in the string.
2009 return ConstantInt::get(CI->getType(), Str.size());
2015 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2016 if (Value *V = optimizeSnPrintFString(CI, B)) {
2023 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2024 optimizeErrorReporting(CI, B, 0);
2026 // All the optimizations depend on the format string.
2027 StringRef FormatStr;
2028 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2031 // Do not do any of the following transformations if the fprintf return
2032 // value is used, in general the fprintf return value is not compatible
2033 // with fwrite(), fputc() or fputs().
2034 if (!CI->use_empty())
2037 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2038 if (CI->getNumArgOperands() == 2) {
2039 // Could handle %% -> % if we cared.
2040 if (FormatStr.find('%') != StringRef::npos)
2041 return nullptr; // We found a format specifier.
2044 CI->getArgOperand(1),
2045 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
2046 CI->getArgOperand(0), B, DL, TLI);
2049 // The remaining optimizations require the format string to be "%s" or "%c"
2050 // and have an extra operand.
2051 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2052 CI->getNumArgOperands() < 3)
2055 // Decode the second character of the format string.
2056 if (FormatStr[1] == 'c') {
2057 // fprintf(F, "%c", chr) --> fputc(chr, F)
2058 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2060 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2063 if (FormatStr[1] == 's') {
2064 // fprintf(F, "%s", str) --> fputs(str, F)
2065 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2067 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2072 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2073 Function *Callee = CI->getCalledFunction();
2074 FunctionType *FT = Callee->getFunctionType();
2075 if (Value *V = optimizeFPrintFString(CI, B)) {
2079 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2080 // floating point arguments.
2081 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
2082 Module *M = B.GetInsertBlock()->getParent()->getParent();
2083 Constant *FIPrintFFn =
2084 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2085 CallInst *New = cast<CallInst>(CI->clone());
2086 New->setCalledFunction(FIPrintFFn);
2093 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2094 optimizeErrorReporting(CI, B, 3);
2096 // Get the element size and count.
2097 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2098 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2099 if (SizeC && CountC) {
2100 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2102 // If this is writing zero records, remove the call (it's a noop).
2104 return ConstantInt::get(CI->getType(), 0);
2106 // If this is writing one byte, turn it into fputc.
2107 // This optimisation is only valid, if the return value is unused.
2108 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2109 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2110 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2111 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2115 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2116 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2117 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2123 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2124 optimizeErrorReporting(CI, B, 1);
2126 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2127 // requires more arguments and thus extra MOVs are required.
2128 if (CI->getFunction()->optForSize())
2131 // Check if has any use
2132 if (!CI->use_empty()) {
2133 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2134 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2137 // We can't optimize if return value is used.
2141 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2142 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2146 // Known to have no uses (see above).
2148 CI->getArgOperand(0),
2149 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2150 CI->getArgOperand(1), B, DL, TLI);
2153 Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2154 optimizeErrorReporting(CI, B, 1);
2156 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2157 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2163 Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2164 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2165 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2170 Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2171 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2172 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2173 CI->getArgOperand(2), B, TLI);
2178 Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2179 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2180 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2181 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2187 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2188 // Check for a constant string.
2190 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2193 if (Str.empty() && CI->use_empty()) {
2194 // puts("") -> putchar('\n')
2195 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
2196 if (CI->use_empty() || !Res)
2198 return B.CreateIntCast(Res, CI->getType(), true);
2204 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2206 SmallString<20> FloatFuncName = FuncName;
2207 FloatFuncName += 'f';
2208 if (TLI->getLibFunc(FloatFuncName, Func))
2209 return TLI->has(Func);
2213 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2214 IRBuilder<> &Builder) {
2216 Function *Callee = CI->getCalledFunction();
2217 // Check for string/memory library functions.
2218 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2219 // Make sure we never change the calling convention.
2220 assert((ignoreCallingConv(Func) ||
2221 isCallingConvCCompatible(CI)) &&
2222 "Optimizing string/memory libcall would change the calling convention");
2224 case LibFunc_strcat:
2225 return optimizeStrCat(CI, Builder);
2226 case LibFunc_strncat:
2227 return optimizeStrNCat(CI, Builder);
2228 case LibFunc_strchr:
2229 return optimizeStrChr(CI, Builder);
2230 case LibFunc_strrchr:
2231 return optimizeStrRChr(CI, Builder);
2232 case LibFunc_strcmp:
2233 return optimizeStrCmp(CI, Builder);
2234 case LibFunc_strncmp:
2235 return optimizeStrNCmp(CI, Builder);
2236 case LibFunc_strcpy:
2237 return optimizeStrCpy(CI, Builder);
2238 case LibFunc_stpcpy:
2239 return optimizeStpCpy(CI, Builder);
2240 case LibFunc_strncpy:
2241 return optimizeStrNCpy(CI, Builder);
2242 case LibFunc_strlen:
2243 return optimizeStrLen(CI, Builder);
2244 case LibFunc_strpbrk:
2245 return optimizeStrPBrk(CI, Builder);
2246 case LibFunc_strtol:
2247 case LibFunc_strtod:
2248 case LibFunc_strtof:
2249 case LibFunc_strtoul:
2250 case LibFunc_strtoll:
2251 case LibFunc_strtold:
2252 case LibFunc_strtoull:
2253 return optimizeStrTo(CI, Builder);
2254 case LibFunc_strspn:
2255 return optimizeStrSpn(CI, Builder);
2256 case LibFunc_strcspn:
2257 return optimizeStrCSpn(CI, Builder);
2258 case LibFunc_strstr:
2259 return optimizeStrStr(CI, Builder);
2260 case LibFunc_memchr:
2261 return optimizeMemChr(CI, Builder);
2262 case LibFunc_memcmp:
2263 return optimizeMemCmp(CI, Builder);
2264 case LibFunc_memcpy:
2265 return optimizeMemCpy(CI, Builder);
2266 case LibFunc_memmove:
2267 return optimizeMemMove(CI, Builder);
2268 case LibFunc_memset:
2269 return optimizeMemSet(CI, Builder);
2270 case LibFunc_realloc:
2271 return optimizeRealloc(CI, Builder);
2272 case LibFunc_wcslen:
2273 return optimizeWcslen(CI, Builder);
2281 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2283 IRBuilder<> &Builder) {
2284 // Don't optimize calls that require strict floating point semantics.
2285 if (CI->isStrictFP())
2292 return optimizeCos(CI, Builder);
2293 case LibFunc_sinpif:
2295 case LibFunc_cospif:
2297 return optimizeSinCosPi(CI, Builder);
2301 return optimizePow(CI, Builder);
2305 return optimizeExp2(CI, Builder);
2309 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2313 return optimizeSqrt(CI, Builder);
2319 return optimizeLog(CI, Builder);
2323 return optimizeTan(CI, Builder);
2325 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2327 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2329 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2330 case LibFunc_nearbyint:
2331 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2333 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2335 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2350 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2351 return optimizeUnaryDoubleFP(CI, Builder, true);
2353 case LibFunc_copysign:
2354 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2355 return optimizeBinaryDoubleFP(CI, Builder);
2363 return optimizeFMinFMax(CI, Builder);
2367 return optimizeCAbs(CI, Builder);
2373 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2374 // TODO: Split out the code below that operates on FP calls so that
2375 // we can all non-FP calls with the StrictFP attribute to be
2377 if (CI->isNoBuiltin())
2381 Function *Callee = CI->getCalledFunction();
2383 SmallVector<OperandBundleDef, 2> OpBundles;
2384 CI->getOperandBundlesAsDefs(OpBundles);
2385 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2386 bool isCallingConvC = isCallingConvCCompatible(CI);
2388 // Command-line parameter overrides instruction attribute.
2389 // This can't be moved to optimizeFloatingPointLibCall() because it may be
2390 // used by the intrinsic optimizations.
2391 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2392 UnsafeFPShrink = EnableUnsafeFPShrink;
2393 else if (isa<FPMathOperator>(CI) && CI->isFast())
2394 UnsafeFPShrink = true;
2396 // First, check for intrinsics.
2397 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2398 if (!isCallingConvC)
2400 // The FP intrinsics have corresponding constrained versions so we don't
2401 // need to check for the StrictFP attribute here.
2402 switch (II->getIntrinsicID()) {
2403 case Intrinsic::pow:
2404 return optimizePow(CI, Builder);
2405 case Intrinsic::exp2:
2406 return optimizeExp2(CI, Builder);
2407 case Intrinsic::log:
2408 return optimizeLog(CI, Builder);
2409 case Intrinsic::sqrt:
2410 return optimizeSqrt(CI, Builder);
2411 // TODO: Use foldMallocMemset() with memset intrinsic.
2417 // Also try to simplify calls to fortified library functions.
2418 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2419 // Try to further simplify the result.
2420 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2421 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2422 // Use an IR Builder from SimplifiedCI if available instead of CI
2423 // to guarantee we reach all uses we might replace later on.
2424 IRBuilder<> TmpBuilder(SimplifiedCI);
2425 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2426 // If we were able to further simplify, remove the now redundant call.
2427 SimplifiedCI->replaceAllUsesWith(V);
2428 SimplifiedCI->eraseFromParent();
2432 return SimplifiedFortifiedCI;
2435 // Then check for known library functions.
2436 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2437 // We never change the calling convention.
2438 if (!ignoreCallingConv(Func) && !isCallingConvC)
2440 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2442 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2448 return optimizeFFS(CI, Builder);
2452 return optimizeFls(CI, Builder);
2456 return optimizeAbs(CI, Builder);
2457 case LibFunc_isdigit:
2458 return optimizeIsDigit(CI, Builder);
2459 case LibFunc_isascii:
2460 return optimizeIsAscii(CI, Builder);
2461 case LibFunc_toascii:
2462 return optimizeToAscii(CI, Builder);
2466 return optimizeAtoi(CI, Builder);
2467 case LibFunc_strtol:
2468 case LibFunc_strtoll:
2469 return optimizeStrtol(CI, Builder);
2470 case LibFunc_printf:
2471 return optimizePrintF(CI, Builder);
2472 case LibFunc_sprintf:
2473 return optimizeSPrintF(CI, Builder);
2474 case LibFunc_snprintf:
2475 return optimizeSnPrintF(CI, Builder);
2476 case LibFunc_fprintf:
2477 return optimizeFPrintF(CI, Builder);
2478 case LibFunc_fwrite:
2479 return optimizeFWrite(CI, Builder);
2481 return optimizeFRead(CI, Builder);
2483 return optimizeFPuts(CI, Builder);
2485 return optimizeFGets(CI, Builder);
2487 return optimizeFPutc(CI, Builder);
2489 return optimizeFGetc(CI, Builder);
2491 return optimizePuts(CI, Builder);
2492 case LibFunc_perror:
2493 return optimizeErrorReporting(CI, Builder);
2494 case LibFunc_vfprintf:
2495 case LibFunc_fiprintf:
2496 return optimizeErrorReporting(CI, Builder, 0);
2504 LibCallSimplifier::LibCallSimplifier(
2505 const DataLayout &DL, const TargetLibraryInfo *TLI,
2506 OptimizationRemarkEmitter &ORE,
2507 function_ref<void(Instruction *, Value *)> Replacer)
2508 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2509 UnsafeFPShrink(false), Replacer(Replacer) {}
2511 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2512 // Indirect through the replacer used in this instance.
2517 // Additional cases that we need to add to this file:
2520 // * cbrt(expN(X)) -> expN(x/3)
2521 // * cbrt(sqrt(x)) -> pow(x,1/6)
2522 // * cbrt(cbrt(x)) -> pow(x,1/9)
2525 // * exp(log(x)) -> x
2528 // * log(exp(x)) -> x
2529 // * log(exp(y)) -> y*log(e)
2530 // * log(exp10(y)) -> y*log(10)
2531 // * log(sqrt(x)) -> 0.5*log(x)
2534 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2535 // * pow(pow(x,y),z)-> pow(x,y*z)
2538 // * signbit(cnst) -> cnst'
2539 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2541 // sqrt, sqrtf, sqrtl:
2542 // * sqrt(expN(x)) -> expN(x*0.5)
2543 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2544 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2547 //===----------------------------------------------------------------------===//
2548 // Fortified Library Call Optimizations
2549 //===----------------------------------------------------------------------===//
2551 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2555 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2557 if (ConstantInt *ObjSizeCI =
2558 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2559 if (ObjSizeCI->isMinusOne())
2561 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2562 if (OnlyLowerUnknownSize)
2565 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2566 // If the length is 0 we don't know how long it is and so we can't
2567 // remove the check.
2570 return ObjSizeCI->getZExtValue() >= Len;
2572 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2573 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2578 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2580 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2581 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2582 CI->getArgOperand(2));
2583 return CI->getArgOperand(0);
2588 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2590 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2591 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2592 CI->getArgOperand(2));
2593 return CI->getArgOperand(0);
2598 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2600 // TODO: Try foldMallocMemset() here.
2602 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2603 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2604 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2605 return CI->getArgOperand(0);
2610 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2613 Function *Callee = CI->getCalledFunction();
2614 StringRef Name = Callee->getName();
2615 const DataLayout &DL = CI->getModule()->getDataLayout();
2616 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2617 *ObjSize = CI->getArgOperand(2);
2619 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2620 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2621 Value *StrLen = emitStrLen(Src, B, DL, TLI);
2622 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2625 // If a) we don't have any length information, or b) we know this will
2626 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2627 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2628 // TODO: It might be nice to get a maximum length out of the possible
2629 // string lengths for varying.
2630 if (isFortifiedCallFoldable(CI, 2, 1, true))
2631 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2633 if (OnlyLowerUnknownSize)
2636 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2637 uint64_t Len = GetStringLength(Src);
2641 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2642 Value *LenV = ConstantInt::get(SizeTTy, Len);
2643 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2644 // If the function was an __stpcpy_chk, and we were able to fold it into
2645 // a __memcpy_chk, we still need to return the correct end pointer.
2646 if (Ret && Func == LibFunc_stpcpy_chk)
2647 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2651 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2654 Function *Callee = CI->getCalledFunction();
2655 StringRef Name = Callee->getName();
2656 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2657 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2658 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2664 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2665 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2666 // Some clang users checked for _chk libcall availability using:
2667 // __has_builtin(__builtin___memcpy_chk)
2668 // When compiling with -fno-builtin, this is always true.
2669 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2670 // end up with fortified libcalls, which isn't acceptable in a freestanding
2671 // environment which only provides their non-fortified counterparts.
2673 // Until we change clang and/or teach external users to check for availability
2674 // differently, disregard the "nobuiltin" attribute and TLI::has.
2679 Function *Callee = CI->getCalledFunction();
2681 SmallVector<OperandBundleDef, 2> OpBundles;
2682 CI->getOperandBundlesAsDefs(OpBundles);
2683 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2684 bool isCallingConvC = isCallingConvCCompatible(CI);
2686 // First, check that this is a known library functions and that the prototype
2688 if (!TLI->getLibFunc(*Callee, Func))
2691 // We never change the calling convention.
2692 if (!ignoreCallingConv(Func) && !isCallingConvC)
2696 case LibFunc_memcpy_chk:
2697 return optimizeMemCpyChk(CI, Builder);
2698 case LibFunc_memmove_chk:
2699 return optimizeMemMoveChk(CI, Builder);
2700 case LibFunc_memset_chk:
2701 return optimizeMemSetChk(CI, Builder);
2702 case LibFunc_stpcpy_chk:
2703 case LibFunc_strcpy_chk:
2704 return optimizeStrpCpyChk(CI, Builder, Func);
2705 case LibFunc_stpncpy_chk:
2706 case LibFunc_strncpy_chk:
2707 return optimizeStrpNCpyChk(CI, Builder, Func);
2714 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2715 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2716 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}