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/ConstantFolding.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.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"
36 #include "llvm/Transforms/Utils/Local.h"
39 using namespace PatternMatch;
42 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
57 static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
61 case llvm::CallingConv::C:
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
72 auto *FuncTy = CI->getFunctionType();
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
89 /// Return true if it is only used in equality comparisons with With.
90 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
91 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
93 if (IC->isEquality() && IC->getOperand(1) == With)
95 // Unknown instruction.
101 static bool callHasFloatingPointArgument(const CallInst *CI) {
102 return any_of(CI->operands(), [](const Use &OI) {
103 return OI->getType()->isFloatingPointTy();
107 /// \brief Check whether the overloaded unary floating point function
108 /// corresponding to \a Ty is available.
109 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
110 LibFunc DoubleFn, LibFunc FloatFn,
111 LibFunc LongDoubleFn) {
112 switch (Ty->getTypeID()) {
113 case Type::FloatTyID:
114 return TLI->has(FloatFn);
115 case Type::DoubleTyID:
116 return TLI->has(DoubleFn);
118 return TLI->has(LongDoubleFn);
122 //===----------------------------------------------------------------------===//
123 // String and Memory Library Call Optimizations
124 //===----------------------------------------------------------------------===//
126 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
127 // Extract some information from the instruction
128 Value *Dst = CI->getArgOperand(0);
129 Value *Src = CI->getArgOperand(1);
131 // See if we can get the length of the input string.
132 uint64_t Len = GetStringLength(Src);
135 --Len; // Unbias length.
137 // Handle the simple, do-nothing case: strcat(x, "") -> x
141 return emitStrLenMemCpy(Src, Dst, Len, B);
144 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
146 // We need to find the end of the destination string. That's where the
147 // memory is to be moved to. We just generate a call to strlen.
148 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
152 // Now that we have the destination's length, we must index into the
153 // destination's pointer to get the actual memcpy destination (end of
154 // the string .. we're concatenating).
155 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
157 // We have enough information to now generate the memcpy call to do the
158 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
159 B.CreateMemCpy(CpyDst, Src,
160 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
165 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
166 // Extract some information from the instruction.
167 Value *Dst = CI->getArgOperand(0);
168 Value *Src = CI->getArgOperand(1);
171 // We don't do anything if length is not constant.
172 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
173 Len = LengthArg->getZExtValue();
177 // See if we can get the length of the input string.
178 uint64_t SrcLen = GetStringLength(Src);
181 --SrcLen; // Unbias length.
183 // Handle the simple, do-nothing cases:
184 // strncat(x, "", c) -> x
185 // strncat(x, c, 0) -> x
186 if (SrcLen == 0 || Len == 0)
189 // We don't optimize this case.
193 // strncat(x, s, c) -> strcat(x, s)
194 // s is constant so the strcat can be optimized further.
195 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
198 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
199 Function *Callee = CI->getCalledFunction();
200 FunctionType *FT = Callee->getFunctionType();
201 Value *SrcStr = CI->getArgOperand(0);
203 // If the second operand is non-constant, see if we can compute the length
204 // of the input string and turn this into memchr.
205 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
207 uint64_t Len = GetStringLength(SrcStr);
208 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
211 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
212 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
216 // Otherwise, the character is a constant, see if the first argument is
217 // a string literal. If so, we can constant fold.
219 if (!getConstantStringInfo(SrcStr, Str)) {
220 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
221 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
226 // Compute the offset, make sure to handle the case when we're searching for
227 // zero (a weird way to spell strlen).
228 size_t I = (0xFF & CharC->getSExtValue()) == 0
230 : Str.find(CharC->getSExtValue());
231 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
232 return Constant::getNullValue(CI->getType());
234 // strchr(s+n,c) -> gep(s+n+i,c)
235 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
238 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
239 Value *SrcStr = CI->getArgOperand(0);
240 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
242 // Cannot fold anything if we're not looking for a constant.
247 if (!getConstantStringInfo(SrcStr, Str)) {
248 // strrchr(s, 0) -> strchr(s, 0)
250 return emitStrChr(SrcStr, '\0', B, TLI);
254 // Compute the offset.
255 size_t I = (0xFF & CharC->getSExtValue()) == 0
257 : Str.rfind(CharC->getSExtValue());
258 if (I == StringRef::npos) // Didn't find the char. Return null.
259 return Constant::getNullValue(CI->getType());
261 // strrchr(s+n,c) -> gep(s+n+i,c)
262 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
265 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
266 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
267 if (Str1P == Str2P) // strcmp(x,x) -> 0
268 return ConstantInt::get(CI->getType(), 0);
270 StringRef Str1, Str2;
271 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
272 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
274 // strcmp(x, y) -> cnst (if both x and y are constant strings)
275 if (HasStr1 && HasStr2)
276 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
278 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
280 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
282 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
283 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
285 // strcmp(P, "x") -> memcmp(P, "x", 2)
286 uint64_t Len1 = GetStringLength(Str1P);
287 uint64_t Len2 = GetStringLength(Str2P);
289 return emitMemCmp(Str1P, Str2P,
290 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
291 std::min(Len1, Len2)),
298 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
299 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
300 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
301 return ConstantInt::get(CI->getType(), 0);
303 // Get the length argument if it is constant.
305 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
306 Length = LengthArg->getZExtValue();
310 if (Length == 0) // strncmp(x,y,0) -> 0
311 return ConstantInt::get(CI->getType(), 0);
313 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
314 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
316 StringRef Str1, Str2;
317 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
318 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
320 // strncmp(x, y) -> cnst (if both x and y are constant strings)
321 if (HasStr1 && HasStr2) {
322 StringRef SubStr1 = Str1.substr(0, Length);
323 StringRef SubStr2 = Str2.substr(0, Length);
324 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
327 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
329 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
331 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
332 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
337 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
338 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
339 if (Dst == Src) // strcpy(x,x) -> x
342 // See if we can get the length of the input string.
343 uint64_t Len = GetStringLength(Src);
347 // We have enough information to now generate the memcpy call to do the
348 // copy for us. Make a memcpy to copy the nul byte with align = 1.
349 B.CreateMemCpy(Dst, Src,
350 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
354 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
355 Function *Callee = CI->getCalledFunction();
356 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
357 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
358 Value *StrLen = emitStrLen(Src, B, DL, TLI);
359 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
362 // See if we can get the length of the input string.
363 uint64_t Len = GetStringLength(Src);
367 Type *PT = Callee->getFunctionType()->getParamType(0);
368 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
369 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
370 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
372 // We have enough information to now generate the memcpy call to do the
373 // copy for us. Make a memcpy to copy the nul byte with align = 1.
374 B.CreateMemCpy(Dst, Src, LenV, 1);
378 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
379 Function *Callee = CI->getCalledFunction();
380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
382 Value *LenOp = CI->getArgOperand(2);
384 // See if we can get the length of the input string.
385 uint64_t SrcLen = GetStringLength(Src);
391 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
392 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
397 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
398 Len = LengthArg->getZExtValue();
403 return Dst; // strncpy(x, y, 0) -> x
405 // Let strncpy handle the zero padding
406 if (Len > SrcLen + 1)
409 Type *PT = Callee->getFunctionType()->getParamType(0);
410 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
411 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
416 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
418 Value *Src = CI->getArgOperand(0);
420 // Constant folding: strlen("xyz") -> 3
421 if (uint64_t Len = GetStringLength(Src, CharSize))
422 return ConstantInt::get(CI->getType(), Len - 1);
424 // If s is a constant pointer pointing to a string literal, we can fold
425 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
426 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
427 // We only try to simplify strlen when the pointer s points to an array
428 // of i8. Otherwise, we would need to scale the offset x before doing the
429 // subtraction. This will make the optimization more complex, and it's not
430 // very useful because calling strlen for a pointer of other types is
432 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
433 if (!isGEPBasedOnPointerToString(GEP, CharSize))
436 ConstantDataArraySlice Slice;
437 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
438 uint64_t NullTermIdx;
439 if (Slice.Array == nullptr) {
442 NullTermIdx = ~((uint64_t)0);
443 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
444 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
449 // If the string does not have '\0', leave it to strlen to compute
451 if (NullTermIdx == ~((uint64_t)0))
455 Value *Offset = GEP->getOperand(2);
456 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
457 Known.Zero.flipAllBits();
459 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
461 // KnownZero's bits are flipped, so zeros in KnownZero now represent
462 // bits known to be zeros in Offset, and ones in KnowZero represent
463 // bits unknown in Offset. Therefore, Offset is known to be in range
464 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
465 // unsigned-less-than NullTermIdx.
467 // If Offset is not provably in the range [0, NullTermIdx], we can still
468 // optimize if we can prove that the program has undefined behavior when
469 // Offset is outside that range. That is the case when GEP->getOperand(0)
470 // is a pointer to an object whose memory extent is NullTermIdx+1.
471 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
472 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
473 NullTermIdx == ArrSize - 1)) {
474 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
475 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
483 // strlen(x?"foo":"bars") --> x ? 3 : 4
484 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
485 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
486 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
487 if (LenTrue && LenFalse) {
489 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
490 << "folded strlen(select) to select of constants";
492 return B.CreateSelect(SI->getCondition(),
493 ConstantInt::get(CI->getType(), LenTrue - 1),
494 ConstantInt::get(CI->getType(), LenFalse - 1));
498 // strlen(x) != 0 --> *x != 0
499 // strlen(x) == 0 --> *x == 0
500 if (isOnlyUsedInZeroEqualityComparison(CI))
501 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
506 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
507 return optimizeStringLength(CI, B, 8);
510 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
511 Module &M = *CI->getParent()->getParent()->getParent();
512 unsigned WCharSize = TLI->getWCharSize(M) * 8;
513 // We cannot perform this optimization without wchar_size metadata.
517 return optimizeStringLength(CI, B, WCharSize);
520 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
522 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
523 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
525 // strpbrk(s, "") -> nullptr
526 // strpbrk("", s) -> nullptr
527 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
528 return Constant::getNullValue(CI->getType());
531 if (HasS1 && HasS2) {
532 size_t I = S1.find_first_of(S2);
533 if (I == StringRef::npos) // No match.
534 return Constant::getNullValue(CI->getType());
536 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
540 // strpbrk(s, "a") -> strchr(s, 'a')
541 if (HasS2 && S2.size() == 1)
542 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
547 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
548 Value *EndPtr = CI->getArgOperand(1);
549 if (isa<ConstantPointerNull>(EndPtr)) {
550 // With a null EndPtr, this function won't capture the main argument.
551 // It would be readonly too, except that it still may write to errno.
552 CI->addParamAttr(0, Attribute::NoCapture);
558 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
560 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
561 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
563 // strspn(s, "") -> 0
564 // strspn("", s) -> 0
565 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
566 return Constant::getNullValue(CI->getType());
569 if (HasS1 && HasS2) {
570 size_t Pos = S1.find_first_not_of(S2);
571 if (Pos == StringRef::npos)
573 return ConstantInt::get(CI->getType(), Pos);
579 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
581 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
582 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
584 // strcspn("", s) -> 0
585 if (HasS1 && S1.empty())
586 return Constant::getNullValue(CI->getType());
589 if (HasS1 && HasS2) {
590 size_t Pos = S1.find_first_of(S2);
591 if (Pos == StringRef::npos)
593 return ConstantInt::get(CI->getType(), Pos);
596 // strcspn(s, "") -> strlen(s)
597 if (HasS2 && S2.empty())
598 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
603 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
604 // fold strstr(x, x) -> x.
605 if (CI->getArgOperand(0) == CI->getArgOperand(1))
606 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
608 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
609 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
610 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
613 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
617 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
618 ICmpInst *Old = cast<ICmpInst>(*UI++);
620 B.CreateICmp(Old->getPredicate(), StrNCmp,
621 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
622 replaceAllUsesWith(Old, Cmp);
627 // See if either input string is a constant string.
628 StringRef SearchStr, ToFindStr;
629 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
630 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
632 // fold strstr(x, "") -> x.
633 if (HasStr2 && ToFindStr.empty())
634 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
636 // If both strings are known, constant fold it.
637 if (HasStr1 && HasStr2) {
638 size_t Offset = SearchStr.find(ToFindStr);
640 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
641 return Constant::getNullValue(CI->getType());
643 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
644 Value *Result = castToCStr(CI->getArgOperand(0), B);
645 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
646 return B.CreateBitCast(Result, CI->getType());
649 // fold strstr(x, "y") -> strchr(x, 'y').
650 if (HasStr2 && ToFindStr.size() == 1) {
651 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
652 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
657 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
658 Value *SrcStr = CI->getArgOperand(0);
659 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
660 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
662 // memchr(x, y, 0) -> null
663 if (LenC && LenC->isZero())
664 return Constant::getNullValue(CI->getType());
666 // From now on we need at least constant length and string.
668 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
671 // Truncate the string to LenC. If Str is smaller than LenC we will still only
672 // scan the string, as reading past the end of it is undefined and we can just
673 // return null if we don't find the char.
674 Str = Str.substr(0, LenC->getZExtValue());
676 // If the char is variable but the input str and length are not we can turn
677 // this memchr call into a simple bit field test. Of course this only works
678 // when the return value is only checked against null.
680 // It would be really nice to reuse switch lowering here but we can't change
681 // the CFG at this point.
683 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
684 // after bounds check.
685 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
687 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
688 reinterpret_cast<const unsigned char *>(Str.end()));
690 // Make sure the bit field we're about to create fits in a register on the
692 // FIXME: On a 64 bit architecture this prevents us from using the
693 // interesting range of alpha ascii chars. We could do better by emitting
694 // two bitfields or shifting the range by 64 if no lower chars are used.
695 if (!DL.fitsInLegalInteger(Max + 1))
698 // For the bit field use a power-of-2 type with at least 8 bits to avoid
699 // creating unnecessary illegal types.
700 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
702 // Now build the bit field.
703 APInt Bitfield(Width, 0);
705 Bitfield.setBit((unsigned char)C);
706 Value *BitfieldC = B.getInt(Bitfield);
708 // First check that the bit field access is within bounds.
709 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
710 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
713 // Create code that checks if the given bit is set in the field.
714 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
715 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
717 // Finally merge both checks and cast to pointer type. The inttoptr
718 // implicitly zexts the i1 to intptr type.
719 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
722 // Check if all arguments are constants. If so, we can constant fold.
726 // Compute the offset.
727 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
728 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
729 return Constant::getNullValue(CI->getType());
731 // memchr(s+n,c,l) -> gep(s+n+i,c)
732 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
735 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
736 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
738 if (LHS == RHS) // memcmp(s,s,x) -> 0
739 return Constant::getNullValue(CI->getType());
741 // Make sure we have a constant length.
742 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
746 uint64_t Len = LenC->getZExtValue();
747 if (Len == 0) // memcmp(s1,s2,0) -> 0
748 return Constant::getNullValue(CI->getType());
750 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
752 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
753 CI->getType(), "lhsv");
754 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
755 CI->getType(), "rhsv");
756 return B.CreateSub(LHSV, RHSV, "chardiff");
759 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
760 // TODO: The case where both inputs are constants does not need to be limited
761 // to legal integers or equality comparison. See block below this.
762 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
763 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
764 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
766 // First, see if we can fold either argument to a constant.
767 Value *LHSV = nullptr;
768 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
769 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
770 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
772 Value *RHSV = nullptr;
773 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
774 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
775 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
778 // Don't generate unaligned loads. If either source is constant data,
779 // alignment doesn't matter for that source because there is no load.
780 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
781 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
784 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
785 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
789 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
790 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
792 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
796 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
797 // TODO: This is limited to i8 arrays.
798 StringRef LHSStr, RHSStr;
799 if (getConstantStringInfo(LHS, LHSStr) &&
800 getConstantStringInfo(RHS, RHSStr)) {
801 // Make sure we're not reading out-of-bounds memory.
802 if (Len > LHSStr.size() || Len > RHSStr.size())
804 // Fold the memcmp and normalize the result. This way we get consistent
805 // results across multiple platforms.
807 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
812 return ConstantInt::get(CI->getType(), Ret);
818 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
819 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
820 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
821 CI->getArgOperand(2), 1);
822 return CI->getArgOperand(0);
825 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
826 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
827 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
828 CI->getArgOperand(2), 1);
829 return CI->getArgOperand(0);
832 // TODO: Does this belong in BuildLibCalls or should all of those similar
833 // functions be moved here?
834 static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
835 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
837 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
840 Module *M = B.GetInsertBlock()->getModule();
841 const DataLayout &DL = M->getDataLayout();
842 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
843 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
845 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
847 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
848 CI->setCallingConv(F->getCallingConv());
853 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
854 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
855 const TargetLibraryInfo &TLI) {
856 // This has to be a memset of zeros (bzero).
857 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
858 if (!FillValue || FillValue->getZExtValue() != 0)
861 // TODO: We should handle the case where the malloc has more than one use.
862 // This is necessary to optimize common patterns such as when the result of
863 // the malloc is checked against null or when a memset intrinsic is used in
864 // place of a memset library call.
865 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
866 if (!Malloc || !Malloc->hasOneUse())
869 // Is the inner call really malloc()?
870 Function *InnerCallee = Malloc->getCalledFunction();
875 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
876 Func != LibFunc_malloc)
879 // The memset must cover the same number of bytes that are malloc'd.
880 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
883 // Replace the malloc with a calloc. We need the data layout to know what the
884 // actual size of a 'size_t' parameter is.
885 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
886 const DataLayout &DL = Malloc->getModule()->getDataLayout();
887 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
888 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
889 Malloc->getArgOperand(0), Malloc->getAttributes(),
894 Malloc->replaceAllUsesWith(Calloc);
895 Malloc->eraseFromParent();
900 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
901 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
904 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
905 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
906 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
907 return CI->getArgOperand(0);
910 //===----------------------------------------------------------------------===//
911 // Math Library Optimizations
912 //===----------------------------------------------------------------------===//
914 /// Return a variant of Val with float type.
915 /// Currently this works in two cases: If Val is an FPExtension of a float
916 /// value to something bigger, simply return the operand.
917 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
918 /// loss of precision do so.
919 static Value *valueHasFloatPrecision(Value *Val) {
920 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
921 Value *Op = Cast->getOperand(0);
922 if (Op->getType()->isFloatTy())
925 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
926 APFloat F = Const->getValueAPF();
928 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
931 return ConstantFP::get(Const->getContext(), F);
936 /// Shrink double -> float for unary functions like 'floor'.
937 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
939 Function *Callee = CI->getCalledFunction();
940 // We know this libcall has a valid prototype, but we don't know which.
941 if (!CI->getType()->isDoubleTy())
945 // Check if all the uses for function like 'sin' are converted to float.
946 for (User *U : CI->users()) {
947 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
948 if (!Cast || !Cast->getType()->isFloatTy())
953 // If this is something like 'floor((double)floatval)', convert to floorf.
954 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
958 // If call isn't an intrinsic, check that it isn't within a function with the
959 // same name as the float version of this call.
961 // e.g. inline float expf(float val) { return (float) exp((double) val); }
963 // A similar such definition exists in the MinGW-w64 math.h header file which
964 // when compiled with -O2 -ffast-math causes the generation of infinite loops
965 // where expf is called.
966 if (!Callee->isIntrinsic()) {
967 const Function *F = CI->getFunction();
968 StringRef FName = F->getName();
969 StringRef CalleeName = Callee->getName();
970 if ((FName.size() == (CalleeName.size() + 1)) &&
971 (FName.back() == 'f') &&
972 FName.startswith(CalleeName))
976 // Propagate fast-math flags from the existing call to the new call.
977 IRBuilder<>::FastMathFlagGuard Guard(B);
978 B.setFastMathFlags(CI->getFastMathFlags());
980 // floor((double)floatval) -> (double)floorf(floatval)
981 if (Callee->isIntrinsic()) {
982 Module *M = CI->getModule();
983 Intrinsic::ID IID = Callee->getIntrinsicID();
984 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
985 V = B.CreateCall(F, V);
987 // The call is a library call rather than an intrinsic.
988 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
991 return B.CreateFPExt(V, B.getDoubleTy());
994 // Replace a libcall \p CI with a call to intrinsic \p IID
995 static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
996 // Propagate fast-math flags from the existing call to the new call.
997 IRBuilder<>::FastMathFlagGuard Guard(B);
998 B.setFastMathFlags(CI->getFastMathFlags());
1000 Module *M = CI->getModule();
1001 Value *V = CI->getArgOperand(0);
1002 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1003 CallInst *NewCall = B.CreateCall(F, V);
1004 NewCall->takeName(CI);
1008 /// Shrink double -> float for binary functions like 'fmin/fmax'.
1009 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1010 Function *Callee = CI->getCalledFunction();
1011 // We know this libcall has a valid prototype, but we don't know which.
1012 if (!CI->getType()->isDoubleTy())
1015 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1016 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1017 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1020 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1024 // Propagate fast-math flags from the existing call to the new call.
1025 IRBuilder<>::FastMathFlagGuard Guard(B);
1026 B.setFastMathFlags(CI->getFastMathFlags());
1028 // fmin((double)floatval1, (double)floatval2)
1029 // -> (double)fminf(floatval1, floatval2)
1030 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1031 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1032 Callee->getAttributes());
1033 return B.CreateFPExt(V, B.getDoubleTy());
1036 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1037 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1041 // Propagate fast-math flags from the existing call to new instructions.
1042 IRBuilder<>::FastMathFlagGuard Guard(B);
1043 B.setFastMathFlags(CI->getFastMathFlags());
1046 if (CI->getNumArgOperands() == 1) {
1047 Value *Op = CI->getArgOperand(0);
1048 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1049 Real = B.CreateExtractValue(Op, 0, "real");
1050 Imag = B.CreateExtractValue(Op, 1, "imag");
1052 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1053 Real = CI->getArgOperand(0);
1054 Imag = CI->getArgOperand(1);
1057 Value *RealReal = B.CreateFMul(Real, Real);
1058 Value *ImagImag = B.CreateFMul(Imag, Imag);
1060 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1062 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1065 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1066 Function *Callee = CI->getCalledFunction();
1067 Value *Ret = nullptr;
1068 StringRef Name = Callee->getName();
1069 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1070 Ret = optimizeUnaryDoubleFP(CI, B, true);
1072 // cos(-x) -> cos(x)
1073 Value *Op1 = CI->getArgOperand(0);
1074 if (BinaryOperator::isFNeg(Op1)) {
1075 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1076 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1081 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1082 // Multiplications calculated using Addition Chains.
1083 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1085 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1087 if (InnerChain[Exp])
1088 return InnerChain[Exp];
1090 static const unsigned AddChain[33][2] = {
1092 {0, 0}, // Unused (base case = pow1).
1093 {1, 1}, // Unused (pre-computed).
1094 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1095 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1096 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1097 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1098 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1101 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1102 getPow(InnerChain, AddChain[Exp][1], B));
1103 return InnerChain[Exp];
1106 /// Use square root in place of pow(x, +/-0.5).
1107 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1108 // TODO: There is some subset of 'fast' under which these transforms should
1113 const APFloat *Arg1C;
1114 if (!match(Pow->getArgOperand(1), m_APFloat(Arg1C)))
1116 if (!Arg1C->isExactlyValue(0.5) && !Arg1C->isExactlyValue(-0.5))
1119 // Fast-math flags from the pow() are propagated to all replacement ops.
1120 IRBuilder<>::FastMathFlagGuard Guard(B);
1121 B.setFastMathFlags(Pow->getFastMathFlags());
1122 Type *Ty = Pow->getType();
1124 if (Pow->hasFnAttr(Attribute::ReadNone)) {
1125 // We know that errno is never set, so replace with an intrinsic:
1126 // pow(x, 0.5) --> llvm.sqrt(x)
1127 // llvm.pow(x, 0.5) --> llvm.sqrt(x)
1128 auto *F = Intrinsic::getDeclaration(Pow->getModule(), Intrinsic::sqrt, Ty);
1129 Sqrt = B.CreateCall(F, Pow->getArgOperand(0));
1130 } else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf,
1132 // Errno could be set, so we must use a sqrt libcall.
1133 // TODO: We also should check that the target can in fact lower the sqrt
1134 // libcall. We currently have no way to ask this question, so we ask
1135 // whether the target has a sqrt libcall which is not exactly the same.
1136 Sqrt = emitUnaryFloatFnCall(Pow->getArgOperand(0),
1137 TLI->getName(LibFunc_sqrt), B,
1138 Pow->getCalledFunction()->getAttributes());
1140 // We can't replace with an intrinsic or a libcall.
1144 // If this is pow(x, -0.5), get the reciprocal.
1145 if (Arg1C->isExactlyValue(-0.5))
1146 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt);
1151 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1152 Function *Callee = CI->getCalledFunction();
1153 Value *Ret = nullptr;
1154 StringRef Name = Callee->getName();
1155 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1156 Ret = optimizeUnaryDoubleFP(CI, B, true);
1158 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1160 // pow(1.0, x) -> 1.0
1161 if (match(Op1, m_SpecificFP(1.0)))
1163 // pow(2.0, x) -> llvm.exp2(x)
1164 if (match(Op1, m_SpecificFP(2.0))) {
1165 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1167 return B.CreateCall(Exp2, Op2, "exp2");
1170 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1172 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1173 // pow(10.0, x) -> exp10(x)
1174 if (Op1C->isExactlyValue(10.0) &&
1175 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1177 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
1178 Callee->getAttributes());
1181 // pow(exp(x), y) -> exp(x * y)
1182 // pow(exp2(x), y) -> exp2(x * y)
1183 // We enable these only with fast-math. Besides rounding differences, the
1184 // transformation changes overflow and underflow behavior quite dramatically.
1185 // Example: x = 1000, y = 0.001.
1186 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1187 auto *OpC = dyn_cast<CallInst>(Op1);
1188 if (OpC && OpC->isFast() && CI->isFast()) {
1190 Function *OpCCallee = OpC->getCalledFunction();
1191 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1192 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
1193 IRBuilder<>::FastMathFlagGuard Guard(B);
1194 B.setFastMathFlags(CI->getFastMathFlags());
1195 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1196 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1197 OpCCallee->getAttributes());
1201 if (Value *Sqrt = replacePowWithSqrt(CI, B))
1204 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1208 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1209 return ConstantFP::get(CI->getType(), 1.0);
1211 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
1212 if (Op2C->isExactlyValue(0.5) &&
1213 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1215 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1216 // This is faster than calling pow, and still handles negative zero
1217 // and negative infinity correctly.
1218 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1219 Value *Inf = ConstantFP::getInfinity(CI->getType());
1220 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1222 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1223 // intrinsic, to match errno semantics.
1224 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1226 Module *M = Callee->getParent();
1227 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1229 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1231 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1232 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1236 // Propagate fast-math-flags from the call to any created instructions.
1237 IRBuilder<>::FastMathFlagGuard Guard(B);
1238 B.setFastMathFlags(CI->getFastMathFlags());
1239 // pow(x, 1.0) --> x
1240 if (Op2C->isExactlyValue(1.0))
1242 // pow(x, 2.0) --> x * x
1243 if (Op2C->isExactlyValue(2.0))
1244 return B.CreateFMul(Op1, Op1, "pow2");
1245 // pow(x, -1.0) --> 1.0 / x
1246 if (Op2C->isExactlyValue(-1.0))
1247 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1249 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
1251 APFloat V = abs(Op2C->getValueAPF());
1252 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1253 // This transformation applies to integer exponents only.
1254 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1258 // We will memoize intermediate products of the Addition Chain.
1259 Value *InnerChain[33] = {nullptr};
1260 InnerChain[1] = Op1;
1261 InnerChain[2] = B.CreateFMul(Op1, Op1);
1263 // We cannot readily convert a non-double type (like float) to a double.
1264 // So we first convert V to something which could be converted to double.
1266 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1268 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1269 // For negative exponents simply compute the reciprocal.
1270 if (Op2C->isNegative())
1271 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1278 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1279 Function *Callee = CI->getCalledFunction();
1280 Value *Ret = nullptr;
1281 StringRef Name = Callee->getName();
1282 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1283 Ret = optimizeUnaryDoubleFP(CI, B, true);
1285 Value *Op = CI->getArgOperand(0);
1286 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1287 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1288 LibFunc LdExp = LibFunc_ldexpl;
1289 if (Op->getType()->isFloatTy())
1290 LdExp = LibFunc_ldexpf;
1291 else if (Op->getType()->isDoubleTy())
1292 LdExp = LibFunc_ldexp;
1294 if (TLI->has(LdExp)) {
1295 Value *LdExpArg = nullptr;
1296 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1297 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1298 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1299 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1300 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1301 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1305 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1306 if (!Op->getType()->isFloatTy())
1307 One = ConstantExpr::getFPExtend(One, Op->getType());
1309 Module *M = CI->getModule();
1311 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1312 Op->getType(), B.getInt32Ty());
1313 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1314 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1315 CI->setCallingConv(F->getCallingConv());
1323 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1324 Function *Callee = CI->getCalledFunction();
1325 // If we can shrink the call to a float function rather than a double
1326 // function, do that first.
1327 StringRef Name = Callee->getName();
1328 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1329 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1332 IRBuilder<>::FastMathFlagGuard Guard(B);
1335 // If the call is 'fast', then anything we create here will also be 'fast'.
1338 // At a minimum, no-nans-fp-math must be true.
1339 if (!CI->hasNoNaNs())
1341 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1342 // "Ideally, fmax would be sensitive to the sign of zero, for example
1343 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1344 // might be impractical."
1345 FMF.setNoSignedZeros();
1348 B.setFastMathFlags(FMF);
1350 // We have a relaxed floating-point environment. We can ignore NaN-handling
1351 // and transform to a compare and select. We do not have to consider errno or
1352 // exceptions, because fmin/fmax do not have those.
1353 Value *Op0 = CI->getArgOperand(0);
1354 Value *Op1 = CI->getArgOperand(1);
1355 Value *Cmp = Callee->getName().startswith("fmin") ?
1356 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1357 return B.CreateSelect(Cmp, Op0, Op1);
1360 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1361 Function *Callee = CI->getCalledFunction();
1362 Value *Ret = nullptr;
1363 StringRef Name = Callee->getName();
1364 if (UnsafeFPShrink && hasFloatVersion(Name))
1365 Ret = optimizeUnaryDoubleFP(CI, B, true);
1369 Value *Op1 = CI->getArgOperand(0);
1370 auto *OpC = dyn_cast<CallInst>(Op1);
1372 // The earlier call must also be 'fast' in order to do these transforms.
1373 if (!OpC || !OpC->isFast())
1376 // log(pow(x,y)) -> y*log(x)
1377 // This is only applicable to log, log2, log10.
1378 if (Name != "log" && Name != "log2" && Name != "log10")
1381 IRBuilder<>::FastMathFlagGuard Guard(B);
1384 B.setFastMathFlags(FMF);
1387 Function *F = OpC->getCalledFunction();
1388 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1389 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1390 return B.CreateFMul(OpC->getArgOperand(1),
1391 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1392 Callee->getAttributes()), "mul");
1394 // log(exp2(y)) -> y*log(2)
1395 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1396 TLI->has(Func) && Func == LibFunc_exp2)
1397 return B.CreateFMul(
1398 OpC->getArgOperand(0),
1399 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1400 Callee->getName(), B, Callee->getAttributes()),
1405 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1406 Function *Callee = CI->getCalledFunction();
1407 Value *Ret = nullptr;
1408 // TODO: Once we have a way (other than checking for the existince of the
1409 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1411 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1412 Callee->getIntrinsicID() == Intrinsic::sqrt))
1413 Ret = optimizeUnaryDoubleFP(CI, B, true);
1418 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1419 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
1422 // We're looking for a repeated factor in a multiplication tree,
1423 // so we can do this fold: sqrt(x * x) -> fabs(x);
1424 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1425 Value *Op0 = I->getOperand(0);
1426 Value *Op1 = I->getOperand(1);
1427 Value *RepeatOp = nullptr;
1428 Value *OtherOp = nullptr;
1430 // Simple match: the operands of the multiply are identical.
1433 // Look for a more complicated pattern: one of the operands is itself
1434 // a multiply, so search for a common factor in that multiply.
1435 // Note: We don't bother looking any deeper than this first level or for
1436 // variations of this pattern because instcombine's visitFMUL and/or the
1437 // reassociation pass should give us this form.
1438 Value *OtherMul0, *OtherMul1;
1439 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1440 // Pattern: sqrt((x * y) * z)
1441 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
1442 // Matched: sqrt((x * x) * z)
1443 RepeatOp = OtherMul0;
1451 // Fast math flags for any created instructions should match the sqrt
1453 IRBuilder<>::FastMathFlagGuard Guard(B);
1454 B.setFastMathFlags(I->getFastMathFlags());
1456 // If we found a repeated factor, hoist it out of the square root and
1457 // replace it with the fabs of that factor.
1458 Module *M = Callee->getParent();
1459 Type *ArgType = I->getType();
1460 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1461 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1463 // If we found a non-repeated factor, we still need to get its square
1464 // root. We then multiply that by the value that was simplified out
1465 // of the square root calculation.
1466 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1467 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1468 return B.CreateFMul(FabsCall, SqrtCall);
1473 // TODO: Generalize to handle any trig function and its inverse.
1474 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1475 Function *Callee = CI->getCalledFunction();
1476 Value *Ret = nullptr;
1477 StringRef Name = Callee->getName();
1478 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1479 Ret = optimizeUnaryDoubleFP(CI, B, true);
1481 Value *Op1 = CI->getArgOperand(0);
1482 auto *OpC = dyn_cast<CallInst>(Op1);
1486 // Both calls must be 'fast' in order to remove them.
1487 if (!CI->isFast() || !OpC->isFast())
1490 // tan(atan(x)) -> x
1491 // tanf(atanf(x)) -> x
1492 // tanl(atanl(x)) -> x
1494 Function *F = OpC->getCalledFunction();
1495 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1496 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1497 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1498 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1499 Ret = OpC->getArgOperand(0);
1503 static bool isTrigLibCall(CallInst *CI) {
1504 // We can only hope to do anything useful if we can ignore things like errno
1505 // and floating-point exceptions.
1506 // We already checked the prototype.
1507 return CI->hasFnAttr(Attribute::NoUnwind) &&
1508 CI->hasFnAttr(Attribute::ReadNone);
1511 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1512 bool UseFloat, Value *&Sin, Value *&Cos,
1514 Type *ArgTy = Arg->getType();
1518 Triple T(OrigCallee->getParent()->getTargetTriple());
1520 Name = "__sincospif_stret";
1522 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1523 // x86_64 can't use {float, float} since that would be returned in both
1524 // xmm0 and xmm1, which isn't what a real struct would do.
1525 ResTy = T.getArch() == Triple::x86_64
1526 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1527 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
1529 Name = "__sincospi_stret";
1530 ResTy = StructType::get(ArgTy, ArgTy);
1533 Module *M = OrigCallee->getParent();
1534 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1537 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1538 // If the argument is an instruction, it must dominate all uses so put our
1539 // sincos call there.
1540 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1542 // Otherwise (e.g. for a constant) the beginning of the function is as
1543 // good a place as any.
1544 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1545 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1548 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1550 if (SinCos->getType()->isStructTy()) {
1551 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1552 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1554 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1556 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1561 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1562 // Make sure the prototype is as expected, otherwise the rest of the
1563 // function is probably invalid and likely to abort.
1564 if (!isTrigLibCall(CI))
1567 Value *Arg = CI->getArgOperand(0);
1568 SmallVector<CallInst *, 1> SinCalls;
1569 SmallVector<CallInst *, 1> CosCalls;
1570 SmallVector<CallInst *, 1> SinCosCalls;
1572 bool IsFloat = Arg->getType()->isFloatTy();
1574 // Look for all compatible sinpi, cospi and sincospi calls with the same
1575 // argument. If there are enough (in some sense) we can make the
1577 Function *F = CI->getFunction();
1578 for (User *U : Arg->users())
1579 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1581 // It's only worthwhile if both sinpi and cospi are actually used.
1582 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1585 Value *Sin, *Cos, *SinCos;
1586 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1588 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1590 for (CallInst *C : Calls)
1591 replaceAllUsesWith(C, Res);
1594 replaceTrigInsts(SinCalls, Sin);
1595 replaceTrigInsts(CosCalls, Cos);
1596 replaceTrigInsts(SinCosCalls, SinCos);
1601 void LibCallSimplifier::classifyArgUse(
1602 Value *Val, Function *F, bool IsFloat,
1603 SmallVectorImpl<CallInst *> &SinCalls,
1604 SmallVectorImpl<CallInst *> &CosCalls,
1605 SmallVectorImpl<CallInst *> &SinCosCalls) {
1606 CallInst *CI = dyn_cast<CallInst>(Val);
1611 // Don't consider calls in other functions.
1612 if (CI->getFunction() != F)
1615 Function *Callee = CI->getCalledFunction();
1617 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1622 if (Func == LibFunc_sinpif)
1623 SinCalls.push_back(CI);
1624 else if (Func == LibFunc_cospif)
1625 CosCalls.push_back(CI);
1626 else if (Func == LibFunc_sincospif_stret)
1627 SinCosCalls.push_back(CI);
1629 if (Func == LibFunc_sinpi)
1630 SinCalls.push_back(CI);
1631 else if (Func == LibFunc_cospi)
1632 CosCalls.push_back(CI);
1633 else if (Func == LibFunc_sincospi_stret)
1634 SinCosCalls.push_back(CI);
1638 //===----------------------------------------------------------------------===//
1639 // Integer Library Call Optimizations
1640 //===----------------------------------------------------------------------===//
1642 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1643 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1644 Value *Op = CI->getArgOperand(0);
1645 Type *ArgType = Op->getType();
1646 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1647 Intrinsic::cttz, ArgType);
1648 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1649 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1650 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1652 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1653 return B.CreateSelect(Cond, V, B.getInt32(0));
1656 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1657 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1658 Value *Op = CI->getArgOperand(0);
1659 Type *ArgType = Op->getType();
1660 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1661 Intrinsic::ctlz, ArgType);
1662 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1663 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1665 return B.CreateIntCast(V, CI->getType(), false);
1668 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1669 // abs(x) -> x >s -1 ? x : -x
1670 Value *Op = CI->getArgOperand(0);
1672 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1673 Value *Neg = B.CreateNeg(Op, "neg");
1674 return B.CreateSelect(Pos, Op, Neg);
1677 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1678 // isdigit(c) -> (c-'0') <u 10
1679 Value *Op = CI->getArgOperand(0);
1680 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1681 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1682 return B.CreateZExt(Op, CI->getType());
1685 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1686 // isascii(c) -> c <u 128
1687 Value *Op = CI->getArgOperand(0);
1688 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1689 return B.CreateZExt(Op, CI->getType());
1692 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1693 // toascii(c) -> c & 0x7f
1694 return B.CreateAnd(CI->getArgOperand(0),
1695 ConstantInt::get(CI->getType(), 0x7F));
1698 //===----------------------------------------------------------------------===//
1699 // Formatting and IO Library Call Optimizations
1700 //===----------------------------------------------------------------------===//
1702 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1704 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1706 Function *Callee = CI->getCalledFunction();
1707 // Error reporting calls should be cold, mark them as such.
1708 // This applies even to non-builtin calls: it is only a hint and applies to
1709 // functions that the frontend might not understand as builtins.
1711 // This heuristic was suggested in:
1712 // Improving Static Branch Prediction in a Compiler
1713 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1714 // Proceedings of PACT'98, Oct. 1998, IEEE
1715 if (!CI->hasFnAttr(Attribute::Cold) &&
1716 isReportingError(Callee, CI, StreamArg)) {
1717 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
1723 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1724 if (!Callee || !Callee->isDeclaration())
1730 // These functions might be considered cold, but only if their stream
1731 // argument is stderr.
1733 if (StreamArg >= (int)CI->getNumArgOperands())
1735 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1738 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1739 if (!GV || !GV->isDeclaration())
1741 return GV->getName() == "stderr";
1744 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1745 // Check for a fixed format string.
1746 StringRef FormatStr;
1747 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1750 // Empty format string -> noop.
1751 if (FormatStr.empty()) // Tolerate printf's declared void.
1752 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1754 // Do not do any of the following transformations if the printf return value
1755 // is used, in general the printf return value is not compatible with either
1756 // putchar() or puts().
1757 if (!CI->use_empty())
1760 // printf("x") -> putchar('x'), even for "%" and "%%".
1761 if (FormatStr.size() == 1 || FormatStr == "%%")
1762 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1764 // printf("%s", "a") --> putchar('a')
1765 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1767 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1769 if (ChrStr.size() != 1)
1771 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1774 // printf("foo\n") --> puts("foo")
1775 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1776 FormatStr.find('%') == StringRef::npos) { // No format characters.
1777 // Create a string literal with no \n on it. We expect the constant merge
1778 // pass to be run after this pass, to merge duplicate strings.
1779 FormatStr = FormatStr.drop_back();
1780 Value *GV = B.CreateGlobalString(FormatStr, "str");
1781 return emitPutS(GV, B, TLI);
1784 // Optimize specific format strings.
1785 // printf("%c", chr) --> putchar(chr)
1786 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1787 CI->getArgOperand(1)->getType()->isIntegerTy())
1788 return emitPutChar(CI->getArgOperand(1), B, TLI);
1790 // printf("%s\n", str) --> puts(str)
1791 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1792 CI->getArgOperand(1)->getType()->isPointerTy())
1793 return emitPutS(CI->getArgOperand(1), B, TLI);
1797 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1799 Function *Callee = CI->getCalledFunction();
1800 FunctionType *FT = Callee->getFunctionType();
1801 if (Value *V = optimizePrintFString(CI, B)) {
1805 // printf(format, ...) -> iprintf(format, ...) if no floating point
1807 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
1808 Module *M = B.GetInsertBlock()->getParent()->getParent();
1809 Constant *IPrintFFn =
1810 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1811 CallInst *New = cast<CallInst>(CI->clone());
1812 New->setCalledFunction(IPrintFFn);
1819 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1820 // Check for a fixed format string.
1821 StringRef FormatStr;
1822 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1825 // If we just have a format string (nothing else crazy) transform it.
1826 if (CI->getNumArgOperands() == 2) {
1827 // Make sure there's no % in the constant array. We could try to handle
1828 // %% -> % in the future if we cared.
1829 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1830 if (FormatStr[i] == '%')
1831 return nullptr; // we found a format specifier, bail out.
1833 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1834 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1835 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1836 FormatStr.size() + 1),
1837 1); // Copy the null byte.
1838 return ConstantInt::get(CI->getType(), FormatStr.size());
1841 // The remaining optimizations require the format string to be "%s" or "%c"
1842 // and have an extra operand.
1843 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1844 CI->getNumArgOperands() < 3)
1847 // Decode the second character of the format string.
1848 if (FormatStr[1] == 'c') {
1849 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1850 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1852 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1853 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1854 B.CreateStore(V, Ptr);
1855 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1856 B.CreateStore(B.getInt8(0), Ptr);
1858 return ConstantInt::get(CI->getType(), 1);
1861 if (FormatStr[1] == 's') {
1862 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1863 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1866 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1870 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1871 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1873 // The sprintf result is the unincremented number of bytes in the string.
1874 return B.CreateIntCast(Len, CI->getType(), false);
1879 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1880 Function *Callee = CI->getCalledFunction();
1881 FunctionType *FT = Callee->getFunctionType();
1882 if (Value *V = optimizeSPrintFString(CI, B)) {
1886 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1888 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
1889 Module *M = B.GetInsertBlock()->getParent()->getParent();
1890 Constant *SIPrintFFn =
1891 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1892 CallInst *New = cast<CallInst>(CI->clone());
1893 New->setCalledFunction(SIPrintFFn);
1900 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1901 optimizeErrorReporting(CI, B, 0);
1903 // All the optimizations depend on the format string.
1904 StringRef FormatStr;
1905 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1908 // Do not do any of the following transformations if the fprintf return
1909 // value is used, in general the fprintf return value is not compatible
1910 // with fwrite(), fputc() or fputs().
1911 if (!CI->use_empty())
1914 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1915 if (CI->getNumArgOperands() == 2) {
1916 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1917 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1918 return nullptr; // We found a format specifier.
1921 CI->getArgOperand(1),
1922 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1923 CI->getArgOperand(0), B, DL, TLI);
1926 // The remaining optimizations require the format string to be "%s" or "%c"
1927 // and have an extra operand.
1928 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1929 CI->getNumArgOperands() < 3)
1932 // Decode the second character of the format string.
1933 if (FormatStr[1] == 'c') {
1934 // fprintf(F, "%c", chr) --> fputc(chr, F)
1935 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1937 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1940 if (FormatStr[1] == 's') {
1941 // fprintf(F, "%s", str) --> fputs(str, F)
1942 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1944 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1949 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1950 Function *Callee = CI->getCalledFunction();
1951 FunctionType *FT = Callee->getFunctionType();
1952 if (Value *V = optimizeFPrintFString(CI, B)) {
1956 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1957 // floating point arguments.
1958 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
1959 Module *M = B.GetInsertBlock()->getParent()->getParent();
1960 Constant *FIPrintFFn =
1961 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1962 CallInst *New = cast<CallInst>(CI->clone());
1963 New->setCalledFunction(FIPrintFFn);
1970 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1971 optimizeErrorReporting(CI, B, 3);
1973 // Get the element size and count.
1974 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1975 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1976 if (!SizeC || !CountC)
1978 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1980 // If this is writing zero records, remove the call (it's a noop).
1982 return ConstantInt::get(CI->getType(), 0);
1984 // If this is writing one byte, turn it into fputc.
1985 // This optimisation is only valid, if the return value is unused.
1986 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1987 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1988 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
1989 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1995 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1996 optimizeErrorReporting(CI, B, 1);
1998 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1999 // requires more arguments and thus extra MOVs are required.
2000 if (CI->getParent()->getParent()->optForSize())
2003 // We can't optimize if return value is used.
2004 if (!CI->use_empty())
2007 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2008 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2012 // Known to have no uses (see above).
2014 CI->getArgOperand(0),
2015 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2016 CI->getArgOperand(1), B, DL, TLI);
2019 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2020 // Check for a constant string.
2022 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2025 if (Str.empty() && CI->use_empty()) {
2026 // puts("") -> putchar('\n')
2027 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
2028 if (CI->use_empty() || !Res)
2030 return B.CreateIntCast(Res, CI->getType(), true);
2036 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2038 SmallString<20> FloatFuncName = FuncName;
2039 FloatFuncName += 'f';
2040 if (TLI->getLibFunc(FloatFuncName, Func))
2041 return TLI->has(Func);
2045 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2046 IRBuilder<> &Builder) {
2048 Function *Callee = CI->getCalledFunction();
2049 // Check for string/memory library functions.
2050 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2051 // Make sure we never change the calling convention.
2052 assert((ignoreCallingConv(Func) ||
2053 isCallingConvCCompatible(CI)) &&
2054 "Optimizing string/memory libcall would change the calling convention");
2056 case LibFunc_strcat:
2057 return optimizeStrCat(CI, Builder);
2058 case LibFunc_strncat:
2059 return optimizeStrNCat(CI, Builder);
2060 case LibFunc_strchr:
2061 return optimizeStrChr(CI, Builder);
2062 case LibFunc_strrchr:
2063 return optimizeStrRChr(CI, Builder);
2064 case LibFunc_strcmp:
2065 return optimizeStrCmp(CI, Builder);
2066 case LibFunc_strncmp:
2067 return optimizeStrNCmp(CI, Builder);
2068 case LibFunc_strcpy:
2069 return optimizeStrCpy(CI, Builder);
2070 case LibFunc_stpcpy:
2071 return optimizeStpCpy(CI, Builder);
2072 case LibFunc_strncpy:
2073 return optimizeStrNCpy(CI, Builder);
2074 case LibFunc_strlen:
2075 return optimizeStrLen(CI, Builder);
2076 case LibFunc_strpbrk:
2077 return optimizeStrPBrk(CI, Builder);
2078 case LibFunc_strtol:
2079 case LibFunc_strtod:
2080 case LibFunc_strtof:
2081 case LibFunc_strtoul:
2082 case LibFunc_strtoll:
2083 case LibFunc_strtold:
2084 case LibFunc_strtoull:
2085 return optimizeStrTo(CI, Builder);
2086 case LibFunc_strspn:
2087 return optimizeStrSpn(CI, Builder);
2088 case LibFunc_strcspn:
2089 return optimizeStrCSpn(CI, Builder);
2090 case LibFunc_strstr:
2091 return optimizeStrStr(CI, Builder);
2092 case LibFunc_memchr:
2093 return optimizeMemChr(CI, Builder);
2094 case LibFunc_memcmp:
2095 return optimizeMemCmp(CI, Builder);
2096 case LibFunc_memcpy:
2097 return optimizeMemCpy(CI, Builder);
2098 case LibFunc_memmove:
2099 return optimizeMemMove(CI, Builder);
2100 case LibFunc_memset:
2101 return optimizeMemSet(CI, Builder);
2102 case LibFunc_wcslen:
2103 return optimizeWcslen(CI, Builder);
2111 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2113 IRBuilder<> &Builder) {
2114 // Don't optimize calls that require strict floating point semantics.
2115 if (CI->isStrictFP())
2122 return optimizeCos(CI, Builder);
2123 case LibFunc_sinpif:
2125 case LibFunc_cospif:
2127 return optimizeSinCosPi(CI, Builder);
2131 return optimizePow(CI, Builder);
2135 return optimizeExp2(CI, Builder);
2139 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2143 return optimizeSqrt(CI, Builder);
2149 return optimizeLog(CI, Builder);
2153 return optimizeTan(CI, Builder);
2155 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2157 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2159 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2160 case LibFunc_nearbyint:
2161 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2163 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2165 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2180 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2181 return optimizeUnaryDoubleFP(CI, Builder, true);
2183 case LibFunc_copysign:
2184 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2185 return optimizeBinaryDoubleFP(CI, Builder);
2193 return optimizeFMinFMax(CI, Builder);
2197 return optimizeCAbs(CI, Builder);
2203 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2204 // TODO: Split out the code below that operates on FP calls so that
2205 // we can all non-FP calls with the StrictFP attribute to be
2207 if (CI->isNoBuiltin())
2211 Function *Callee = CI->getCalledFunction();
2213 SmallVector<OperandBundleDef, 2> OpBundles;
2214 CI->getOperandBundlesAsDefs(OpBundles);
2215 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2216 bool isCallingConvC = isCallingConvCCompatible(CI);
2218 // Command-line parameter overrides instruction attribute.
2219 // This can't be moved to optimizeFloatingPointLibCall() because it may be
2220 // used by the intrinsic optimizations.
2221 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2222 UnsafeFPShrink = EnableUnsafeFPShrink;
2223 else if (isa<FPMathOperator>(CI) && CI->isFast())
2224 UnsafeFPShrink = true;
2226 // First, check for intrinsics.
2227 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2228 if (!isCallingConvC)
2230 // The FP intrinsics have corresponding constrained versions so we don't
2231 // need to check for the StrictFP attribute here.
2232 switch (II->getIntrinsicID()) {
2233 case Intrinsic::pow:
2234 return optimizePow(CI, Builder);
2235 case Intrinsic::exp2:
2236 return optimizeExp2(CI, Builder);
2237 case Intrinsic::log:
2238 return optimizeLog(CI, Builder);
2239 case Intrinsic::sqrt:
2240 return optimizeSqrt(CI, Builder);
2241 // TODO: Use foldMallocMemset() with memset intrinsic.
2247 // Also try to simplify calls to fortified library functions.
2248 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2249 // Try to further simplify the result.
2250 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2251 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2252 // Use an IR Builder from SimplifiedCI if available instead of CI
2253 // to guarantee we reach all uses we might replace later on.
2254 IRBuilder<> TmpBuilder(SimplifiedCI);
2255 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2256 // If we were able to further simplify, remove the now redundant call.
2257 SimplifiedCI->replaceAllUsesWith(V);
2258 SimplifiedCI->eraseFromParent();
2262 return SimplifiedFortifiedCI;
2265 // Then check for known library functions.
2266 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2267 // We never change the calling convention.
2268 if (!ignoreCallingConv(Func) && !isCallingConvC)
2270 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2272 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2278 return optimizeFFS(CI, Builder);
2282 return optimizeFls(CI, Builder);
2286 return optimizeAbs(CI, Builder);
2287 case LibFunc_isdigit:
2288 return optimizeIsDigit(CI, Builder);
2289 case LibFunc_isascii:
2290 return optimizeIsAscii(CI, Builder);
2291 case LibFunc_toascii:
2292 return optimizeToAscii(CI, Builder);
2293 case LibFunc_printf:
2294 return optimizePrintF(CI, Builder);
2295 case LibFunc_sprintf:
2296 return optimizeSPrintF(CI, Builder);
2297 case LibFunc_fprintf:
2298 return optimizeFPrintF(CI, Builder);
2299 case LibFunc_fwrite:
2300 return optimizeFWrite(CI, Builder);
2302 return optimizeFPuts(CI, Builder);
2304 return optimizePuts(CI, Builder);
2305 case LibFunc_perror:
2306 return optimizeErrorReporting(CI, Builder);
2307 case LibFunc_vfprintf:
2308 case LibFunc_fiprintf:
2309 return optimizeErrorReporting(CI, Builder, 0);
2311 return optimizeErrorReporting(CI, Builder, 1);
2319 LibCallSimplifier::LibCallSimplifier(
2320 const DataLayout &DL, const TargetLibraryInfo *TLI,
2321 OptimizationRemarkEmitter &ORE,
2322 function_ref<void(Instruction *, Value *)> Replacer)
2323 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2324 UnsafeFPShrink(false), Replacer(Replacer) {}
2326 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2327 // Indirect through the replacer used in this instance.
2332 // Additional cases that we need to add to this file:
2335 // * cbrt(expN(X)) -> expN(x/3)
2336 // * cbrt(sqrt(x)) -> pow(x,1/6)
2337 // * cbrt(cbrt(x)) -> pow(x,1/9)
2340 // * exp(log(x)) -> x
2343 // * log(exp(x)) -> x
2344 // * log(exp(y)) -> y*log(e)
2345 // * log(exp10(y)) -> y*log(10)
2346 // * log(sqrt(x)) -> 0.5*log(x)
2349 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2350 // * pow(pow(x,y),z)-> pow(x,y*z)
2353 // * signbit(cnst) -> cnst'
2354 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2356 // sqrt, sqrtf, sqrtl:
2357 // * sqrt(expN(x)) -> expN(x*0.5)
2358 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2359 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2362 //===----------------------------------------------------------------------===//
2363 // Fortified Library Call Optimizations
2364 //===----------------------------------------------------------------------===//
2366 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2370 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2372 if (ConstantInt *ObjSizeCI =
2373 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2374 if (ObjSizeCI->isMinusOne())
2376 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2377 if (OnlyLowerUnknownSize)
2380 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2381 // If the length is 0 we don't know how long it is and so we can't
2382 // remove the check.
2385 return ObjSizeCI->getZExtValue() >= Len;
2387 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2388 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2393 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2395 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2396 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2397 CI->getArgOperand(2), 1);
2398 return CI->getArgOperand(0);
2403 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2405 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2406 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2407 CI->getArgOperand(2), 1);
2408 return CI->getArgOperand(0);
2413 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2415 // TODO: Try foldMallocMemset() here.
2417 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2418 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2419 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2420 return CI->getArgOperand(0);
2425 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2428 Function *Callee = CI->getCalledFunction();
2429 StringRef Name = Callee->getName();
2430 const DataLayout &DL = CI->getModule()->getDataLayout();
2431 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2432 *ObjSize = CI->getArgOperand(2);
2434 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2435 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2436 Value *StrLen = emitStrLen(Src, B, DL, TLI);
2437 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2440 // If a) we don't have any length information, or b) we know this will
2441 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2442 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2443 // TODO: It might be nice to get a maximum length out of the possible
2444 // string lengths for varying.
2445 if (isFortifiedCallFoldable(CI, 2, 1, true))
2446 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2448 if (OnlyLowerUnknownSize)
2451 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2452 uint64_t Len = GetStringLength(Src);
2456 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2457 Value *LenV = ConstantInt::get(SizeTTy, Len);
2458 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2459 // If the function was an __stpcpy_chk, and we were able to fold it into
2460 // a __memcpy_chk, we still need to return the correct end pointer.
2461 if (Ret && Func == LibFunc_stpcpy_chk)
2462 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2466 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2469 Function *Callee = CI->getCalledFunction();
2470 StringRef Name = Callee->getName();
2471 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2472 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2473 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2479 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2480 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2481 // Some clang users checked for _chk libcall availability using:
2482 // __has_builtin(__builtin___memcpy_chk)
2483 // When compiling with -fno-builtin, this is always true.
2484 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2485 // end up with fortified libcalls, which isn't acceptable in a freestanding
2486 // environment which only provides their non-fortified counterparts.
2488 // Until we change clang and/or teach external users to check for availability
2489 // differently, disregard the "nobuiltin" attribute and TLI::has.
2494 Function *Callee = CI->getCalledFunction();
2496 SmallVector<OperandBundleDef, 2> OpBundles;
2497 CI->getOperandBundlesAsDefs(OpBundles);
2498 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2499 bool isCallingConvC = isCallingConvCCompatible(CI);
2501 // First, check that this is a known library functions and that the prototype
2503 if (!TLI->getLibFunc(*Callee, Func))
2506 // We never change the calling convention.
2507 if (!ignoreCallingConv(Func) && !isCallingConvC)
2511 case LibFunc_memcpy_chk:
2512 return optimizeMemCpyChk(CI, Builder);
2513 case LibFunc_memmove_chk:
2514 return optimizeMemMoveChk(CI, Builder);
2515 case LibFunc_memset_chk:
2516 return optimizeMemSetChk(CI, Builder);
2517 case LibFunc_stpcpy_chk:
2518 case LibFunc_strcpy_chk:
2519 return optimizeStrpCpyChk(CI, Builder, Func);
2520 case LibFunc_stpncpy_chk:
2521 case LibFunc_strncpy_chk:
2522 return optimizeStrpNCpyChk(CI, Builder, Func);
2529 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2530 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2531 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}