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/Allocator.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/Transforms/Utils/Local.h"
38 using namespace PatternMatch;
41 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static bool ignoreCallingConv(LibFunc::Func Func) {
56 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
60 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
61 /// value is equal or not-equal to zero.
62 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
63 for (User *U : V->users()) {
64 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
66 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
69 // Unknown instruction.
75 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
76 /// comparisons with With.
77 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
78 for (User *U : V->users()) {
79 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
80 if (IC->isEquality() && IC->getOperand(1) == With)
82 // Unknown instruction.
88 static bool callHasFloatingPointArgument(const CallInst *CI) {
89 for (const Use &OI : CI->operands())
90 if (OI->getType()->isFloatingPointTy())
95 /// \brief Check whether the overloaded unary floating point function
96 /// corresponding to \a Ty is available.
97 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
98 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
99 LibFunc::Func LongDoubleFn) {
100 switch (Ty->getTypeID()) {
101 case Type::FloatTyID:
102 return TLI->has(FloatFn);
103 case Type::DoubleTyID:
104 return TLI->has(DoubleFn);
106 return TLI->has(LongDoubleFn);
110 /// \brief Check whether we can use unsafe floating point math for
111 /// the function passed as input.
112 static bool canUseUnsafeFPMath(Function *F) {
114 // FIXME: For finer-grain optimization, we need intrinsics to have the same
115 // fast-math flag decorations that are applied to FP instructions. For now,
116 // we have to rely on the function-level unsafe-fp-math attribute to do this
117 // optimization because there's no other way to express that the call can be
119 if (F->hasFnAttribute("unsafe-fp-math")) {
120 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
121 if (Attr.getValueAsString() == "true")
127 /// \brief Returns whether \p F matches the signature expected for the
128 /// string/memory copying library function \p Func.
129 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
130 /// Their fortified (_chk) counterparts are also accepted.
131 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
132 const DataLayout &DL = F->getParent()->getDataLayout();
133 FunctionType *FT = F->getFunctionType();
134 LLVMContext &Context = F->getContext();
135 Type *PCharTy = Type::getInt8PtrTy(Context);
136 Type *SizeTTy = DL.getIntPtrType(Context);
137 unsigned NumParams = FT->getNumParams();
139 // All string libfuncs return the same type as the first parameter.
140 if (FT->getReturnType() != FT->getParamType(0))
145 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
146 case LibFunc::stpncpy_chk:
147 case LibFunc::strncpy_chk:
148 --NumParams; // fallthrough
149 case LibFunc::stpncpy:
150 case LibFunc::strncpy: {
151 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
152 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
156 case LibFunc::strcpy_chk:
157 case LibFunc::stpcpy_chk:
158 --NumParams; // fallthrough
159 case LibFunc::stpcpy:
160 case LibFunc::strcpy: {
161 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
162 FT->getParamType(0) != PCharTy)
166 case LibFunc::memmove_chk:
167 case LibFunc::memcpy_chk:
168 --NumParams; // fallthrough
169 case LibFunc::memmove:
170 case LibFunc::memcpy: {
171 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
176 case LibFunc::memset_chk:
177 --NumParams; // fallthrough
178 case LibFunc::memset: {
179 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
180 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
185 // If this is a fortified libcall, the last parameter is a size_t.
186 if (NumParams == FT->getNumParams() - 1)
187 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
191 //===----------------------------------------------------------------------===//
192 // String and Memory Library Call Optimizations
193 //===----------------------------------------------------------------------===//
195 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
196 Function *Callee = CI->getCalledFunction();
197 // Verify the "strcat" function prototype.
198 FunctionType *FT = Callee->getFunctionType();
199 if (FT->getNumParams() != 2||
200 FT->getReturnType() != B.getInt8PtrTy() ||
201 FT->getParamType(0) != FT->getReturnType() ||
202 FT->getParamType(1) != FT->getReturnType())
205 // Extract some information from the instruction
206 Value *Dst = CI->getArgOperand(0);
207 Value *Src = CI->getArgOperand(1);
209 // See if we can get the length of the input string.
210 uint64_t Len = GetStringLength(Src);
213 --Len; // Unbias length.
215 // Handle the simple, do-nothing case: strcat(x, "") -> x
219 return emitStrLenMemCpy(Src, Dst, Len, B);
222 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
224 // We need to find the end of the destination string. That's where the
225 // memory is to be moved to. We just generate a call to strlen.
226 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
230 // Now that we have the destination's length, we must index into the
231 // destination's pointer to get the actual memcpy destination (end of
232 // the string .. we're concatenating).
233 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
235 // We have enough information to now generate the memcpy call to do the
236 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
237 B.CreateMemCpy(CpyDst, Src,
238 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
243 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
244 Function *Callee = CI->getCalledFunction();
245 // Verify the "strncat" function prototype.
246 FunctionType *FT = Callee->getFunctionType();
247 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
248 FT->getParamType(0) != FT->getReturnType() ||
249 FT->getParamType(1) != FT->getReturnType() ||
250 !FT->getParamType(2)->isIntegerTy())
253 // Extract some information from the instruction
254 Value *Dst = CI->getArgOperand(0);
255 Value *Src = CI->getArgOperand(1);
258 // We don't do anything if length is not constant
259 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
260 Len = LengthArg->getZExtValue();
264 // See if we can get the length of the input string.
265 uint64_t SrcLen = GetStringLength(Src);
268 --SrcLen; // Unbias length.
270 // Handle the simple, do-nothing cases:
271 // strncat(x, "", c) -> x
272 // strncat(x, c, 0) -> x
273 if (SrcLen == 0 || Len == 0)
276 // We don't optimize this case
280 // strncat(x, s, c) -> strcat(x, s)
281 // s is constant so the strcat can be optimized further
282 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
285 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
286 Function *Callee = CI->getCalledFunction();
287 // Verify the "strchr" function prototype.
288 FunctionType *FT = Callee->getFunctionType();
289 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
290 FT->getParamType(0) != FT->getReturnType() ||
291 !FT->getParamType(1)->isIntegerTy(32))
294 Value *SrcStr = CI->getArgOperand(0);
296 // If the second operand is non-constant, see if we can compute the length
297 // of the input string and turn this into memchr.
298 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
300 uint64_t Len = GetStringLength(SrcStr);
301 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
304 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
305 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
309 // Otherwise, the character is a constant, see if the first argument is
310 // a string literal. If so, we can constant fold.
312 if (!getConstantStringInfo(SrcStr, Str)) {
313 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
314 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
318 // Compute the offset, make sure to handle the case when we're searching for
319 // zero (a weird way to spell strlen).
320 size_t I = (0xFF & CharC->getSExtValue()) == 0
322 : Str.find(CharC->getSExtValue());
323 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
324 return Constant::getNullValue(CI->getType());
326 // strchr(s+n,c) -> gep(s+n+i,c)
327 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
330 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
331 Function *Callee = CI->getCalledFunction();
332 // Verify the "strrchr" function prototype.
333 FunctionType *FT = Callee->getFunctionType();
334 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
335 FT->getParamType(0) != FT->getReturnType() ||
336 !FT->getParamType(1)->isIntegerTy(32))
339 Value *SrcStr = CI->getArgOperand(0);
340 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
342 // Cannot fold anything if we're not looking for a constant.
347 if (!getConstantStringInfo(SrcStr, Str)) {
348 // strrchr(s, 0) -> strchr(s, 0)
350 return EmitStrChr(SrcStr, '\0', B, TLI);
354 // Compute the offset.
355 size_t I = (0xFF & CharC->getSExtValue()) == 0
357 : Str.rfind(CharC->getSExtValue());
358 if (I == StringRef::npos) // Didn't find the char. Return null.
359 return Constant::getNullValue(CI->getType());
361 // strrchr(s+n,c) -> gep(s+n+i,c)
362 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
365 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
366 Function *Callee = CI->getCalledFunction();
367 // Verify the "strcmp" function prototype.
368 FunctionType *FT = Callee->getFunctionType();
369 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
370 FT->getParamType(0) != FT->getParamType(1) ||
371 FT->getParamType(0) != B.getInt8PtrTy())
374 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
375 if (Str1P == Str2P) // strcmp(x,x) -> 0
376 return ConstantInt::get(CI->getType(), 0);
378 StringRef Str1, Str2;
379 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
380 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
382 // strcmp(x, y) -> cnst (if both x and y are constant strings)
383 if (HasStr1 && HasStr2)
384 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
386 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
388 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
390 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
391 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
393 // strcmp(P, "x") -> memcmp(P, "x", 2)
394 uint64_t Len1 = GetStringLength(Str1P);
395 uint64_t Len2 = GetStringLength(Str2P);
397 return EmitMemCmp(Str1P, Str2P,
398 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
399 std::min(Len1, Len2)),
406 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
407 Function *Callee = CI->getCalledFunction();
408 // Verify the "strncmp" function prototype.
409 FunctionType *FT = Callee->getFunctionType();
410 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
411 FT->getParamType(0) != FT->getParamType(1) ||
412 FT->getParamType(0) != B.getInt8PtrTy() ||
413 !FT->getParamType(2)->isIntegerTy())
416 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
417 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
418 return ConstantInt::get(CI->getType(), 0);
420 // Get the length argument if it is constant.
422 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
423 Length = LengthArg->getZExtValue();
427 if (Length == 0) // strncmp(x,y,0) -> 0
428 return ConstantInt::get(CI->getType(), 0);
430 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
431 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
433 StringRef Str1, Str2;
434 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
435 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
437 // strncmp(x, y) -> cnst (if both x and y are constant strings)
438 if (HasStr1 && HasStr2) {
439 StringRef SubStr1 = Str1.substr(0, Length);
440 StringRef SubStr2 = Str2.substr(0, Length);
441 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
444 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
446 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
448 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
449 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
454 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
455 Function *Callee = CI->getCalledFunction();
457 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
460 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
461 if (Dst == Src) // strcpy(x,x) -> x
464 // See if we can get the length of the input string.
465 uint64_t Len = GetStringLength(Src);
469 // We have enough information to now generate the memcpy call to do the
470 // copy for us. Make a memcpy to copy the nul byte with align = 1.
471 B.CreateMemCpy(Dst, Src,
472 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
476 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
477 Function *Callee = CI->getCalledFunction();
478 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
481 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
482 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
483 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
484 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
487 // See if we can get the length of the input string.
488 uint64_t Len = GetStringLength(Src);
492 Type *PT = Callee->getFunctionType()->getParamType(0);
493 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
495 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
497 // We have enough information to now generate the memcpy call to do the
498 // copy for us. Make a memcpy to copy the nul byte with align = 1.
499 B.CreateMemCpy(Dst, Src, LenV, 1);
503 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
504 Function *Callee = CI->getCalledFunction();
505 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
508 Value *Dst = CI->getArgOperand(0);
509 Value *Src = CI->getArgOperand(1);
510 Value *LenOp = CI->getArgOperand(2);
512 // See if we can get the length of the input string.
513 uint64_t SrcLen = GetStringLength(Src);
519 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
520 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
525 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
526 Len = LengthArg->getZExtValue();
531 return Dst; // strncpy(x, y, 0) -> x
533 // Let strncpy handle the zero padding
534 if (Len > SrcLen + 1)
537 Type *PT = Callee->getFunctionType()->getParamType(0);
538 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
539 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
544 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
545 Function *Callee = CI->getCalledFunction();
546 FunctionType *FT = Callee->getFunctionType();
547 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
548 !FT->getReturnType()->isIntegerTy())
551 Value *Src = CI->getArgOperand(0);
553 // Constant folding: strlen("xyz") -> 3
554 if (uint64_t Len = GetStringLength(Src))
555 return ConstantInt::get(CI->getType(), Len - 1);
557 // strlen(x?"foo":"bars") --> x ? 3 : 4
558 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
559 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
560 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
561 if (LenTrue && LenFalse) {
562 Function *Caller = CI->getParent()->getParent();
563 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
565 "folded strlen(select) to select of constants");
566 return B.CreateSelect(SI->getCondition(),
567 ConstantInt::get(CI->getType(), LenTrue - 1),
568 ConstantInt::get(CI->getType(), LenFalse - 1));
572 // strlen(x) != 0 --> *x != 0
573 // strlen(x) == 0 --> *x == 0
574 if (isOnlyUsedInZeroEqualityComparison(CI))
575 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
580 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
581 Function *Callee = CI->getCalledFunction();
582 FunctionType *FT = Callee->getFunctionType();
583 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
584 FT->getParamType(1) != FT->getParamType(0) ||
585 FT->getReturnType() != FT->getParamType(0))
589 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
590 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
592 // strpbrk(s, "") -> nullptr
593 // strpbrk("", s) -> nullptr
594 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
595 return Constant::getNullValue(CI->getType());
598 if (HasS1 && HasS2) {
599 size_t I = S1.find_first_of(S2);
600 if (I == StringRef::npos) // No match.
601 return Constant::getNullValue(CI->getType());
603 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
606 // strpbrk(s, "a") -> strchr(s, 'a')
607 if (HasS2 && S2.size() == 1)
608 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
613 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
614 Function *Callee = CI->getCalledFunction();
615 FunctionType *FT = Callee->getFunctionType();
616 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
617 !FT->getParamType(0)->isPointerTy() ||
618 !FT->getParamType(1)->isPointerTy())
621 Value *EndPtr = CI->getArgOperand(1);
622 if (isa<ConstantPointerNull>(EndPtr)) {
623 // With a null EndPtr, this function won't capture the main argument.
624 // It would be readonly too, except that it still may write to errno.
625 CI->addAttribute(1, Attribute::NoCapture);
631 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
632 Function *Callee = CI->getCalledFunction();
633 FunctionType *FT = Callee->getFunctionType();
634 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
635 FT->getParamType(1) != FT->getParamType(0) ||
636 !FT->getReturnType()->isIntegerTy())
640 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
641 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
643 // strspn(s, "") -> 0
644 // strspn("", s) -> 0
645 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
646 return Constant::getNullValue(CI->getType());
649 if (HasS1 && HasS2) {
650 size_t Pos = S1.find_first_not_of(S2);
651 if (Pos == StringRef::npos)
653 return ConstantInt::get(CI->getType(), Pos);
659 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
660 Function *Callee = CI->getCalledFunction();
661 FunctionType *FT = Callee->getFunctionType();
662 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
663 FT->getParamType(1) != FT->getParamType(0) ||
664 !FT->getReturnType()->isIntegerTy())
668 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
669 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
671 // strcspn("", s) -> 0
672 if (HasS1 && S1.empty())
673 return Constant::getNullValue(CI->getType());
676 if (HasS1 && HasS2) {
677 size_t Pos = S1.find_first_of(S2);
678 if (Pos == StringRef::npos)
680 return ConstantInt::get(CI->getType(), Pos);
683 // strcspn(s, "") -> strlen(s)
684 if (HasS2 && S2.empty())
685 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
690 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
691 Function *Callee = CI->getCalledFunction();
692 FunctionType *FT = Callee->getFunctionType();
693 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
694 !FT->getParamType(1)->isPointerTy() ||
695 !FT->getReturnType()->isPointerTy())
698 // fold strstr(x, x) -> x.
699 if (CI->getArgOperand(0) == CI->getArgOperand(1))
700 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
702 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
703 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
704 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
707 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
711 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
712 ICmpInst *Old = cast<ICmpInst>(*UI++);
714 B.CreateICmp(Old->getPredicate(), StrNCmp,
715 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
716 replaceAllUsesWith(Old, Cmp);
721 // See if either input string is a constant string.
722 StringRef SearchStr, ToFindStr;
723 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
724 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
726 // fold strstr(x, "") -> x.
727 if (HasStr2 && ToFindStr.empty())
728 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
730 // If both strings are known, constant fold it.
731 if (HasStr1 && HasStr2) {
732 size_t Offset = SearchStr.find(ToFindStr);
734 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
735 return Constant::getNullValue(CI->getType());
737 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
738 Value *Result = CastToCStr(CI->getArgOperand(0), B);
739 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
740 return B.CreateBitCast(Result, CI->getType());
743 // fold strstr(x, "y") -> strchr(x, 'y').
744 if (HasStr2 && ToFindStr.size() == 1) {
745 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
746 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
751 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
752 Function *Callee = CI->getCalledFunction();
753 FunctionType *FT = Callee->getFunctionType();
754 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
755 !FT->getParamType(1)->isIntegerTy(32) ||
756 !FT->getParamType(2)->isIntegerTy() ||
757 !FT->getReturnType()->isPointerTy())
760 Value *SrcStr = CI->getArgOperand(0);
761 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
762 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
764 // memchr(x, y, 0) -> null
765 if (LenC && LenC->isNullValue())
766 return Constant::getNullValue(CI->getType());
768 // From now on we need at least constant length and string.
770 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
773 // Truncate the string to LenC. If Str is smaller than LenC we will still only
774 // scan the string, as reading past the end of it is undefined and we can just
775 // return null if we don't find the char.
776 Str = Str.substr(0, LenC->getZExtValue());
778 // If the char is variable but the input str and length are not we can turn
779 // this memchr call into a simple bit field test. Of course this only works
780 // when the return value is only checked against null.
782 // It would be really nice to reuse switch lowering here but we can't change
783 // the CFG at this point.
785 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
786 // after bounds check.
787 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
789 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
790 reinterpret_cast<const unsigned char *>(Str.end()));
792 // Make sure the bit field we're about to create fits in a register on the
794 // FIXME: On a 64 bit architecture this prevents us from using the
795 // interesting range of alpha ascii chars. We could do better by emitting
796 // two bitfields or shifting the range by 64 if no lower chars are used.
797 if (!DL.fitsInLegalInteger(Max + 1))
800 // For the bit field use a power-of-2 type with at least 8 bits to avoid
801 // creating unnecessary illegal types.
802 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
804 // Now build the bit field.
805 APInt Bitfield(Width, 0);
807 Bitfield.setBit((unsigned char)C);
808 Value *BitfieldC = B.getInt(Bitfield);
810 // First check that the bit field access is within bounds.
811 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
812 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
815 // Create code that checks if the given bit is set in the field.
816 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
817 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
819 // Finally merge both checks and cast to pointer type. The inttoptr
820 // implicitly zexts the i1 to intptr type.
821 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
824 // Check if all arguments are constants. If so, we can constant fold.
828 // Compute the offset.
829 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
830 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
831 return Constant::getNullValue(CI->getType());
833 // memchr(s+n,c,l) -> gep(s+n+i,c)
834 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
837 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
838 Function *Callee = CI->getCalledFunction();
839 FunctionType *FT = Callee->getFunctionType();
840 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
841 !FT->getParamType(1)->isPointerTy() ||
842 !FT->getReturnType()->isIntegerTy(32))
845 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
847 if (LHS == RHS) // memcmp(s,s,x) -> 0
848 return Constant::getNullValue(CI->getType());
850 // Make sure we have a constant length.
851 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
854 uint64_t Len = LenC->getZExtValue();
856 if (Len == 0) // memcmp(s1,s2,0) -> 0
857 return Constant::getNullValue(CI->getType());
859 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
861 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
862 CI->getType(), "lhsv");
863 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
864 CI->getType(), "rhsv");
865 return B.CreateSub(LHSV, RHSV, "chardiff");
868 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
869 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
871 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
872 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
874 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
875 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
878 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
880 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
882 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
883 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
885 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
889 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
890 StringRef LHSStr, RHSStr;
891 if (getConstantStringInfo(LHS, LHSStr) &&
892 getConstantStringInfo(RHS, RHSStr)) {
893 // Make sure we're not reading out-of-bounds memory.
894 if (Len > LHSStr.size() || Len > RHSStr.size())
896 // Fold the memcmp and normalize the result. This way we get consistent
897 // results across multiple platforms.
899 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
904 return ConstantInt::get(CI->getType(), Ret);
910 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
911 Function *Callee = CI->getCalledFunction();
913 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
916 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
917 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
918 CI->getArgOperand(2), 1);
919 return CI->getArgOperand(0);
922 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
923 Function *Callee = CI->getCalledFunction();
925 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
928 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
929 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
930 CI->getArgOperand(2), 1);
931 return CI->getArgOperand(0);
934 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
935 Function *Callee = CI->getCalledFunction();
937 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
940 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
941 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
942 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
943 return CI->getArgOperand(0);
946 //===----------------------------------------------------------------------===//
947 // Math Library Optimizations
948 //===----------------------------------------------------------------------===//
950 /// Return a variant of Val with float type.
951 /// Currently this works in two cases: If Val is an FPExtension of a float
952 /// value to something bigger, simply return the operand.
953 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
954 /// loss of precision do so.
955 static Value *valueHasFloatPrecision(Value *Val) {
956 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
957 Value *Op = Cast->getOperand(0);
958 if (Op->getType()->isFloatTy())
961 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
962 APFloat F = Const->getValueAPF();
964 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
967 return ConstantFP::get(Const->getContext(), F);
972 //===----------------------------------------------------------------------===//
973 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
975 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
977 Function *Callee = CI->getCalledFunction();
978 FunctionType *FT = Callee->getFunctionType();
979 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
980 !FT->getParamType(0)->isDoubleTy())
984 // Check if all the uses for function like 'sin' are converted to float.
985 for (User *U : CI->users()) {
986 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
987 if (!Cast || !Cast->getType()->isFloatTy())
992 // If this is something like 'floor((double)floatval)', convert to floorf.
993 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
997 // floor((double)floatval) -> (double)floorf(floatval)
998 if (Callee->isIntrinsic()) {
999 Module *M = CI->getParent()->getParent()->getParent();
1000 Intrinsic::ID IID = Callee->getIntrinsicID();
1001 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1002 V = B.CreateCall(F, V);
1004 // The call is a library call rather than an intrinsic.
1005 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1008 return B.CreateFPExt(V, B.getDoubleTy());
1011 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1012 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1013 Function *Callee = CI->getCalledFunction();
1014 FunctionType *FT = Callee->getFunctionType();
1015 // Just make sure this has 2 arguments of the same FP type, which match the
1017 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1018 FT->getParamType(0) != FT->getParamType(1) ||
1019 !FT->getParamType(0)->isFloatingPointTy())
1022 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1023 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1024 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1027 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1031 // fmin((double)floatval1, (double)floatval2)
1032 // -> (double)fminf(floatval1, floatval2)
1033 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1034 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1035 Callee->getAttributes());
1036 return B.CreateFPExt(V, B.getDoubleTy());
1039 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1040 Function *Callee = CI->getCalledFunction();
1041 Value *Ret = nullptr;
1042 StringRef Name = Callee->getName();
1043 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1044 Ret = optimizeUnaryDoubleFP(CI, B, true);
1046 FunctionType *FT = Callee->getFunctionType();
1047 // Just make sure this has 1 argument of FP type, which matches the
1049 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1050 !FT->getParamType(0)->isFloatingPointTy())
1053 // cos(-x) -> cos(x)
1054 Value *Op1 = CI->getArgOperand(0);
1055 if (BinaryOperator::isFNeg(Op1)) {
1056 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1057 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1062 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1063 Function *Callee = CI->getCalledFunction();
1064 Value *Ret = nullptr;
1065 StringRef Name = Callee->getName();
1066 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1067 Ret = optimizeUnaryDoubleFP(CI, B, true);
1069 FunctionType *FT = Callee->getFunctionType();
1070 // Just make sure this has 2 arguments of the same FP type, which match the
1072 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1073 FT->getParamType(0) != FT->getParamType(1) ||
1074 !FT->getParamType(0)->isFloatingPointTy())
1077 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1078 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1079 // pow(1.0, x) -> 1.0
1080 if (Op1C->isExactlyValue(1.0))
1082 // pow(2.0, x) -> exp2(x)
1083 if (Op1C->isExactlyValue(2.0) &&
1084 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1086 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1087 Callee->getAttributes());
1088 // pow(10.0, x) -> exp10(x)
1089 if (Op1C->isExactlyValue(10.0) &&
1090 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1092 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1093 Callee->getAttributes());
1096 bool unsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1098 // pow(exp(x), y) -> exp(x*y)
1099 // pow(exp2(x), y) -> exp2(x * y)
1100 // We enable these only under fast-math. Besides rounding
1101 // differences the transformation changes overflow and
1102 // underflow behavior quite dramatically.
1103 // Example: x = 1000, y = 0.001.
1104 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1106 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1107 IRBuilder<>::FastMathFlagGuard Guard(B);
1109 FMF.setUnsafeAlgebra();
1110 B.SetFastMathFlags(FMF);
1113 Function *OpCCallee = OpC->getCalledFunction();
1114 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1115 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2))
1116 return EmitUnaryFloatFnCall(
1117 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"),
1118 OpCCallee->getName(), B, OpCCallee->getAttributes());
1122 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1126 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1127 return ConstantFP::get(CI->getType(), 1.0);
1129 if (Op2C->isExactlyValue(0.5) &&
1130 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1132 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1135 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1137 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1138 Callee->getAttributes());
1140 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1141 // This is faster than calling pow, and still handles negative zero
1142 // and negative infinity correctly.
1143 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1144 Value *Inf = ConstantFP::getInfinity(CI->getType());
1145 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1146 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1148 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1149 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1150 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1154 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1156 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1157 return B.CreateFMul(Op1, Op1, "pow2");
1158 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1159 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1163 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1164 Function *Callee = CI->getCalledFunction();
1165 Function *Caller = CI->getParent()->getParent();
1166 Value *Ret = nullptr;
1167 StringRef Name = Callee->getName();
1168 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1169 Ret = optimizeUnaryDoubleFP(CI, B, true);
1171 FunctionType *FT = Callee->getFunctionType();
1172 // Just make sure this has 1 argument of FP type, which matches the
1174 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1175 !FT->getParamType(0)->isFloatingPointTy())
1178 Value *Op = CI->getArgOperand(0);
1179 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1180 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1181 LibFunc::Func LdExp = LibFunc::ldexpl;
1182 if (Op->getType()->isFloatTy())
1183 LdExp = LibFunc::ldexpf;
1184 else if (Op->getType()->isDoubleTy())
1185 LdExp = LibFunc::ldexp;
1187 if (TLI->has(LdExp)) {
1188 Value *LdExpArg = nullptr;
1189 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1190 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1191 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1192 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1193 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1194 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1198 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1199 if (!Op->getType()->isFloatTy())
1200 One = ConstantExpr::getFPExtend(One, Op->getType());
1202 Module *M = Caller->getParent();
1204 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1205 Op->getType(), B.getInt32Ty(), nullptr);
1206 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1207 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1208 CI->setCallingConv(F->getCallingConv());
1216 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1217 Function *Callee = CI->getCalledFunction();
1218 Value *Ret = nullptr;
1219 StringRef Name = Callee->getName();
1220 if (Name == "fabs" && hasFloatVersion(Name))
1221 Ret = optimizeUnaryDoubleFP(CI, B, false);
1223 FunctionType *FT = Callee->getFunctionType();
1224 // Make sure this has 1 argument of FP type which matches the result type.
1225 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1226 !FT->getParamType(0)->isFloatingPointTy())
1229 Value *Op = CI->getArgOperand(0);
1230 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1231 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1232 if (I->getOpcode() == Instruction::FMul)
1233 if (I->getOperand(0) == I->getOperand(1))
1239 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1240 // If we can shrink the call to a float function rather than a double
1241 // function, do that first.
1242 Function *Callee = CI->getCalledFunction();
1243 StringRef Name = Callee->getName();
1244 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1245 (Name == "fmax" && hasFloatVersion(Name))) {
1246 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1251 // Make sure this has 2 arguments of FP type which match the result type.
1252 FunctionType *FT = Callee->getFunctionType();
1253 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1254 FT->getParamType(0) != FT->getParamType(1) ||
1255 !FT->getParamType(0)->isFloatingPointTy())
1258 IRBuilder<>::FastMathFlagGuard Guard(B);
1260 Function *F = CI->getParent()->getParent();
1261 if (canUseUnsafeFPMath(F)) {
1262 // Unsafe algebra sets all fast-math-flags to true.
1263 FMF.setUnsafeAlgebra();
1265 // At a minimum, no-nans-fp-math must be true.
1266 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
1267 if (Attr.getValueAsString() != "true")
1269 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1270 // "Ideally, fmax would be sensitive to the sign of zero, for example
1271 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1272 // might be impractical."
1273 FMF.setNoSignedZeros();
1276 B.SetFastMathFlags(FMF);
1278 // We have a relaxed floating-point environment. We can ignore NaN-handling
1279 // and transform to a compare and select. We do not have to consider errno or
1280 // exceptions, because fmin/fmax do not have those.
1281 Value *Op0 = CI->getArgOperand(0);
1282 Value *Op1 = CI->getArgOperand(1);
1283 Value *Cmp = Callee->getName().startswith("fmin") ?
1284 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1285 return B.CreateSelect(Cmp, Op0, Op1);
1288 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1289 Function *Callee = CI->getCalledFunction();
1291 Value *Ret = nullptr;
1292 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1293 Callee->getIntrinsicID() == Intrinsic::sqrt))
1294 Ret = optimizeUnaryDoubleFP(CI, B, true);
1295 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1298 Value *Op = CI->getArgOperand(0);
1299 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1300 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1301 // We're looking for a repeated factor in a multiplication tree,
1302 // so we can do this fold: sqrt(x * x) -> fabs(x);
1303 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1304 Value *Op0 = I->getOperand(0);
1305 Value *Op1 = I->getOperand(1);
1306 Value *RepeatOp = nullptr;
1307 Value *OtherOp = nullptr;
1309 // Simple match: the operands of the multiply are identical.
1312 // Look for a more complicated pattern: one of the operands is itself
1313 // a multiply, so search for a common factor in that multiply.
1314 // Note: We don't bother looking any deeper than this first level or for
1315 // variations of this pattern because instcombine's visitFMUL and/or the
1316 // reassociation pass should give us this form.
1317 Value *OtherMul0, *OtherMul1;
1318 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1319 // Pattern: sqrt((x * y) * z)
1320 if (OtherMul0 == OtherMul1) {
1321 // Matched: sqrt((x * x) * z)
1322 RepeatOp = OtherMul0;
1328 // Fast math flags for any created instructions should match the sqrt
1330 // FIXME: We're not checking the sqrt because it doesn't have
1331 // fast-math-flags (see earlier comment).
1332 IRBuilder<>::FastMathFlagGuard Guard(B);
1333 B.SetFastMathFlags(I->getFastMathFlags());
1334 // If we found a repeated factor, hoist it out of the square root and
1335 // replace it with the fabs of that factor.
1336 Module *M = Callee->getParent();
1337 Type *ArgType = Op->getType();
1338 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1339 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1341 // If we found a non-repeated factor, we still need to get its square
1342 // root. We then multiply that by the value that was simplified out
1343 // of the square root calculation.
1344 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1345 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1346 return B.CreateFMul(FabsCall, SqrtCall);
1355 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1356 Function *Callee = CI->getCalledFunction();
1357 Value *Ret = nullptr;
1358 StringRef Name = Callee->getName();
1359 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1360 Ret = optimizeUnaryDoubleFP(CI, B, true);
1361 FunctionType *FT = Callee->getFunctionType();
1363 // Just make sure this has 1 argument of FP type, which matches the
1365 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1366 !FT->getParamType(0)->isFloatingPointTy())
1369 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1371 Value *Op1 = CI->getArgOperand(0);
1372 auto *OpC = dyn_cast<CallInst>(Op1);
1376 // tan(atan(x)) -> x
1377 // tanf(atanf(x)) -> x
1378 // tanl(atanl(x)) -> x
1380 Function *F = OpC->getCalledFunction();
1381 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1382 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1383 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1384 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1385 Ret = OpC->getArgOperand(0);
1389 static bool isTrigLibCall(CallInst *CI);
1390 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1391 bool UseFloat, Value *&Sin, Value *&Cos,
1394 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1396 // Make sure the prototype is as expected, otherwise the rest of the
1397 // function is probably invalid and likely to abort.
1398 if (!isTrigLibCall(CI))
1401 Value *Arg = CI->getArgOperand(0);
1402 SmallVector<CallInst *, 1> SinCalls;
1403 SmallVector<CallInst *, 1> CosCalls;
1404 SmallVector<CallInst *, 1> SinCosCalls;
1406 bool IsFloat = Arg->getType()->isFloatTy();
1408 // Look for all compatible sinpi, cospi and sincospi calls with the same
1409 // argument. If there are enough (in some sense) we can make the
1411 for (User *U : Arg->users())
1412 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1415 // It's only worthwhile if both sinpi and cospi are actually used.
1416 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1419 Value *Sin, *Cos, *SinCos;
1420 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1422 replaceTrigInsts(SinCalls, Sin);
1423 replaceTrigInsts(CosCalls, Cos);
1424 replaceTrigInsts(SinCosCalls, SinCos);
1429 static bool isTrigLibCall(CallInst *CI) {
1430 Function *Callee = CI->getCalledFunction();
1431 FunctionType *FT = Callee->getFunctionType();
1433 // We can only hope to do anything useful if we can ignore things like errno
1434 // and floating-point exceptions.
1435 bool AttributesSafe =
1436 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1438 // Other than that we need float(float) or double(double)
1439 return AttributesSafe && FT->getNumParams() == 1 &&
1440 FT->getReturnType() == FT->getParamType(0) &&
1441 (FT->getParamType(0)->isFloatTy() ||
1442 FT->getParamType(0)->isDoubleTy());
1446 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1447 SmallVectorImpl<CallInst *> &SinCalls,
1448 SmallVectorImpl<CallInst *> &CosCalls,
1449 SmallVectorImpl<CallInst *> &SinCosCalls) {
1450 CallInst *CI = dyn_cast<CallInst>(Val);
1455 Function *Callee = CI->getCalledFunction();
1457 if (Callee && (!TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1458 !isTrigLibCall(CI)))
1462 if (Func == LibFunc::sinpif)
1463 SinCalls.push_back(CI);
1464 else if (Func == LibFunc::cospif)
1465 CosCalls.push_back(CI);
1466 else if (Func == LibFunc::sincospif_stret)
1467 SinCosCalls.push_back(CI);
1469 if (Func == LibFunc::sinpi)
1470 SinCalls.push_back(CI);
1471 else if (Func == LibFunc::cospi)
1472 CosCalls.push_back(CI);
1473 else if (Func == LibFunc::sincospi_stret)
1474 SinCosCalls.push_back(CI);
1478 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1480 for (CallInst *C : Calls)
1481 replaceAllUsesWith(C, Res);
1484 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1485 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1486 Type *ArgTy = Arg->getType();
1490 Triple T(OrigCallee->getParent()->getTargetTriple());
1492 Name = "__sincospif_stret";
1494 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1495 // x86_64 can't use {float, float} since that would be returned in both
1496 // xmm0 and xmm1, which isn't what a real struct would do.
1497 ResTy = T.getArch() == Triple::x86_64
1498 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1499 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1501 Name = "__sincospi_stret";
1502 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1505 Module *M = OrigCallee->getParent();
1506 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1507 ResTy, ArgTy, nullptr);
1509 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1510 // If the argument is an instruction, it must dominate all uses so put our
1511 // sincos call there.
1512 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1514 // Otherwise (e.g. for a constant) the beginning of the function is as
1515 // good a place as any.
1516 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1517 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1520 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1522 if (SinCos->getType()->isStructTy()) {
1523 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1524 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1526 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1528 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1533 //===----------------------------------------------------------------------===//
1534 // Integer Library Call Optimizations
1535 //===----------------------------------------------------------------------===//
1537 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1538 FunctionType *FT = Callee->getFunctionType();
1539 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1540 FT->getParamType(0)->isIntegerTy();
1543 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1544 Function *Callee = CI->getCalledFunction();
1545 if (!checkIntUnaryReturnAndParam(Callee))
1547 Value *Op = CI->getArgOperand(0);
1550 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1551 if (CI->isZero()) // ffs(0) -> 0.
1552 return B.getInt32(0);
1553 // ffs(c) -> cttz(c)+1
1554 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1557 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1558 Type *ArgType = Op->getType();
1560 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1561 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1562 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1563 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1565 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1566 return B.CreateSelect(Cond, V, B.getInt32(0));
1569 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1570 Function *Callee = CI->getCalledFunction();
1571 FunctionType *FT = Callee->getFunctionType();
1572 // We require integer(integer) where the types agree.
1573 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1574 FT->getParamType(0) != FT->getReturnType())
1577 // abs(x) -> x >s -1 ? x : -x
1578 Value *Op = CI->getArgOperand(0);
1580 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1581 Value *Neg = B.CreateNeg(Op, "neg");
1582 return B.CreateSelect(Pos, Op, Neg);
1585 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1586 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1589 // isdigit(c) -> (c-'0') <u 10
1590 Value *Op = CI->getArgOperand(0);
1591 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1592 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1593 return B.CreateZExt(Op, CI->getType());
1596 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1597 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1600 // isascii(c) -> c <u 128
1601 Value *Op = CI->getArgOperand(0);
1602 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1603 return B.CreateZExt(Op, CI->getType());
1606 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1607 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1610 // toascii(c) -> c & 0x7f
1611 return B.CreateAnd(CI->getArgOperand(0),
1612 ConstantInt::get(CI->getType(), 0x7F));
1615 //===----------------------------------------------------------------------===//
1616 // Formatting and IO Library Call Optimizations
1617 //===----------------------------------------------------------------------===//
1619 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1621 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1623 // Error reporting calls should be cold, mark them as such.
1624 // This applies even to non-builtin calls: it is only a hint and applies to
1625 // functions that the frontend might not understand as builtins.
1627 // This heuristic was suggested in:
1628 // Improving Static Branch Prediction in a Compiler
1629 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1630 // Proceedings of PACT'98, Oct. 1998, IEEE
1631 Function *Callee = CI->getCalledFunction();
1633 if (!CI->hasFnAttr(Attribute::Cold) &&
1634 isReportingError(Callee, CI, StreamArg)) {
1635 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1641 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1642 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1648 // These functions might be considered cold, but only if their stream
1649 // argument is stderr.
1651 if (StreamArg >= (int)CI->getNumArgOperands())
1653 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1656 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1657 if (!GV || !GV->isDeclaration())
1659 return GV->getName() == "stderr";
1662 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1663 // Check for a fixed format string.
1664 StringRef FormatStr;
1665 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1668 // Empty format string -> noop.
1669 if (FormatStr.empty()) // Tolerate printf's declared void.
1670 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1672 // Do not do any of the following transformations if the printf return value
1673 // is used, in general the printf return value is not compatible with either
1674 // putchar() or puts().
1675 if (!CI->use_empty())
1678 // printf("x") -> putchar('x'), even for '%'.
1679 if (FormatStr.size() == 1) {
1680 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1681 if (CI->use_empty() || !Res)
1683 return B.CreateIntCast(Res, CI->getType(), true);
1686 // printf("foo\n") --> puts("foo")
1687 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1688 FormatStr.find('%') == StringRef::npos) { // No format characters.
1689 // Create a string literal with no \n on it. We expect the constant merge
1690 // pass to be run after this pass, to merge duplicate strings.
1691 FormatStr = FormatStr.drop_back();
1692 Value *GV = B.CreateGlobalString(FormatStr, "str");
1693 Value *NewCI = EmitPutS(GV, B, TLI);
1694 return (CI->use_empty() || !NewCI)
1696 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1699 // Optimize specific format strings.
1700 // printf("%c", chr) --> putchar(chr)
1701 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1702 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1703 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1705 if (CI->use_empty() || !Res)
1707 return B.CreateIntCast(Res, CI->getType(), true);
1710 // printf("%s\n", str) --> puts(str)
1711 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1712 CI->getArgOperand(1)->getType()->isPointerTy()) {
1713 return EmitPutS(CI->getArgOperand(1), B, TLI);
1718 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1720 Function *Callee = CI->getCalledFunction();
1721 // Require one fixed pointer argument and an integer/void result.
1722 FunctionType *FT = Callee->getFunctionType();
1723 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1724 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1727 if (Value *V = optimizePrintFString(CI, B)) {
1731 // printf(format, ...) -> iprintf(format, ...) if no floating point
1733 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1734 Module *M = B.GetInsertBlock()->getParent()->getParent();
1735 Constant *IPrintFFn =
1736 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1737 CallInst *New = cast<CallInst>(CI->clone());
1738 New->setCalledFunction(IPrintFFn);
1745 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1746 // Check for a fixed format string.
1747 StringRef FormatStr;
1748 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1751 // If we just have a format string (nothing else crazy) transform it.
1752 if (CI->getNumArgOperands() == 2) {
1753 // Make sure there's no % in the constant array. We could try to handle
1754 // %% -> % in the future if we cared.
1755 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1756 if (FormatStr[i] == '%')
1757 return nullptr; // we found a format specifier, bail out.
1759 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1760 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1761 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1762 FormatStr.size() + 1),
1763 1); // Copy the null byte.
1764 return ConstantInt::get(CI->getType(), FormatStr.size());
1767 // The remaining optimizations require the format string to be "%s" or "%c"
1768 // and have an extra operand.
1769 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1770 CI->getNumArgOperands() < 3)
1773 // Decode the second character of the format string.
1774 if (FormatStr[1] == 'c') {
1775 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1776 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1778 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1779 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1780 B.CreateStore(V, Ptr);
1781 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1782 B.CreateStore(B.getInt8(0), Ptr);
1784 return ConstantInt::get(CI->getType(), 1);
1787 if (FormatStr[1] == 's') {
1788 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1789 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1792 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1796 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1797 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1799 // The sprintf result is the unincremented number of bytes in the string.
1800 return B.CreateIntCast(Len, CI->getType(), false);
1805 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1806 Function *Callee = CI->getCalledFunction();
1807 // Require two fixed pointer arguments and an integer result.
1808 FunctionType *FT = Callee->getFunctionType();
1809 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1810 !FT->getParamType(1)->isPointerTy() ||
1811 !FT->getReturnType()->isIntegerTy())
1814 if (Value *V = optimizeSPrintFString(CI, B)) {
1818 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1820 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1821 Module *M = B.GetInsertBlock()->getParent()->getParent();
1822 Constant *SIPrintFFn =
1823 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1824 CallInst *New = cast<CallInst>(CI->clone());
1825 New->setCalledFunction(SIPrintFFn);
1832 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1833 optimizeErrorReporting(CI, B, 0);
1835 // All the optimizations depend on the format string.
1836 StringRef FormatStr;
1837 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1840 // Do not do any of the following transformations if the fprintf return
1841 // value is used, in general the fprintf return value is not compatible
1842 // with fwrite(), fputc() or fputs().
1843 if (!CI->use_empty())
1846 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1847 if (CI->getNumArgOperands() == 2) {
1848 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1849 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1850 return nullptr; // We found a format specifier.
1853 CI->getArgOperand(1),
1854 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1855 CI->getArgOperand(0), B, DL, TLI);
1858 // The remaining optimizations require the format string to be "%s" or "%c"
1859 // and have an extra operand.
1860 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1861 CI->getNumArgOperands() < 3)
1864 // Decode the second character of the format string.
1865 if (FormatStr[1] == 'c') {
1866 // fprintf(F, "%c", chr) --> fputc(chr, F)
1867 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1869 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1872 if (FormatStr[1] == 's') {
1873 // fprintf(F, "%s", str) --> fputs(str, F)
1874 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1876 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1881 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1882 Function *Callee = CI->getCalledFunction();
1883 // Require two fixed paramters as pointers and integer result.
1884 FunctionType *FT = Callee->getFunctionType();
1885 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1886 !FT->getParamType(1)->isPointerTy() ||
1887 !FT->getReturnType()->isIntegerTy())
1890 if (Value *V = optimizeFPrintFString(CI, B)) {
1894 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1895 // floating point arguments.
1896 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1897 Module *M = B.GetInsertBlock()->getParent()->getParent();
1898 Constant *FIPrintFFn =
1899 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1900 CallInst *New = cast<CallInst>(CI->clone());
1901 New->setCalledFunction(FIPrintFFn);
1908 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1909 optimizeErrorReporting(CI, B, 3);
1911 Function *Callee = CI->getCalledFunction();
1912 // Require a pointer, an integer, an integer, a pointer, returning integer.
1913 FunctionType *FT = Callee->getFunctionType();
1914 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1915 !FT->getParamType(1)->isIntegerTy() ||
1916 !FT->getParamType(2)->isIntegerTy() ||
1917 !FT->getParamType(3)->isPointerTy() ||
1918 !FT->getReturnType()->isIntegerTy())
1921 // Get the element size and count.
1922 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1923 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1924 if (!SizeC || !CountC)
1926 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1928 // If this is writing zero records, remove the call (it's a noop).
1930 return ConstantInt::get(CI->getType(), 0);
1932 // If this is writing one byte, turn it into fputc.
1933 // This optimisation is only valid, if the return value is unused.
1934 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1935 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1936 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1937 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1943 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1944 optimizeErrorReporting(CI, B, 1);
1946 Function *Callee = CI->getCalledFunction();
1948 // Require two pointers. Also, we can't optimize if return value is used.
1949 FunctionType *FT = Callee->getFunctionType();
1950 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1951 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1954 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1955 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1959 // Known to have no uses (see above).
1961 CI->getArgOperand(0),
1962 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1963 CI->getArgOperand(1), B, DL, TLI);
1966 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1967 Function *Callee = CI->getCalledFunction();
1968 // Require one fixed pointer argument and an integer/void result.
1969 FunctionType *FT = Callee->getFunctionType();
1970 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1971 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1974 // Check for a constant string.
1976 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1979 if (Str.empty() && CI->use_empty()) {
1980 // puts("") -> putchar('\n')
1981 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1982 if (CI->use_empty() || !Res)
1984 return B.CreateIntCast(Res, CI->getType(), true);
1990 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1992 SmallString<20> FloatFuncName = FuncName;
1993 FloatFuncName += 'f';
1994 if (TLI->getLibFunc(FloatFuncName, Func))
1995 return TLI->has(Func);
1999 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2000 IRBuilder<> &Builder) {
2002 Function *Callee = CI->getCalledFunction();
2003 StringRef FuncName = Callee->getName();
2005 // Check for string/memory library functions.
2006 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2007 // Make sure we never change the calling convention.
2008 assert((ignoreCallingConv(Func) ||
2009 CI->getCallingConv() == llvm::CallingConv::C) &&
2010 "Optimizing string/memory libcall would change the calling convention");
2012 case LibFunc::strcat:
2013 return optimizeStrCat(CI, Builder);
2014 case LibFunc::strncat:
2015 return optimizeStrNCat(CI, Builder);
2016 case LibFunc::strchr:
2017 return optimizeStrChr(CI, Builder);
2018 case LibFunc::strrchr:
2019 return optimizeStrRChr(CI, Builder);
2020 case LibFunc::strcmp:
2021 return optimizeStrCmp(CI, Builder);
2022 case LibFunc::strncmp:
2023 return optimizeStrNCmp(CI, Builder);
2024 case LibFunc::strcpy:
2025 return optimizeStrCpy(CI, Builder);
2026 case LibFunc::stpcpy:
2027 return optimizeStpCpy(CI, Builder);
2028 case LibFunc::strncpy:
2029 return optimizeStrNCpy(CI, Builder);
2030 case LibFunc::strlen:
2031 return optimizeStrLen(CI, Builder);
2032 case LibFunc::strpbrk:
2033 return optimizeStrPBrk(CI, Builder);
2034 case LibFunc::strtol:
2035 case LibFunc::strtod:
2036 case LibFunc::strtof:
2037 case LibFunc::strtoul:
2038 case LibFunc::strtoll:
2039 case LibFunc::strtold:
2040 case LibFunc::strtoull:
2041 return optimizeStrTo(CI, Builder);
2042 case LibFunc::strspn:
2043 return optimizeStrSpn(CI, Builder);
2044 case LibFunc::strcspn:
2045 return optimizeStrCSpn(CI, Builder);
2046 case LibFunc::strstr:
2047 return optimizeStrStr(CI, Builder);
2048 case LibFunc::memchr:
2049 return optimizeMemChr(CI, Builder);
2050 case LibFunc::memcmp:
2051 return optimizeMemCmp(CI, Builder);
2052 case LibFunc::memcpy:
2053 return optimizeMemCpy(CI, Builder);
2054 case LibFunc::memmove:
2055 return optimizeMemMove(CI, Builder);
2056 case LibFunc::memset:
2057 return optimizeMemSet(CI, Builder);
2065 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2066 if (CI->isNoBuiltin())
2070 Function *Callee = CI->getCalledFunction();
2071 StringRef FuncName = Callee->getName();
2072 IRBuilder<> Builder(CI);
2073 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2075 // Command-line parameter overrides function attribute.
2076 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2077 UnsafeFPShrink = EnableUnsafeFPShrink;
2078 else if (canUseUnsafeFPMath(Callee))
2079 UnsafeFPShrink = true;
2081 // First, check for intrinsics.
2082 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2083 if (!isCallingConvC)
2085 switch (II->getIntrinsicID()) {
2086 case Intrinsic::pow:
2087 return optimizePow(CI, Builder);
2088 case Intrinsic::exp2:
2089 return optimizeExp2(CI, Builder);
2090 case Intrinsic::fabs:
2091 return optimizeFabs(CI, Builder);
2092 case Intrinsic::sqrt:
2093 return optimizeSqrt(CI, Builder);
2099 // Also try to simplify calls to fortified library functions.
2100 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2101 // Try to further simplify the result.
2102 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2103 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2104 // Use an IR Builder from SimplifiedCI if available instead of CI
2105 // to guarantee we reach all uses we might replace later on.
2106 IRBuilder<> TmpBuilder(SimplifiedCI);
2107 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2108 // If we were able to further simplify, remove the now redundant call.
2109 SimplifiedCI->replaceAllUsesWith(V);
2110 SimplifiedCI->eraseFromParent();
2114 return SimplifiedFortifiedCI;
2117 // Then check for known library functions.
2118 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2119 // We never change the calling convention.
2120 if (!ignoreCallingConv(Func) && !isCallingConvC)
2122 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2128 return optimizeCos(CI, Builder);
2129 case LibFunc::sinpif:
2130 case LibFunc::sinpi:
2131 case LibFunc::cospif:
2132 case LibFunc::cospi:
2133 return optimizeSinCosPi(CI, Builder);
2137 return optimizePow(CI, Builder);
2138 case LibFunc::exp2l:
2140 case LibFunc::exp2f:
2141 return optimizeExp2(CI, Builder);
2142 case LibFunc::fabsf:
2144 case LibFunc::fabsl:
2145 return optimizeFabs(CI, Builder);
2146 case LibFunc::sqrtf:
2148 case LibFunc::sqrtl:
2149 return optimizeSqrt(CI, Builder);
2152 case LibFunc::ffsll:
2153 return optimizeFFS(CI, Builder);
2156 case LibFunc::llabs:
2157 return optimizeAbs(CI, Builder);
2158 case LibFunc::isdigit:
2159 return optimizeIsDigit(CI, Builder);
2160 case LibFunc::isascii:
2161 return optimizeIsAscii(CI, Builder);
2162 case LibFunc::toascii:
2163 return optimizeToAscii(CI, Builder);
2164 case LibFunc::printf:
2165 return optimizePrintF(CI, Builder);
2166 case LibFunc::sprintf:
2167 return optimizeSPrintF(CI, Builder);
2168 case LibFunc::fprintf:
2169 return optimizeFPrintF(CI, Builder);
2170 case LibFunc::fwrite:
2171 return optimizeFWrite(CI, Builder);
2172 case LibFunc::fputs:
2173 return optimizeFPuts(CI, Builder);
2175 return optimizePuts(CI, Builder);
2179 return optimizeTan(CI, Builder);
2180 case LibFunc::perror:
2181 return optimizeErrorReporting(CI, Builder);
2182 case LibFunc::vfprintf:
2183 case LibFunc::fiprintf:
2184 return optimizeErrorReporting(CI, Builder, 0);
2185 case LibFunc::fputc:
2186 return optimizeErrorReporting(CI, Builder, 1);
2188 case LibFunc::floor:
2190 case LibFunc::round:
2191 case LibFunc::nearbyint:
2192 case LibFunc::trunc:
2193 if (hasFloatVersion(FuncName))
2194 return optimizeUnaryDoubleFP(CI, Builder, false);
2197 case LibFunc::acosh:
2199 case LibFunc::asinh:
2201 case LibFunc::atanh:
2205 case LibFunc::exp10:
2206 case LibFunc::expm1:
2208 case LibFunc::log10:
2209 case LibFunc::log1p:
2215 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2216 return optimizeUnaryDoubleFP(CI, Builder, true);
2218 case LibFunc::copysign:
2219 if (hasFloatVersion(FuncName))
2220 return optimizeBinaryDoubleFP(CI, Builder);
2222 case LibFunc::fminf:
2224 case LibFunc::fminl:
2225 case LibFunc::fmaxf:
2227 case LibFunc::fmaxl:
2228 return optimizeFMinFMax(CI, Builder);
2236 LibCallSimplifier::LibCallSimplifier(
2237 const DataLayout &DL, const TargetLibraryInfo *TLI,
2238 function_ref<void(Instruction *, Value *)> Replacer)
2239 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2240 Replacer(Replacer) {}
2242 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2243 // Indirect through the replacer used in this instance.
2248 // Additional cases that we need to add to this file:
2251 // * cbrt(expN(X)) -> expN(x/3)
2252 // * cbrt(sqrt(x)) -> pow(x,1/6)
2253 // * cbrt(cbrt(x)) -> pow(x,1/9)
2256 // * exp(log(x)) -> x
2259 // * log(exp(x)) -> x
2260 // * log(x**y) -> y*log(x)
2261 // * log(exp(y)) -> y*log(e)
2262 // * log(exp2(y)) -> y*log(2)
2263 // * log(exp10(y)) -> y*log(10)
2264 // * log(sqrt(x)) -> 0.5*log(x)
2265 // * log(pow(x,y)) -> y*log(x)
2267 // lround, lroundf, lroundl:
2268 // * lround(cnst) -> cnst'
2271 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2272 // * pow(pow(x,y),z)-> pow(x,y*z)
2274 // round, roundf, roundl:
2275 // * round(cnst) -> cnst'
2278 // * signbit(cnst) -> cnst'
2279 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2281 // sqrt, sqrtf, sqrtl:
2282 // * sqrt(expN(x)) -> expN(x*0.5)
2283 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2284 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2286 // trunc, truncf, truncl:
2287 // * trunc(cnst) -> cnst'
2291 //===----------------------------------------------------------------------===//
2292 // Fortified Library Call Optimizations
2293 //===----------------------------------------------------------------------===//
2295 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2299 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2301 if (ConstantInt *ObjSizeCI =
2302 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2303 if (ObjSizeCI->isAllOnesValue())
2305 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2306 if (OnlyLowerUnknownSize)
2309 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2310 // If the length is 0 we don't know how long it is and so we can't
2311 // remove the check.
2314 return ObjSizeCI->getZExtValue() >= Len;
2316 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2317 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2322 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2323 Function *Callee = CI->getCalledFunction();
2325 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2328 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2329 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2330 CI->getArgOperand(2), 1);
2331 return CI->getArgOperand(0);
2336 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2337 Function *Callee = CI->getCalledFunction();
2339 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2342 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2343 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2344 CI->getArgOperand(2), 1);
2345 return CI->getArgOperand(0);
2350 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2351 Function *Callee = CI->getCalledFunction();
2353 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2356 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2357 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2358 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2359 return CI->getArgOperand(0);
2364 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2366 LibFunc::Func Func) {
2367 Function *Callee = CI->getCalledFunction();
2368 StringRef Name = Callee->getName();
2369 const DataLayout &DL = CI->getModule()->getDataLayout();
2371 if (!checkStringCopyLibFuncSignature(Callee, Func))
2374 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2375 *ObjSize = CI->getArgOperand(2);
2377 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2378 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2379 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2380 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2383 // If a) we don't have any length information, or b) we know this will
2384 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2385 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2386 // TODO: It might be nice to get a maximum length out of the possible
2387 // string lengths for varying.
2388 if (isFortifiedCallFoldable(CI, 2, 1, true))
2389 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2391 if (OnlyLowerUnknownSize)
2394 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2395 uint64_t Len = GetStringLength(Src);
2399 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2400 Value *LenV = ConstantInt::get(SizeTTy, Len);
2401 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2402 // If the function was an __stpcpy_chk, and we were able to fold it into
2403 // a __memcpy_chk, we still need to return the correct end pointer.
2404 if (Ret && Func == LibFunc::stpcpy_chk)
2405 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2409 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2411 LibFunc::Func Func) {
2412 Function *Callee = CI->getCalledFunction();
2413 StringRef Name = Callee->getName();
2415 if (!checkStringCopyLibFuncSignature(Callee, Func))
2417 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2418 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2419 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2425 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2426 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2427 // Some clang users checked for _chk libcall availability using:
2428 // __has_builtin(__builtin___memcpy_chk)
2429 // When compiling with -fno-builtin, this is always true.
2430 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2431 // end up with fortified libcalls, which isn't acceptable in a freestanding
2432 // environment which only provides their non-fortified counterparts.
2434 // Until we change clang and/or teach external users to check for availability
2435 // differently, disregard the "nobuiltin" attribute and TLI::has.
2440 Function *Callee = CI->getCalledFunction();
2441 StringRef FuncName = Callee->getName();
2442 IRBuilder<> Builder(CI);
2443 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2445 // First, check that this is a known library functions.
2446 if (!TLI->getLibFunc(FuncName, Func))
2449 // We never change the calling convention.
2450 if (!ignoreCallingConv(Func) && !isCallingConvC)
2454 case LibFunc::memcpy_chk:
2455 return optimizeMemCpyChk(CI, Builder);
2456 case LibFunc::memmove_chk:
2457 return optimizeMemMoveChk(CI, Builder);
2458 case LibFunc::memset_chk:
2459 return optimizeMemSetChk(CI, Builder);
2460 case LibFunc::stpcpy_chk:
2461 case LibFunc::strcpy_chk:
2462 return optimizeStrpCpyChk(CI, Builder, Func);
2463 case LibFunc::stpncpy_chk:
2464 case LibFunc::strncpy_chk:
2465 return optimizeStrpNCpyChk(CI, Builder, Func);
2472 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2473 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2474 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}