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/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/KnownBits.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/Transforms/Utils/Local.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 only matters that the value is equal or not-equal to zero.
89 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
90 for (User *U : V->users()) {
91 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
93 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 // Unknown instruction.
102 /// Return true if it is only used in equality comparisons with With.
103 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
104 for (User *U : V->users()) {
105 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
106 if (IC->isEquality() && IC->getOperand(1) == With)
108 // Unknown instruction.
114 static bool callHasFloatingPointArgument(const CallInst *CI) {
115 return any_of(CI->operands(), [](const Use &OI) {
116 return OI->getType()->isFloatingPointTy();
120 /// \brief Check whether the overloaded unary floating point function
121 /// corresponding to \a Ty is available.
122 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
123 LibFunc DoubleFn, LibFunc FloatFn,
124 LibFunc LongDoubleFn) {
125 switch (Ty->getTypeID()) {
126 case Type::FloatTyID:
127 return TLI->has(FloatFn);
128 case Type::DoubleTyID:
129 return TLI->has(DoubleFn);
131 return TLI->has(LongDoubleFn);
135 //===----------------------------------------------------------------------===//
136 // String and Memory Library Call Optimizations
137 //===----------------------------------------------------------------------===//
139 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
140 // Extract some information from the instruction
141 Value *Dst = CI->getArgOperand(0);
142 Value *Src = CI->getArgOperand(1);
144 // See if we can get the length of the input string.
145 uint64_t Len = GetStringLength(Src);
148 --Len; // Unbias length.
150 // Handle the simple, do-nothing case: strcat(x, "") -> x
154 return emitStrLenMemCpy(Src, Dst, Len, B);
157 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
159 // We need to find the end of the destination string. That's where the
160 // memory is to be moved to. We just generate a call to strlen.
161 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
165 // Now that we have the destination's length, we must index into the
166 // destination's pointer to get the actual memcpy destination (end of
167 // the string .. we're concatenating).
168 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
170 // We have enough information to now generate the memcpy call to do the
171 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
172 B.CreateMemCpy(CpyDst, Src,
173 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
178 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
179 // Extract some information from the instruction.
180 Value *Dst = CI->getArgOperand(0);
181 Value *Src = CI->getArgOperand(1);
184 // We don't do anything if length is not constant.
185 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
186 Len = LengthArg->getZExtValue();
190 // See if we can get the length of the input string.
191 uint64_t SrcLen = GetStringLength(Src);
194 --SrcLen; // Unbias length.
196 // Handle the simple, do-nothing cases:
197 // strncat(x, "", c) -> x
198 // strncat(x, c, 0) -> x
199 if (SrcLen == 0 || Len == 0)
202 // We don't optimize this case.
206 // strncat(x, s, c) -> strcat(x, s)
207 // s is constant so the strcat can be optimized further.
208 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
211 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
212 Function *Callee = CI->getCalledFunction();
213 FunctionType *FT = Callee->getFunctionType();
214 Value *SrcStr = CI->getArgOperand(0);
216 // If the second operand is non-constant, see if we can compute the length
217 // of the input string and turn this into memchr.
218 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
220 uint64_t Len = GetStringLength(SrcStr);
221 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
224 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
225 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
229 // Otherwise, the character is a constant, see if the first argument is
230 // a string literal. If so, we can constant fold.
232 if (!getConstantStringInfo(SrcStr, Str)) {
233 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
234 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
239 // Compute the offset, make sure to handle the case when we're searching for
240 // zero (a weird way to spell strlen).
241 size_t I = (0xFF & CharC->getSExtValue()) == 0
243 : Str.find(CharC->getSExtValue());
244 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
245 return Constant::getNullValue(CI->getType());
247 // strchr(s+n,c) -> gep(s+n+i,c)
248 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
251 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
252 Value *SrcStr = CI->getArgOperand(0);
253 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
255 // Cannot fold anything if we're not looking for a constant.
260 if (!getConstantStringInfo(SrcStr, Str)) {
261 // strrchr(s, 0) -> strchr(s, 0)
263 return emitStrChr(SrcStr, '\0', B, TLI);
267 // Compute the offset.
268 size_t I = (0xFF & CharC->getSExtValue()) == 0
270 : Str.rfind(CharC->getSExtValue());
271 if (I == StringRef::npos) // Didn't find the char. Return null.
272 return Constant::getNullValue(CI->getType());
274 // strrchr(s+n,c) -> gep(s+n+i,c)
275 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
278 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
279 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
280 if (Str1P == Str2P) // strcmp(x,x) -> 0
281 return ConstantInt::get(CI->getType(), 0);
283 StringRef Str1, Str2;
284 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
285 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
287 // strcmp(x, y) -> cnst (if both x and y are constant strings)
288 if (HasStr1 && HasStr2)
289 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
291 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
293 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
295 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
296 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
298 // strcmp(P, "x") -> memcmp(P, "x", 2)
299 uint64_t Len1 = GetStringLength(Str1P);
300 uint64_t Len2 = GetStringLength(Str2P);
302 return emitMemCmp(Str1P, Str2P,
303 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
304 std::min(Len1, Len2)),
311 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
312 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
313 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
314 return ConstantInt::get(CI->getType(), 0);
316 // Get the length argument if it is constant.
318 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
319 Length = LengthArg->getZExtValue();
323 if (Length == 0) // strncmp(x,y,0) -> 0
324 return ConstantInt::get(CI->getType(), 0);
326 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
327 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
329 StringRef Str1, Str2;
330 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
331 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
333 // strncmp(x, y) -> cnst (if both x and y are constant strings)
334 if (HasStr1 && HasStr2) {
335 StringRef SubStr1 = Str1.substr(0, Length);
336 StringRef SubStr2 = Str2.substr(0, Length);
337 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
340 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
342 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
344 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
345 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
350 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
351 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
352 if (Dst == Src) // strcpy(x,x) -> x
355 // See if we can get the length of the input string.
356 uint64_t Len = GetStringLength(Src);
360 // We have enough information to now generate the memcpy call to do the
361 // copy for us. Make a memcpy to copy the nul byte with align = 1.
362 B.CreateMemCpy(Dst, Src,
363 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
367 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
368 Function *Callee = CI->getCalledFunction();
369 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
370 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
371 Value *StrLen = emitStrLen(Src, B, DL, TLI);
372 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
375 // See if we can get the length of the input string.
376 uint64_t Len = GetStringLength(Src);
380 Type *PT = Callee->getFunctionType()->getParamType(0);
381 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
382 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
383 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
385 // We have enough information to now generate the memcpy call to do the
386 // copy for us. Make a memcpy to copy the nul byte with align = 1.
387 B.CreateMemCpy(Dst, Src, LenV, 1);
391 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
392 Function *Callee = CI->getCalledFunction();
393 Value *Dst = CI->getArgOperand(0);
394 Value *Src = CI->getArgOperand(1);
395 Value *LenOp = CI->getArgOperand(2);
397 // See if we can get the length of the input string.
398 uint64_t SrcLen = GetStringLength(Src);
404 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
405 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
410 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
411 Len = LengthArg->getZExtValue();
416 return Dst; // strncpy(x, y, 0) -> x
418 // Let strncpy handle the zero padding
419 if (Len > SrcLen + 1)
422 Type *PT = Callee->getFunctionType()->getParamType(0);
423 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
424 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
429 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
430 Value *Src = CI->getArgOperand(0);
432 // Constant folding: strlen("xyz") -> 3
433 if (uint64_t Len = GetStringLength(Src))
434 return ConstantInt::get(CI->getType(), Len - 1);
436 // If s is a constant pointer pointing to a string literal, we can fold
437 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
438 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
439 // We only try to simplify strlen when the pointer s points to an array
440 // of i8. Otherwise, we would need to scale the offset x before doing the
441 // subtraction. This will make the optimization more complex, and it's not
442 // very useful because calling strlen for a pointer of other types is
444 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
445 if (!isGEPBasedOnPointerToString(GEP))
449 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
450 size_t NullTermIdx = Str.find('\0');
452 // If the string does not have '\0', leave it to strlen to compute
454 if (NullTermIdx == StringRef::npos)
457 Value *Offset = GEP->getOperand(2);
458 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
459 KnownBits Known(BitWidth);
460 computeKnownBits(Offset, Known, DL, 0, nullptr, CI, nullptr);
461 Known.Zero.flipAllBits();
463 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
465 // KnownZero's bits are flipped, so zeros in KnownZero now represent
466 // bits known to be zeros in Offset, and ones in KnowZero represent
467 // bits unknown in Offset. Therefore, Offset is known to be in range
468 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
469 // unsigned-less-than NullTermIdx.
471 // If Offset is not provably in the range [0, NullTermIdx], we can still
472 // optimize if we can prove that the program has undefined behavior when
473 // Offset is outside that range. That is the case when GEP->getOperand(0)
474 // is a pointer to an object whose memory extent is NullTermIdx+1.
475 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
476 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
477 NullTermIdx == ArrSize - 1))
478 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
485 // strlen(x?"foo":"bars") --> x ? 3 : 4
486 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
487 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
488 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
489 if (LenTrue && LenFalse) {
490 Function *Caller = CI->getParent()->getParent();
491 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
493 "folded strlen(select) to select of constants");
494 return B.CreateSelect(SI->getCondition(),
495 ConstantInt::get(CI->getType(), LenTrue - 1),
496 ConstantInt::get(CI->getType(), LenFalse - 1));
500 // strlen(x) != 0 --> *x != 0
501 // strlen(x) == 0 --> *x == 0
502 if (isOnlyUsedInZeroEqualityComparison(CI))
503 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
508 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
510 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
511 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
513 // strpbrk(s, "") -> nullptr
514 // strpbrk("", s) -> nullptr
515 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
516 return Constant::getNullValue(CI->getType());
519 if (HasS1 && HasS2) {
520 size_t I = S1.find_first_of(S2);
521 if (I == StringRef::npos) // No match.
522 return Constant::getNullValue(CI->getType());
524 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
528 // strpbrk(s, "a") -> strchr(s, 'a')
529 if (HasS2 && S2.size() == 1)
530 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
535 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
536 Value *EndPtr = CI->getArgOperand(1);
537 if (isa<ConstantPointerNull>(EndPtr)) {
538 // With a null EndPtr, this function won't capture the main argument.
539 // It would be readonly too, except that it still may write to errno.
540 CI->addAttribute(1, Attribute::NoCapture);
546 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
548 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
549 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
551 // strspn(s, "") -> 0
552 // strspn("", s) -> 0
553 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
554 return Constant::getNullValue(CI->getType());
557 if (HasS1 && HasS2) {
558 size_t Pos = S1.find_first_not_of(S2);
559 if (Pos == StringRef::npos)
561 return ConstantInt::get(CI->getType(), Pos);
567 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
569 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
570 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
572 // strcspn("", s) -> 0
573 if (HasS1 && S1.empty())
574 return Constant::getNullValue(CI->getType());
577 if (HasS1 && HasS2) {
578 size_t Pos = S1.find_first_of(S2);
579 if (Pos == StringRef::npos)
581 return ConstantInt::get(CI->getType(), Pos);
584 // strcspn(s, "") -> strlen(s)
585 if (HasS2 && S2.empty())
586 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
591 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
592 // fold strstr(x, x) -> x.
593 if (CI->getArgOperand(0) == CI->getArgOperand(1))
594 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
596 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
597 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
598 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
601 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
605 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
606 ICmpInst *Old = cast<ICmpInst>(*UI++);
608 B.CreateICmp(Old->getPredicate(), StrNCmp,
609 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
610 replaceAllUsesWith(Old, Cmp);
615 // See if either input string is a constant string.
616 StringRef SearchStr, ToFindStr;
617 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
618 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
620 // fold strstr(x, "") -> x.
621 if (HasStr2 && ToFindStr.empty())
622 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
624 // If both strings are known, constant fold it.
625 if (HasStr1 && HasStr2) {
626 size_t Offset = SearchStr.find(ToFindStr);
628 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
629 return Constant::getNullValue(CI->getType());
631 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
632 Value *Result = castToCStr(CI->getArgOperand(0), B);
633 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
634 return B.CreateBitCast(Result, CI->getType());
637 // fold strstr(x, "y") -> strchr(x, 'y').
638 if (HasStr2 && ToFindStr.size() == 1) {
639 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
640 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
645 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
646 Value *SrcStr = CI->getArgOperand(0);
647 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
648 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
650 // memchr(x, y, 0) -> null
651 if (LenC && LenC->isNullValue())
652 return Constant::getNullValue(CI->getType());
654 // From now on we need at least constant length and string.
656 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
659 // Truncate the string to LenC. If Str is smaller than LenC we will still only
660 // scan the string, as reading past the end of it is undefined and we can just
661 // return null if we don't find the char.
662 Str = Str.substr(0, LenC->getZExtValue());
664 // If the char is variable but the input str and length are not we can turn
665 // this memchr call into a simple bit field test. Of course this only works
666 // when the return value is only checked against null.
668 // It would be really nice to reuse switch lowering here but we can't change
669 // the CFG at this point.
671 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
672 // after bounds check.
673 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
675 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
676 reinterpret_cast<const unsigned char *>(Str.end()));
678 // Make sure the bit field we're about to create fits in a register on the
680 // FIXME: On a 64 bit architecture this prevents us from using the
681 // interesting range of alpha ascii chars. We could do better by emitting
682 // two bitfields or shifting the range by 64 if no lower chars are used.
683 if (!DL.fitsInLegalInteger(Max + 1))
686 // For the bit field use a power-of-2 type with at least 8 bits to avoid
687 // creating unnecessary illegal types.
688 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
690 // Now build the bit field.
691 APInt Bitfield(Width, 0);
693 Bitfield.setBit((unsigned char)C);
694 Value *BitfieldC = B.getInt(Bitfield);
696 // First check that the bit field access is within bounds.
697 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
698 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
701 // Create code that checks if the given bit is set in the field.
702 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
703 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
705 // Finally merge both checks and cast to pointer type. The inttoptr
706 // implicitly zexts the i1 to intptr type.
707 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
710 // Check if all arguments are constants. If so, we can constant fold.
714 // Compute the offset.
715 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
716 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
717 return Constant::getNullValue(CI->getType());
719 // memchr(s+n,c,l) -> gep(s+n+i,c)
720 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
723 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
724 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
726 if (LHS == RHS) // memcmp(s,s,x) -> 0
727 return Constant::getNullValue(CI->getType());
729 // Make sure we have a constant length.
730 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
733 uint64_t Len = LenC->getZExtValue();
735 if (Len == 0) // memcmp(s1,s2,0) -> 0
736 return Constant::getNullValue(CI->getType());
738 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
740 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
741 CI->getType(), "lhsv");
742 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
743 CI->getType(), "rhsv");
744 return B.CreateSub(LHSV, RHSV, "chardiff");
747 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
748 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
750 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
751 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
753 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
754 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
757 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
759 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
762 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
764 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
766 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
770 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
771 StringRef LHSStr, RHSStr;
772 if (getConstantStringInfo(LHS, LHSStr) &&
773 getConstantStringInfo(RHS, RHSStr)) {
774 // Make sure we're not reading out-of-bounds memory.
775 if (Len > LHSStr.size() || Len > RHSStr.size())
777 // Fold the memcmp and normalize the result. This way we get consistent
778 // results across multiple platforms.
780 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
785 return ConstantInt::get(CI->getType(), Ret);
791 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
792 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
793 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
794 CI->getArgOperand(2), 1);
795 return CI->getArgOperand(0);
798 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
799 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
800 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
801 CI->getArgOperand(2), 1);
802 return CI->getArgOperand(0);
805 // TODO: Does this belong in BuildLibCalls or should all of those similar
806 // functions be moved here?
807 static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
808 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
810 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
813 Module *M = B.GetInsertBlock()->getModule();
814 const DataLayout &DL = M->getDataLayout();
815 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
816 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
818 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
820 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
821 CI->setCallingConv(F->getCallingConv());
826 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
827 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
828 const TargetLibraryInfo &TLI) {
829 // This has to be a memset of zeros (bzero).
830 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
831 if (!FillValue || FillValue->getZExtValue() != 0)
834 // TODO: We should handle the case where the malloc has more than one use.
835 // This is necessary to optimize common patterns such as when the result of
836 // the malloc is checked against null or when a memset intrinsic is used in
837 // place of a memset library call.
838 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
839 if (!Malloc || !Malloc->hasOneUse())
842 // Is the inner call really malloc()?
843 Function *InnerCallee = Malloc->getCalledFunction();
848 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
849 Func != LibFunc_malloc)
852 // The memset must cover the same number of bytes that are malloc'd.
853 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
856 // Replace the malloc with a calloc. We need the data layout to know what the
857 // actual size of a 'size_t' parameter is.
858 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
859 const DataLayout &DL = Malloc->getModule()->getDataLayout();
860 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
861 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
862 Malloc->getArgOperand(0), Malloc->getAttributes(),
867 Malloc->replaceAllUsesWith(Calloc);
868 Malloc->eraseFromParent();
873 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
874 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
877 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
878 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
879 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
880 return CI->getArgOperand(0);
883 //===----------------------------------------------------------------------===//
884 // Math Library Optimizations
885 //===----------------------------------------------------------------------===//
887 /// Return a variant of Val with float type.
888 /// Currently this works in two cases: If Val is an FPExtension of a float
889 /// value to something bigger, simply return the operand.
890 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
891 /// loss of precision do so.
892 static Value *valueHasFloatPrecision(Value *Val) {
893 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
894 Value *Op = Cast->getOperand(0);
895 if (Op->getType()->isFloatTy())
898 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
899 APFloat F = Const->getValueAPF();
901 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
904 return ConstantFP::get(Const->getContext(), F);
909 /// Shrink double -> float for unary functions like 'floor'.
910 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
912 Function *Callee = CI->getCalledFunction();
913 // We know this libcall has a valid prototype, but we don't know which.
914 if (!CI->getType()->isDoubleTy())
918 // Check if all the uses for function like 'sin' are converted to float.
919 for (User *U : CI->users()) {
920 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
921 if (!Cast || !Cast->getType()->isFloatTy())
926 // If this is something like 'floor((double)floatval)', convert to floorf.
927 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
931 // If call isn't an intrinsic, check that it isn't within a function with the
932 // same name as the float version of this call.
934 // e.g. inline float expf(float val) { return (float) exp((double) val); }
936 // A similar such definition exists in the MinGW-w64 math.h header file which
937 // when compiled with -O2 -ffast-math causes the generation of infinite loops
938 // where expf is called.
939 if (!Callee->isIntrinsic()) {
940 const Function *F = CI->getFunction();
941 StringRef FName = F->getName();
942 StringRef CalleeName = Callee->getName();
943 if ((FName.size() == (CalleeName.size() + 1)) &&
944 (FName.back() == 'f') &&
945 FName.startswith(CalleeName))
949 // Propagate fast-math flags from the existing call to the new call.
950 IRBuilder<>::FastMathFlagGuard Guard(B);
951 B.setFastMathFlags(CI->getFastMathFlags());
953 // floor((double)floatval) -> (double)floorf(floatval)
954 if (Callee->isIntrinsic()) {
955 Module *M = CI->getModule();
956 Intrinsic::ID IID = Callee->getIntrinsicID();
957 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
958 V = B.CreateCall(F, V);
960 // The call is a library call rather than an intrinsic.
961 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
964 return B.CreateFPExt(V, B.getDoubleTy());
967 // Replace a libcall \p CI with a call to intrinsic \p IID
968 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
969 // Propagate fast-math flags from the existing call to the new call.
970 IRBuilder<>::FastMathFlagGuard Guard(B);
971 B.setFastMathFlags(CI->getFastMathFlags());
973 Module *M = CI->getModule();
974 Value *V = CI->getArgOperand(0);
975 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
976 CallInst *NewCall = B.CreateCall(F, V);
977 NewCall->takeName(CI);
981 /// Shrink double -> float for binary functions like 'fmin/fmax'.
982 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
983 Function *Callee = CI->getCalledFunction();
984 // We know this libcall has a valid prototype, but we don't know which.
985 if (!CI->getType()->isDoubleTy())
988 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
989 // or fmin(1.0, (double)floatval), then we convert it to fminf.
990 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
993 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
997 // Propagate fast-math flags from the existing call to the new call.
998 IRBuilder<>::FastMathFlagGuard Guard(B);
999 B.setFastMathFlags(CI->getFastMathFlags());
1001 // fmin((double)floatval1, (double)floatval2)
1002 // -> (double)fminf(floatval1, floatval2)
1003 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1004 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1005 Callee->getAttributes());
1006 return B.CreateFPExt(V, B.getDoubleTy());
1009 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1010 Function *Callee = CI->getCalledFunction();
1011 Value *Ret = nullptr;
1012 StringRef Name = Callee->getName();
1013 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1014 Ret = optimizeUnaryDoubleFP(CI, B, true);
1016 // cos(-x) -> cos(x)
1017 Value *Op1 = CI->getArgOperand(0);
1018 if (BinaryOperator::isFNeg(Op1)) {
1019 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1020 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1025 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1026 // Multiplications calculated using Addition Chains.
1027 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1029 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1031 if (InnerChain[Exp])
1032 return InnerChain[Exp];
1034 static const unsigned AddChain[33][2] = {
1036 {0, 0}, // Unused (base case = pow1).
1037 {1, 1}, // Unused (pre-computed).
1038 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1039 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1040 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1041 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1042 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1045 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1046 getPow(InnerChain, AddChain[Exp][1], B));
1047 return InnerChain[Exp];
1050 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1051 Function *Callee = CI->getCalledFunction();
1052 Value *Ret = nullptr;
1053 StringRef Name = Callee->getName();
1054 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1055 Ret = optimizeUnaryDoubleFP(CI, B, true);
1057 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1059 // pow(1.0, x) -> 1.0
1060 if (match(Op1, m_SpecificFP(1.0)))
1062 // pow(2.0, x) -> llvm.exp2(x)
1063 if (match(Op1, m_SpecificFP(2.0))) {
1064 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1066 return B.CreateCall(Exp2, Op2, "exp2");
1069 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1071 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1072 // pow(10.0, x) -> exp10(x)
1073 if (Op1C->isExactlyValue(10.0) &&
1074 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1076 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
1077 Callee->getAttributes());
1080 // pow(exp(x), y) -> exp(x * y)
1081 // pow(exp2(x), y) -> exp2(x * y)
1082 // We enable these only with fast-math. Besides rounding differences, the
1083 // transformation changes overflow and underflow behavior quite dramatically.
1084 // Example: x = 1000, y = 0.001.
1085 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1086 auto *OpC = dyn_cast<CallInst>(Op1);
1087 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1089 Function *OpCCallee = OpC->getCalledFunction();
1090 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1091 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
1092 IRBuilder<>::FastMathFlagGuard Guard(B);
1093 B.setFastMathFlags(CI->getFastMathFlags());
1094 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1095 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1096 OpCCallee->getAttributes());
1100 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1104 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1105 return ConstantFP::get(CI->getType(), 1.0);
1107 if (Op2C->isExactlyValue(-0.5) &&
1108 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1111 // pow(x, -0.5) -> 1.0 / sqrt(x)
1112 if (CI->hasUnsafeAlgebra()) {
1113 IRBuilder<>::FastMathFlagGuard Guard(B);
1114 B.setFastMathFlags(CI->getFastMathFlags());
1116 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1117 // intrinsic, so we match errno semantics. We also should check that the
1118 // target can in fact lower the sqrt intrinsic -- we currently have no way
1119 // to ask this question other than asking whether the target has a sqrt
1120 // libcall, which is a sufficient but not necessary condition.
1121 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
1122 Callee->getAttributes());
1124 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1128 if (Op2C->isExactlyValue(0.5) &&
1129 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1132 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1133 if (CI->hasUnsafeAlgebra()) {
1134 IRBuilder<>::FastMathFlagGuard Guard(B);
1135 B.setFastMathFlags(CI->getFastMathFlags());
1137 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1138 // intrinsic, to match errno semantics.
1139 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
1140 Callee->getAttributes());
1143 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1144 // This is faster than calling pow, and still handles negative zero
1145 // and negative infinity correctly.
1146 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1147 Value *Inf = ConstantFP::getInfinity(CI->getType());
1148 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1150 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1151 // intrinsic, to match errno semantics.
1152 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1154 Module *M = Callee->getParent();
1155 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1157 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1159 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1160 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1164 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1166 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1167 return B.CreateFMul(Op1, Op1, "pow2");
1168 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1169 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1171 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
1172 if (CI->hasUnsafeAlgebra()) {
1173 APFloat V = abs(Op2C->getValueAPF());
1174 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1175 // This transformation applies to integer exponents only.
1176 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1180 // Propagate fast math flags.
1181 IRBuilder<>::FastMathFlagGuard Guard(B);
1182 B.setFastMathFlags(CI->getFastMathFlags());
1184 // We will memoize intermediate products of the Addition Chain.
1185 Value *InnerChain[33] = {nullptr};
1186 InnerChain[1] = Op1;
1187 InnerChain[2] = B.CreateFMul(Op1, Op1);
1189 // We cannot readily convert a non-double type (like float) to a double.
1190 // So we first convert V to something which could be converted to double.
1192 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
1194 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1195 // For negative exponents simply compute the reciprocal.
1196 if (Op2C->isNegative())
1197 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1204 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1205 Function *Callee = CI->getCalledFunction();
1206 Value *Ret = nullptr;
1207 StringRef Name = Callee->getName();
1208 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1209 Ret = optimizeUnaryDoubleFP(CI, B, true);
1211 Value *Op = CI->getArgOperand(0);
1212 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1213 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1214 LibFunc LdExp = LibFunc_ldexpl;
1215 if (Op->getType()->isFloatTy())
1216 LdExp = LibFunc_ldexpf;
1217 else if (Op->getType()->isDoubleTy())
1218 LdExp = LibFunc_ldexp;
1220 if (TLI->has(LdExp)) {
1221 Value *LdExpArg = nullptr;
1222 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1223 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1224 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1225 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1226 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1227 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1231 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1232 if (!Op->getType()->isFloatTy())
1233 One = ConstantExpr::getFPExtend(One, Op->getType());
1235 Module *M = CI->getModule();
1237 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1238 Op->getType(), B.getInt32Ty());
1239 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1240 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1241 CI->setCallingConv(F->getCallingConv());
1249 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1250 Function *Callee = CI->getCalledFunction();
1251 // If we can shrink the call to a float function rather than a double
1252 // function, do that first.
1253 StringRef Name = Callee->getName();
1254 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1255 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1258 IRBuilder<>::FastMathFlagGuard Guard(B);
1260 if (CI->hasUnsafeAlgebra()) {
1261 // Unsafe algebra sets all fast-math-flags to true.
1262 FMF.setUnsafeAlgebra();
1264 // At a minimum, no-nans-fp-math must be true.
1265 if (!CI->hasNoNaNs())
1267 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1268 // "Ideally, fmax would be sensitive to the sign of zero, for example
1269 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1270 // might be impractical."
1271 FMF.setNoSignedZeros();
1274 B.setFastMathFlags(FMF);
1276 // We have a relaxed floating-point environment. We can ignore NaN-handling
1277 // and transform to a compare and select. We do not have to consider errno or
1278 // exceptions, because fmin/fmax do not have those.
1279 Value *Op0 = CI->getArgOperand(0);
1280 Value *Op1 = CI->getArgOperand(1);
1281 Value *Cmp = Callee->getName().startswith("fmin") ?
1282 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1283 return B.CreateSelect(Cmp, Op0, Op1);
1286 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1287 Function *Callee = CI->getCalledFunction();
1288 Value *Ret = nullptr;
1289 StringRef Name = Callee->getName();
1290 if (UnsafeFPShrink && hasFloatVersion(Name))
1291 Ret = optimizeUnaryDoubleFP(CI, B, true);
1293 if (!CI->hasUnsafeAlgebra())
1295 Value *Op1 = CI->getArgOperand(0);
1296 auto *OpC = dyn_cast<CallInst>(Op1);
1298 // The earlier call must also be unsafe in order to do these transforms.
1299 if (!OpC || !OpC->hasUnsafeAlgebra())
1302 // log(pow(x,y)) -> y*log(x)
1303 // This is only applicable to log, log2, log10.
1304 if (Name != "log" && Name != "log2" && Name != "log10")
1307 IRBuilder<>::FastMathFlagGuard Guard(B);
1309 FMF.setUnsafeAlgebra();
1310 B.setFastMathFlags(FMF);
1313 Function *F = OpC->getCalledFunction();
1314 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1315 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1316 return B.CreateFMul(OpC->getArgOperand(1),
1317 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1318 Callee->getAttributes()), "mul");
1320 // log(exp2(y)) -> y*log(2)
1321 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1322 TLI->has(Func) && Func == LibFunc_exp2)
1323 return B.CreateFMul(
1324 OpC->getArgOperand(0),
1325 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1326 Callee->getName(), B, Callee->getAttributes()),
1331 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1332 Function *Callee = CI->getCalledFunction();
1333 Value *Ret = nullptr;
1334 // TODO: Once we have a way (other than checking for the existince of the
1335 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1337 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1338 Callee->getIntrinsicID() == Intrinsic::sqrt))
1339 Ret = optimizeUnaryDoubleFP(CI, B, true);
1341 if (!CI->hasUnsafeAlgebra())
1344 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1345 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1348 // We're looking for a repeated factor in a multiplication tree,
1349 // so we can do this fold: sqrt(x * x) -> fabs(x);
1350 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1351 Value *Op0 = I->getOperand(0);
1352 Value *Op1 = I->getOperand(1);
1353 Value *RepeatOp = nullptr;
1354 Value *OtherOp = nullptr;
1356 // Simple match: the operands of the multiply are identical.
1359 // Look for a more complicated pattern: one of the operands is itself
1360 // a multiply, so search for a common factor in that multiply.
1361 // Note: We don't bother looking any deeper than this first level or for
1362 // variations of this pattern because instcombine's visitFMUL and/or the
1363 // reassociation pass should give us this form.
1364 Value *OtherMul0, *OtherMul1;
1365 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1366 // Pattern: sqrt((x * y) * z)
1367 if (OtherMul0 == OtherMul1 &&
1368 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
1369 // Matched: sqrt((x * x) * z)
1370 RepeatOp = OtherMul0;
1378 // Fast math flags for any created instructions should match the sqrt
1380 IRBuilder<>::FastMathFlagGuard Guard(B);
1381 B.setFastMathFlags(I->getFastMathFlags());
1383 // If we found a repeated factor, hoist it out of the square root and
1384 // replace it with the fabs of that factor.
1385 Module *M = Callee->getParent();
1386 Type *ArgType = I->getType();
1387 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1388 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1390 // If we found a non-repeated factor, we still need to get its square
1391 // root. We then multiply that by the value that was simplified out
1392 // of the square root calculation.
1393 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1394 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1395 return B.CreateFMul(FabsCall, SqrtCall);
1400 // TODO: Generalize to handle any trig function and its inverse.
1401 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1402 Function *Callee = CI->getCalledFunction();
1403 Value *Ret = nullptr;
1404 StringRef Name = Callee->getName();
1405 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1406 Ret = optimizeUnaryDoubleFP(CI, B, true);
1408 Value *Op1 = CI->getArgOperand(0);
1409 auto *OpC = dyn_cast<CallInst>(Op1);
1413 // Both calls must allow unsafe optimizations in order to remove them.
1414 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1417 // tan(atan(x)) -> x
1418 // tanf(atanf(x)) -> x
1419 // tanl(atanl(x)) -> x
1421 Function *F = OpC->getCalledFunction();
1422 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1423 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1424 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1425 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1426 Ret = OpC->getArgOperand(0);
1430 static bool isTrigLibCall(CallInst *CI) {
1431 // We can only hope to do anything useful if we can ignore things like errno
1432 // and floating-point exceptions.
1433 // We already checked the prototype.
1434 return CI->hasFnAttr(Attribute::NoUnwind) &&
1435 CI->hasFnAttr(Attribute::ReadNone);
1438 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1439 bool UseFloat, Value *&Sin, Value *&Cos,
1441 Type *ArgTy = Arg->getType();
1445 Triple T(OrigCallee->getParent()->getTargetTriple());
1447 Name = "__sincospif_stret";
1449 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1450 // x86_64 can't use {float, float} since that would be returned in both
1451 // xmm0 and xmm1, which isn't what a real struct would do.
1452 ResTy = T.getArch() == Triple::x86_64
1453 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1454 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1456 Name = "__sincospi_stret";
1457 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1460 Module *M = OrigCallee->getParent();
1461 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1464 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1465 // If the argument is an instruction, it must dominate all uses so put our
1466 // sincos call there.
1467 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1469 // Otherwise (e.g. for a constant) the beginning of the function is as
1470 // good a place as any.
1471 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1472 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1475 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1477 if (SinCos->getType()->isStructTy()) {
1478 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1479 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1481 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1483 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1488 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1489 // Make sure the prototype is as expected, otherwise the rest of the
1490 // function is probably invalid and likely to abort.
1491 if (!isTrigLibCall(CI))
1494 Value *Arg = CI->getArgOperand(0);
1495 SmallVector<CallInst *, 1> SinCalls;
1496 SmallVector<CallInst *, 1> CosCalls;
1497 SmallVector<CallInst *, 1> SinCosCalls;
1499 bool IsFloat = Arg->getType()->isFloatTy();
1501 // Look for all compatible sinpi, cospi and sincospi calls with the same
1502 // argument. If there are enough (in some sense) we can make the
1504 Function *F = CI->getFunction();
1505 for (User *U : Arg->users())
1506 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1508 // It's only worthwhile if both sinpi and cospi are actually used.
1509 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1512 Value *Sin, *Cos, *SinCos;
1513 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1515 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1517 for (CallInst *C : Calls)
1518 replaceAllUsesWith(C, Res);
1521 replaceTrigInsts(SinCalls, Sin);
1522 replaceTrigInsts(CosCalls, Cos);
1523 replaceTrigInsts(SinCosCalls, SinCos);
1528 void LibCallSimplifier::classifyArgUse(
1529 Value *Val, Function *F, bool IsFloat,
1530 SmallVectorImpl<CallInst *> &SinCalls,
1531 SmallVectorImpl<CallInst *> &CosCalls,
1532 SmallVectorImpl<CallInst *> &SinCosCalls) {
1533 CallInst *CI = dyn_cast<CallInst>(Val);
1538 // Don't consider calls in other functions.
1539 if (CI->getFunction() != F)
1542 Function *Callee = CI->getCalledFunction();
1544 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1549 if (Func == LibFunc_sinpif)
1550 SinCalls.push_back(CI);
1551 else if (Func == LibFunc_cospif)
1552 CosCalls.push_back(CI);
1553 else if (Func == LibFunc_sincospif_stret)
1554 SinCosCalls.push_back(CI);
1556 if (Func == LibFunc_sinpi)
1557 SinCalls.push_back(CI);
1558 else if (Func == LibFunc_cospi)
1559 CosCalls.push_back(CI);
1560 else if (Func == LibFunc_sincospi_stret)
1561 SinCosCalls.push_back(CI);
1565 //===----------------------------------------------------------------------===//
1566 // Integer Library Call Optimizations
1567 //===----------------------------------------------------------------------===//
1569 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1570 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1571 Value *Op = CI->getArgOperand(0);
1572 Type *ArgType = Op->getType();
1573 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1574 Intrinsic::cttz, ArgType);
1575 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1576 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1577 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1579 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1580 return B.CreateSelect(Cond, V, B.getInt32(0));
1583 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1584 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1585 Value *Op = CI->getArgOperand(0);
1586 Type *ArgType = Op->getType();
1587 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1588 Intrinsic::ctlz, ArgType);
1589 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1590 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1592 return B.CreateIntCast(V, CI->getType(), false);
1595 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1596 // abs(x) -> x >s -1 ? x : -x
1597 Value *Op = CI->getArgOperand(0);
1599 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1600 Value *Neg = B.CreateNeg(Op, "neg");
1601 return B.CreateSelect(Pos, Op, Neg);
1604 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1605 // isdigit(c) -> (c-'0') <u 10
1606 Value *Op = CI->getArgOperand(0);
1607 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1608 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1609 return B.CreateZExt(Op, CI->getType());
1612 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1613 // isascii(c) -> c <u 128
1614 Value *Op = CI->getArgOperand(0);
1615 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1616 return B.CreateZExt(Op, CI->getType());
1619 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1620 // toascii(c) -> c & 0x7f
1621 return B.CreateAnd(CI->getArgOperand(0),
1622 ConstantInt::get(CI->getType(), 0x7F));
1625 //===----------------------------------------------------------------------===//
1626 // Formatting and IO Library Call Optimizations
1627 //===----------------------------------------------------------------------===//
1629 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1631 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1633 Function *Callee = CI->getCalledFunction();
1634 // Error reporting calls should be cold, mark them as such.
1635 // This applies even to non-builtin calls: it is only a hint and applies to
1636 // functions that the frontend might not understand as builtins.
1638 // This heuristic was suggested in:
1639 // Improving Static Branch Prediction in a Compiler
1640 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1641 // Proceedings of PACT'98, Oct. 1998, IEEE
1642 if (!CI->hasFnAttr(Attribute::Cold) &&
1643 isReportingError(Callee, CI, StreamArg)) {
1644 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
1650 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1651 if (!Callee || !Callee->isDeclaration())
1657 // These functions might be considered cold, but only if their stream
1658 // argument is stderr.
1660 if (StreamArg >= (int)CI->getNumArgOperands())
1662 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1665 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1666 if (!GV || !GV->isDeclaration())
1668 return GV->getName() == "stderr";
1671 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1672 // Check for a fixed format string.
1673 StringRef FormatStr;
1674 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1677 // Empty format string -> noop.
1678 if (FormatStr.empty()) // Tolerate printf's declared void.
1679 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1681 // Do not do any of the following transformations if the printf return value
1682 // is used, in general the printf return value is not compatible with either
1683 // putchar() or puts().
1684 if (!CI->use_empty())
1687 // printf("x") -> putchar('x'), even for "%" and "%%".
1688 if (FormatStr.size() == 1 || FormatStr == "%%")
1689 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1691 // printf("%s", "a") --> putchar('a')
1692 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1694 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1696 if (ChrStr.size() != 1)
1698 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1701 // printf("foo\n") --> puts("foo")
1702 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1703 FormatStr.find('%') == StringRef::npos) { // No format characters.
1704 // Create a string literal with no \n on it. We expect the constant merge
1705 // pass to be run after this pass, to merge duplicate strings.
1706 FormatStr = FormatStr.drop_back();
1707 Value *GV = B.CreateGlobalString(FormatStr, "str");
1708 return emitPutS(GV, B, TLI);
1711 // Optimize specific format strings.
1712 // printf("%c", chr) --> putchar(chr)
1713 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1714 CI->getArgOperand(1)->getType()->isIntegerTy())
1715 return emitPutChar(CI->getArgOperand(1), B, TLI);
1717 // printf("%s\n", str) --> puts(str)
1718 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1719 CI->getArgOperand(1)->getType()->isPointerTy())
1720 return emitPutS(CI->getArgOperand(1), B, TLI);
1724 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1726 Function *Callee = CI->getCalledFunction();
1727 FunctionType *FT = Callee->getFunctionType();
1728 if (Value *V = optimizePrintFString(CI, B)) {
1732 // printf(format, ...) -> iprintf(format, ...) if no floating point
1734 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
1735 Module *M = B.GetInsertBlock()->getParent()->getParent();
1736 Constant *IPrintFFn =
1737 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1738 CallInst *New = cast<CallInst>(CI->clone());
1739 New->setCalledFunction(IPrintFFn);
1746 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1747 // Check for a fixed format string.
1748 StringRef FormatStr;
1749 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1752 // If we just have a format string (nothing else crazy) transform it.
1753 if (CI->getNumArgOperands() == 2) {
1754 // Make sure there's no % in the constant array. We could try to handle
1755 // %% -> % in the future if we cared.
1756 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1757 if (FormatStr[i] == '%')
1758 return nullptr; // we found a format specifier, bail out.
1760 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1761 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1762 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1763 FormatStr.size() + 1),
1764 1); // Copy the null byte.
1765 return ConstantInt::get(CI->getType(), FormatStr.size());
1768 // The remaining optimizations require the format string to be "%s" or "%c"
1769 // and have an extra operand.
1770 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1771 CI->getNumArgOperands() < 3)
1774 // Decode the second character of the format string.
1775 if (FormatStr[1] == 'c') {
1776 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1777 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1779 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1780 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1781 B.CreateStore(V, Ptr);
1782 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1783 B.CreateStore(B.getInt8(0), Ptr);
1785 return ConstantInt::get(CI->getType(), 1);
1788 if (FormatStr[1] == 's') {
1789 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1790 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1793 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1797 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1798 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1800 // The sprintf result is the unincremented number of bytes in the string.
1801 return B.CreateIntCast(Len, CI->getType(), false);
1806 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1807 Function *Callee = CI->getCalledFunction();
1808 FunctionType *FT = Callee->getFunctionType();
1809 if (Value *V = optimizeSPrintFString(CI, B)) {
1813 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1815 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
1816 Module *M = B.GetInsertBlock()->getParent()->getParent();
1817 Constant *SIPrintFFn =
1818 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1819 CallInst *New = cast<CallInst>(CI->clone());
1820 New->setCalledFunction(SIPrintFFn);
1827 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1828 optimizeErrorReporting(CI, B, 0);
1830 // All the optimizations depend on the format string.
1831 StringRef FormatStr;
1832 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1835 // Do not do any of the following transformations if the fprintf return
1836 // value is used, in general the fprintf return value is not compatible
1837 // with fwrite(), fputc() or fputs().
1838 if (!CI->use_empty())
1841 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1842 if (CI->getNumArgOperands() == 2) {
1843 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1844 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1845 return nullptr; // We found a format specifier.
1848 CI->getArgOperand(1),
1849 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1850 CI->getArgOperand(0), B, DL, TLI);
1853 // The remaining optimizations require the format string to be "%s" or "%c"
1854 // and have an extra operand.
1855 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1856 CI->getNumArgOperands() < 3)
1859 // Decode the second character of the format string.
1860 if (FormatStr[1] == 'c') {
1861 // fprintf(F, "%c", chr) --> fputc(chr, F)
1862 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1864 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1867 if (FormatStr[1] == 's') {
1868 // fprintf(F, "%s", str) --> fputs(str, F)
1869 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1871 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1876 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1877 Function *Callee = CI->getCalledFunction();
1878 FunctionType *FT = Callee->getFunctionType();
1879 if (Value *V = optimizeFPrintFString(CI, B)) {
1883 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1884 // floating point arguments.
1885 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
1886 Module *M = B.GetInsertBlock()->getParent()->getParent();
1887 Constant *FIPrintFFn =
1888 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1889 CallInst *New = cast<CallInst>(CI->clone());
1890 New->setCalledFunction(FIPrintFFn);
1897 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1898 optimizeErrorReporting(CI, B, 3);
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, TLI);
1916 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1922 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1923 optimizeErrorReporting(CI, B, 1);
1925 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1926 // requires more arguments and thus extra MOVs are required.
1927 if (CI->getParent()->getParent()->optForSize())
1930 // We can't optimize if return value is used.
1931 if (!CI->use_empty())
1934 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1935 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1939 // Known to have no uses (see above).
1941 CI->getArgOperand(0),
1942 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1943 CI->getArgOperand(1), B, DL, TLI);
1946 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1947 // Check for a constant string.
1949 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1952 if (Str.empty() && CI->use_empty()) {
1953 // puts("") -> putchar('\n')
1954 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
1955 if (CI->use_empty() || !Res)
1957 return B.CreateIntCast(Res, CI->getType(), true);
1963 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1965 SmallString<20> FloatFuncName = FuncName;
1966 FloatFuncName += 'f';
1967 if (TLI->getLibFunc(FloatFuncName, Func))
1968 return TLI->has(Func);
1972 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1973 IRBuilder<> &Builder) {
1975 Function *Callee = CI->getCalledFunction();
1976 // Check for string/memory library functions.
1977 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
1978 // Make sure we never change the calling convention.
1979 assert((ignoreCallingConv(Func) ||
1980 isCallingConvCCompatible(CI)) &&
1981 "Optimizing string/memory libcall would change the calling convention");
1983 case LibFunc_strcat:
1984 return optimizeStrCat(CI, Builder);
1985 case LibFunc_strncat:
1986 return optimizeStrNCat(CI, Builder);
1987 case LibFunc_strchr:
1988 return optimizeStrChr(CI, Builder);
1989 case LibFunc_strrchr:
1990 return optimizeStrRChr(CI, Builder);
1991 case LibFunc_strcmp:
1992 return optimizeStrCmp(CI, Builder);
1993 case LibFunc_strncmp:
1994 return optimizeStrNCmp(CI, Builder);
1995 case LibFunc_strcpy:
1996 return optimizeStrCpy(CI, Builder);
1997 case LibFunc_stpcpy:
1998 return optimizeStpCpy(CI, Builder);
1999 case LibFunc_strncpy:
2000 return optimizeStrNCpy(CI, Builder);
2001 case LibFunc_strlen:
2002 return optimizeStrLen(CI, Builder);
2003 case LibFunc_strpbrk:
2004 return optimizeStrPBrk(CI, Builder);
2005 case LibFunc_strtol:
2006 case LibFunc_strtod:
2007 case LibFunc_strtof:
2008 case LibFunc_strtoul:
2009 case LibFunc_strtoll:
2010 case LibFunc_strtold:
2011 case LibFunc_strtoull:
2012 return optimizeStrTo(CI, Builder);
2013 case LibFunc_strspn:
2014 return optimizeStrSpn(CI, Builder);
2015 case LibFunc_strcspn:
2016 return optimizeStrCSpn(CI, Builder);
2017 case LibFunc_strstr:
2018 return optimizeStrStr(CI, Builder);
2019 case LibFunc_memchr:
2020 return optimizeMemChr(CI, Builder);
2021 case LibFunc_memcmp:
2022 return optimizeMemCmp(CI, Builder);
2023 case LibFunc_memcpy:
2024 return optimizeMemCpy(CI, Builder);
2025 case LibFunc_memmove:
2026 return optimizeMemMove(CI, Builder);
2027 case LibFunc_memset:
2028 return optimizeMemSet(CI, Builder);
2036 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2037 if (CI->isNoBuiltin())
2041 Function *Callee = CI->getCalledFunction();
2042 StringRef FuncName = Callee->getName();
2044 SmallVector<OperandBundleDef, 2> OpBundles;
2045 CI->getOperandBundlesAsDefs(OpBundles);
2046 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2047 bool isCallingConvC = isCallingConvCCompatible(CI);
2049 // Command-line parameter overrides instruction attribute.
2050 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2051 UnsafeFPShrink = EnableUnsafeFPShrink;
2052 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
2053 UnsafeFPShrink = true;
2055 // First, check for intrinsics.
2056 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2057 if (!isCallingConvC)
2059 switch (II->getIntrinsicID()) {
2060 case Intrinsic::pow:
2061 return optimizePow(CI, Builder);
2062 case Intrinsic::exp2:
2063 return optimizeExp2(CI, Builder);
2064 case Intrinsic::log:
2065 return optimizeLog(CI, Builder);
2066 case Intrinsic::sqrt:
2067 return optimizeSqrt(CI, Builder);
2068 // TODO: Use foldMallocMemset() with memset intrinsic.
2074 // Also try to simplify calls to fortified library functions.
2075 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2076 // Try to further simplify the result.
2077 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2078 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2079 // Use an IR Builder from SimplifiedCI if available instead of CI
2080 // to guarantee we reach all uses we might replace later on.
2081 IRBuilder<> TmpBuilder(SimplifiedCI);
2082 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2083 // If we were able to further simplify, remove the now redundant call.
2084 SimplifiedCI->replaceAllUsesWith(V);
2085 SimplifiedCI->eraseFromParent();
2089 return SimplifiedFortifiedCI;
2092 // Then check for known library functions.
2093 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2094 // We never change the calling convention.
2095 if (!ignoreCallingConv(Func) && !isCallingConvC)
2097 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2103 return optimizeCos(CI, Builder);
2104 case LibFunc_sinpif:
2106 case LibFunc_cospif:
2108 return optimizeSinCosPi(CI, Builder);
2112 return optimizePow(CI, Builder);
2116 return optimizeExp2(CI, Builder);
2120 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2124 return optimizeSqrt(CI, Builder);
2128 return optimizeFFS(CI, Builder);
2132 return optimizeFls(CI, Builder);
2136 return optimizeAbs(CI, Builder);
2137 case LibFunc_isdigit:
2138 return optimizeIsDigit(CI, Builder);
2139 case LibFunc_isascii:
2140 return optimizeIsAscii(CI, Builder);
2141 case LibFunc_toascii:
2142 return optimizeToAscii(CI, Builder);
2143 case LibFunc_printf:
2144 return optimizePrintF(CI, Builder);
2145 case LibFunc_sprintf:
2146 return optimizeSPrintF(CI, Builder);
2147 case LibFunc_fprintf:
2148 return optimizeFPrintF(CI, Builder);
2149 case LibFunc_fwrite:
2150 return optimizeFWrite(CI, Builder);
2152 return optimizeFPuts(CI, Builder);
2158 return optimizeLog(CI, Builder);
2160 return optimizePuts(CI, Builder);
2164 return optimizeTan(CI, Builder);
2165 case LibFunc_perror:
2166 return optimizeErrorReporting(CI, Builder);
2167 case LibFunc_vfprintf:
2168 case LibFunc_fiprintf:
2169 return optimizeErrorReporting(CI, Builder, 0);
2171 return optimizeErrorReporting(CI, Builder, 1);
2173 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2175 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2177 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2178 case LibFunc_nearbyint:
2179 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2181 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2183 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2198 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2199 return optimizeUnaryDoubleFP(CI, Builder, true);
2201 case LibFunc_copysign:
2202 if (hasFloatVersion(FuncName))
2203 return optimizeBinaryDoubleFP(CI, Builder);
2211 return optimizeFMinFMax(CI, Builder);
2219 LibCallSimplifier::LibCallSimplifier(
2220 const DataLayout &DL, const TargetLibraryInfo *TLI,
2221 function_ref<void(Instruction *, Value *)> Replacer)
2222 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2223 Replacer(Replacer) {}
2225 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2226 // Indirect through the replacer used in this instance.
2231 // Additional cases that we need to add to this file:
2234 // * cbrt(expN(X)) -> expN(x/3)
2235 // * cbrt(sqrt(x)) -> pow(x,1/6)
2236 // * cbrt(cbrt(x)) -> pow(x,1/9)
2239 // * exp(log(x)) -> x
2242 // * log(exp(x)) -> x
2243 // * log(exp(y)) -> y*log(e)
2244 // * log(exp10(y)) -> y*log(10)
2245 // * log(sqrt(x)) -> 0.5*log(x)
2248 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2249 // * pow(pow(x,y),z)-> pow(x,y*z)
2252 // * signbit(cnst) -> cnst'
2253 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2255 // sqrt, sqrtf, sqrtl:
2256 // * sqrt(expN(x)) -> expN(x*0.5)
2257 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2258 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2261 //===----------------------------------------------------------------------===//
2262 // Fortified Library Call Optimizations
2263 //===----------------------------------------------------------------------===//
2265 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2269 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2271 if (ConstantInt *ObjSizeCI =
2272 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2273 if (ObjSizeCI->isAllOnesValue())
2275 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2276 if (OnlyLowerUnknownSize)
2279 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2280 // If the length is 0 we don't know how long it is and so we can't
2281 // remove the check.
2284 return ObjSizeCI->getZExtValue() >= Len;
2286 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2287 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2292 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2294 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2295 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2296 CI->getArgOperand(2), 1);
2297 return CI->getArgOperand(0);
2302 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2305 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2306 CI->getArgOperand(2), 1);
2307 return CI->getArgOperand(0);
2312 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2314 // TODO: Try foldMallocMemset() here.
2316 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2317 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2318 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2319 return CI->getArgOperand(0);
2324 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2327 Function *Callee = CI->getCalledFunction();
2328 StringRef Name = Callee->getName();
2329 const DataLayout &DL = CI->getModule()->getDataLayout();
2330 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2331 *ObjSize = CI->getArgOperand(2);
2333 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2334 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2335 Value *StrLen = emitStrLen(Src, B, DL, TLI);
2336 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2339 // If a) we don't have any length information, or b) we know this will
2340 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2341 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2342 // TODO: It might be nice to get a maximum length out of the possible
2343 // string lengths for varying.
2344 if (isFortifiedCallFoldable(CI, 2, 1, true))
2345 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2347 if (OnlyLowerUnknownSize)
2350 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2351 uint64_t Len = GetStringLength(Src);
2355 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2356 Value *LenV = ConstantInt::get(SizeTTy, Len);
2357 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2358 // If the function was an __stpcpy_chk, and we were able to fold it into
2359 // a __memcpy_chk, we still need to return the correct end pointer.
2360 if (Ret && Func == LibFunc_stpcpy_chk)
2361 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2365 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2368 Function *Callee = CI->getCalledFunction();
2369 StringRef Name = Callee->getName();
2370 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2371 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2372 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2378 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2379 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2380 // Some clang users checked for _chk libcall availability using:
2381 // __has_builtin(__builtin___memcpy_chk)
2382 // When compiling with -fno-builtin, this is always true.
2383 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2384 // end up with fortified libcalls, which isn't acceptable in a freestanding
2385 // environment which only provides their non-fortified counterparts.
2387 // Until we change clang and/or teach external users to check for availability
2388 // differently, disregard the "nobuiltin" attribute and TLI::has.
2393 Function *Callee = CI->getCalledFunction();
2395 SmallVector<OperandBundleDef, 2> OpBundles;
2396 CI->getOperandBundlesAsDefs(OpBundles);
2397 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2398 bool isCallingConvC = isCallingConvCCompatible(CI);
2400 // First, check that this is a known library functions and that the prototype
2402 if (!TLI->getLibFunc(*Callee, Func))
2405 // We never change the calling convention.
2406 if (!ignoreCallingConv(Func) && !isCallingConvC)
2410 case LibFunc_memcpy_chk:
2411 return optimizeMemCpyChk(CI, Builder);
2412 case LibFunc_memmove_chk:
2413 return optimizeMemMoveChk(CI, Builder);
2414 case LibFunc_memset_chk:
2415 return optimizeMemSetChk(CI, Builder);
2416 case LibFunc_stpcpy_chk:
2417 case LibFunc_strcpy_chk:
2418 return optimizeStrpCpyChk(CI, Builder, Func);
2419 case LibFunc_stpncpy_chk:
2420 case LibFunc_strncpy_chk:
2421 return optimizeStrpNCpyChk(CI, Builder, Func);
2428 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2429 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2430 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}