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 (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
91 if ((*it)->getType()->isFloatingPointTy())
97 /// \brief Check whether the overloaded unary floating point function
98 /// corresponding to \a Ty is available.
99 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
100 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
101 LibFunc::Func LongDoubleFn) {
102 switch (Ty->getTypeID()) {
103 case Type::FloatTyID:
104 return TLI->has(FloatFn);
105 case Type::DoubleTyID:
106 return TLI->has(DoubleFn);
108 return TLI->has(LongDoubleFn);
112 /// \brief Check whether we can use unsafe floating point math for
113 /// the function passed as input.
114 static bool canUseUnsafeFPMath(Function *F) {
116 // FIXME: For finer-grain optimization, we need intrinsics to have the same
117 // fast-math flag decorations that are applied to FP instructions. For now,
118 // we have to rely on the function-level unsafe-fp-math attribute to do this
119 // optimization because there's no other way to express that the call can be
121 if (F->hasFnAttribute("unsafe-fp-math")) {
122 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
123 if (Attr.getValueAsString() == "true")
129 /// \brief Returns whether \p F matches the signature expected for the
130 /// string/memory copying library function \p Func.
131 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
132 /// Their fortified (_chk) counterparts are also accepted.
133 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
134 const DataLayout &DL = F->getParent()->getDataLayout();
135 FunctionType *FT = F->getFunctionType();
136 LLVMContext &Context = F->getContext();
137 Type *PCharTy = Type::getInt8PtrTy(Context);
138 Type *SizeTTy = DL.getIntPtrType(Context);
139 unsigned NumParams = FT->getNumParams();
141 // All string libfuncs return the same type as the first parameter.
142 if (FT->getReturnType() != FT->getParamType(0))
147 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
148 case LibFunc::stpncpy_chk:
149 case LibFunc::strncpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpncpy:
152 case LibFunc::strncpy: {
153 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
158 case LibFunc::strcpy_chk:
159 case LibFunc::stpcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::stpcpy:
162 case LibFunc::strcpy: {
163 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
164 FT->getParamType(0) != PCharTy)
168 case LibFunc::memmove_chk:
169 case LibFunc::memcpy_chk:
170 --NumParams; // fallthrough
171 case LibFunc::memmove:
172 case LibFunc::memcpy: {
173 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
174 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
178 case LibFunc::memset_chk:
179 --NumParams; // fallthrough
180 case LibFunc::memset: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
187 // If this is a fortified libcall, the last parameter is a size_t.
188 if (NumParams == FT->getNumParams() - 1)
189 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
193 //===----------------------------------------------------------------------===//
194 // String and Memory Library Call Optimizations
195 //===----------------------------------------------------------------------===//
197 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
198 Function *Callee = CI->getCalledFunction();
199 // Verify the "strcat" function prototype.
200 FunctionType *FT = Callee->getFunctionType();
201 if (FT->getNumParams() != 2||
202 FT->getReturnType() != B.getInt8PtrTy() ||
203 FT->getParamType(0) != FT->getReturnType() ||
204 FT->getParamType(1) != FT->getReturnType())
207 // Extract some information from the instruction
208 Value *Dst = CI->getArgOperand(0);
209 Value *Src = CI->getArgOperand(1);
211 // See if we can get the length of the input string.
212 uint64_t Len = GetStringLength(Src);
215 --Len; // Unbias length.
217 // Handle the simple, do-nothing case: strcat(x, "") -> x
221 return emitStrLenMemCpy(Src, Dst, Len, B);
224 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
226 // We need to find the end of the destination string. That's where the
227 // memory is to be moved to. We just generate a call to strlen.
228 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
232 // Now that we have the destination's length, we must index into the
233 // destination's pointer to get the actual memcpy destination (end of
234 // the string .. we're concatenating).
235 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
237 // We have enough information to now generate the memcpy call to do the
238 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
239 B.CreateMemCpy(CpyDst, Src,
240 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
245 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
246 Function *Callee = CI->getCalledFunction();
247 // Verify the "strncat" function prototype.
248 FunctionType *FT = Callee->getFunctionType();
249 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
250 FT->getParamType(0) != FT->getReturnType() ||
251 FT->getParamType(1) != FT->getReturnType() ||
252 !FT->getParamType(2)->isIntegerTy())
255 // Extract some information from the instruction
256 Value *Dst = CI->getArgOperand(0);
257 Value *Src = CI->getArgOperand(1);
260 // We don't do anything if length is not constant
261 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
262 Len = LengthArg->getZExtValue();
266 // See if we can get the length of the input string.
267 uint64_t SrcLen = GetStringLength(Src);
270 --SrcLen; // Unbias length.
272 // Handle the simple, do-nothing cases:
273 // strncat(x, "", c) -> x
274 // strncat(x, c, 0) -> x
275 if (SrcLen == 0 || Len == 0)
278 // We don't optimize this case
282 // strncat(x, s, c) -> strcat(x, s)
283 // s is constant so the strcat can be optimized further
284 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
287 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
288 Function *Callee = CI->getCalledFunction();
289 // Verify the "strchr" function prototype.
290 FunctionType *FT = Callee->getFunctionType();
291 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
292 FT->getParamType(0) != FT->getReturnType() ||
293 !FT->getParamType(1)->isIntegerTy(32))
296 Value *SrcStr = CI->getArgOperand(0);
298 // If the second operand is non-constant, see if we can compute the length
299 // of the input string and turn this into memchr.
300 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
302 uint64_t Len = GetStringLength(SrcStr);
303 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
306 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
307 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
311 // Otherwise, the character is a constant, see if the first argument is
312 // a string literal. If so, we can constant fold.
314 if (!getConstantStringInfo(SrcStr, Str)) {
315 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
316 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
320 // Compute the offset, make sure to handle the case when we're searching for
321 // zero (a weird way to spell strlen).
322 size_t I = (0xFF & CharC->getSExtValue()) == 0
324 : Str.find(CharC->getSExtValue());
325 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
326 return Constant::getNullValue(CI->getType());
328 // strchr(s+n,c) -> gep(s+n+i,c)
329 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
332 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
333 Function *Callee = CI->getCalledFunction();
334 // Verify the "strrchr" function prototype.
335 FunctionType *FT = Callee->getFunctionType();
336 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
337 FT->getParamType(0) != FT->getReturnType() ||
338 !FT->getParamType(1)->isIntegerTy(32))
341 Value *SrcStr = CI->getArgOperand(0);
342 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
344 // Cannot fold anything if we're not looking for a constant.
349 if (!getConstantStringInfo(SrcStr, Str)) {
350 // strrchr(s, 0) -> strchr(s, 0)
352 return EmitStrChr(SrcStr, '\0', B, TLI);
356 // Compute the offset.
357 size_t I = (0xFF & CharC->getSExtValue()) == 0
359 : Str.rfind(CharC->getSExtValue());
360 if (I == StringRef::npos) // Didn't find the char. Return null.
361 return Constant::getNullValue(CI->getType());
363 // strrchr(s+n,c) -> gep(s+n+i,c)
364 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
367 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
368 Function *Callee = CI->getCalledFunction();
369 // Verify the "strcmp" function prototype.
370 FunctionType *FT = Callee->getFunctionType();
371 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
372 FT->getParamType(0) != FT->getParamType(1) ||
373 FT->getParamType(0) != B.getInt8PtrTy())
376 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
377 if (Str1P == Str2P) // strcmp(x,x) -> 0
378 return ConstantInt::get(CI->getType(), 0);
380 StringRef Str1, Str2;
381 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
382 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
384 // strcmp(x, y) -> cnst (if both x and y are constant strings)
385 if (HasStr1 && HasStr2)
386 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
388 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
390 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
392 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
393 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
395 // strcmp(P, "x") -> memcmp(P, "x", 2)
396 uint64_t Len1 = GetStringLength(Str1P);
397 uint64_t Len2 = GetStringLength(Str2P);
399 return EmitMemCmp(Str1P, Str2P,
400 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
401 std::min(Len1, Len2)),
408 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
409 Function *Callee = CI->getCalledFunction();
410 // Verify the "strncmp" function prototype.
411 FunctionType *FT = Callee->getFunctionType();
412 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
413 FT->getParamType(0) != FT->getParamType(1) ||
414 FT->getParamType(0) != B.getInt8PtrTy() ||
415 !FT->getParamType(2)->isIntegerTy())
418 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
419 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
420 return ConstantInt::get(CI->getType(), 0);
422 // Get the length argument if it is constant.
424 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
425 Length = LengthArg->getZExtValue();
429 if (Length == 0) // strncmp(x,y,0) -> 0
430 return ConstantInt::get(CI->getType(), 0);
432 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
433 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
435 StringRef Str1, Str2;
436 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
437 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
439 // strncmp(x, y) -> cnst (if both x and y are constant strings)
440 if (HasStr1 && HasStr2) {
441 StringRef SubStr1 = Str1.substr(0, Length);
442 StringRef SubStr2 = Str2.substr(0, Length);
443 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
446 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
448 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
450 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
451 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
456 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
457 Function *Callee = CI->getCalledFunction();
459 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
462 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
463 if (Dst == Src) // strcpy(x,x) -> x
466 // See if we can get the length of the input string.
467 uint64_t Len = GetStringLength(Src);
471 // We have enough information to now generate the memcpy call to do the
472 // copy for us. Make a memcpy to copy the nul byte with align = 1.
473 B.CreateMemCpy(Dst, Src,
474 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
478 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
479 Function *Callee = CI->getCalledFunction();
480 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
483 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
484 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
485 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
486 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
489 // See if we can get the length of the input string.
490 uint64_t Len = GetStringLength(Src);
494 Type *PT = Callee->getFunctionType()->getParamType(0);
495 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
497 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
499 // We have enough information to now generate the memcpy call to do the
500 // copy for us. Make a memcpy to copy the nul byte with align = 1.
501 B.CreateMemCpy(Dst, Src, LenV, 1);
505 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
506 Function *Callee = CI->getCalledFunction();
507 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
510 Value *Dst = CI->getArgOperand(0);
511 Value *Src = CI->getArgOperand(1);
512 Value *LenOp = CI->getArgOperand(2);
514 // See if we can get the length of the input string.
515 uint64_t SrcLen = GetStringLength(Src);
521 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
522 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
527 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
528 Len = LengthArg->getZExtValue();
533 return Dst; // strncpy(x, y, 0) -> x
535 // Let strncpy handle the zero padding
536 if (Len > SrcLen + 1)
539 Type *PT = Callee->getFunctionType()->getParamType(0);
540 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
541 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
546 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
547 Function *Callee = CI->getCalledFunction();
548 FunctionType *FT = Callee->getFunctionType();
549 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
550 !FT->getReturnType()->isIntegerTy())
553 Value *Src = CI->getArgOperand(0);
555 // Constant folding: strlen("xyz") -> 3
556 if (uint64_t Len = GetStringLength(Src))
557 return ConstantInt::get(CI->getType(), Len - 1);
559 // strlen(x?"foo":"bars") --> x ? 3 : 4
560 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
561 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
562 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
563 if (LenTrue && LenFalse) {
564 Function *Caller = CI->getParent()->getParent();
565 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
567 "folded strlen(select) to select of constants");
568 return B.CreateSelect(SI->getCondition(),
569 ConstantInt::get(CI->getType(), LenTrue - 1),
570 ConstantInt::get(CI->getType(), LenFalse - 1));
574 // strlen(x) != 0 --> *x != 0
575 // strlen(x) == 0 --> *x == 0
576 if (isOnlyUsedInZeroEqualityComparison(CI))
577 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
582 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
583 Function *Callee = CI->getCalledFunction();
584 FunctionType *FT = Callee->getFunctionType();
585 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
586 FT->getParamType(1) != FT->getParamType(0) ||
587 FT->getReturnType() != FT->getParamType(0))
591 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
592 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
594 // strpbrk(s, "") -> nullptr
595 // strpbrk("", s) -> nullptr
596 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
597 return Constant::getNullValue(CI->getType());
600 if (HasS1 && HasS2) {
601 size_t I = S1.find_first_of(S2);
602 if (I == StringRef::npos) // No match.
603 return Constant::getNullValue(CI->getType());
605 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
608 // strpbrk(s, "a") -> strchr(s, 'a')
609 if (HasS2 && S2.size() == 1)
610 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
615 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
616 Function *Callee = CI->getCalledFunction();
617 FunctionType *FT = Callee->getFunctionType();
618 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
619 !FT->getParamType(0)->isPointerTy() ||
620 !FT->getParamType(1)->isPointerTy())
623 Value *EndPtr = CI->getArgOperand(1);
624 if (isa<ConstantPointerNull>(EndPtr)) {
625 // With a null EndPtr, this function won't capture the main argument.
626 // It would be readonly too, except that it still may write to errno.
627 CI->addAttribute(1, Attribute::NoCapture);
633 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
634 Function *Callee = CI->getCalledFunction();
635 FunctionType *FT = Callee->getFunctionType();
636 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
642 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
645 // strspn(s, "") -> 0
646 // strspn("", s) -> 0
647 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
648 return Constant::getNullValue(CI->getType());
651 if (HasS1 && HasS2) {
652 size_t Pos = S1.find_first_not_of(S2);
653 if (Pos == StringRef::npos)
655 return ConstantInt::get(CI->getType(), Pos);
661 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
662 Function *Callee = CI->getCalledFunction();
663 FunctionType *FT = Callee->getFunctionType();
664 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
665 FT->getParamType(1) != FT->getParamType(0) ||
666 !FT->getReturnType()->isIntegerTy())
670 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
671 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
673 // strcspn("", s) -> 0
674 if (HasS1 && S1.empty())
675 return Constant::getNullValue(CI->getType());
678 if (HasS1 && HasS2) {
679 size_t Pos = S1.find_first_of(S2);
680 if (Pos == StringRef::npos)
682 return ConstantInt::get(CI->getType(), Pos);
685 // strcspn(s, "") -> strlen(s)
686 if (HasS2 && S2.empty())
687 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
692 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
693 Function *Callee = CI->getCalledFunction();
694 FunctionType *FT = Callee->getFunctionType();
695 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
696 !FT->getParamType(1)->isPointerTy() ||
697 !FT->getReturnType()->isPointerTy())
700 // fold strstr(x, x) -> x.
701 if (CI->getArgOperand(0) == CI->getArgOperand(1))
702 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
704 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
705 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
706 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
709 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
713 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
714 ICmpInst *Old = cast<ICmpInst>(*UI++);
716 B.CreateICmp(Old->getPredicate(), StrNCmp,
717 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
718 replaceAllUsesWith(Old, Cmp);
723 // See if either input string is a constant string.
724 StringRef SearchStr, ToFindStr;
725 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
726 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
728 // fold strstr(x, "") -> x.
729 if (HasStr2 && ToFindStr.empty())
730 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
732 // If both strings are known, constant fold it.
733 if (HasStr1 && HasStr2) {
734 size_t Offset = SearchStr.find(ToFindStr);
736 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
737 return Constant::getNullValue(CI->getType());
739 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
740 Value *Result = CastToCStr(CI->getArgOperand(0), B);
741 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
742 return B.CreateBitCast(Result, CI->getType());
745 // fold strstr(x, "y") -> strchr(x, 'y').
746 if (HasStr2 && ToFindStr.size() == 1) {
747 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
748 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
753 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
754 Function *Callee = CI->getCalledFunction();
755 FunctionType *FT = Callee->getFunctionType();
756 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
757 !FT->getParamType(1)->isIntegerTy(32) ||
758 !FT->getParamType(2)->isIntegerTy() ||
759 !FT->getReturnType()->isPointerTy())
762 Value *SrcStr = CI->getArgOperand(0);
763 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
764 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
766 // memchr(x, y, 0) -> null
767 if (LenC && LenC->isNullValue())
768 return Constant::getNullValue(CI->getType());
770 // From now on we need at least constant length and string.
772 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
775 // Truncate the string to LenC. If Str is smaller than LenC we will still only
776 // scan the string, as reading past the end of it is undefined and we can just
777 // return null if we don't find the char.
778 Str = Str.substr(0, LenC->getZExtValue());
780 // If the char is variable but the input str and length are not we can turn
781 // this memchr call into a simple bit field test. Of course this only works
782 // when the return value is only checked against null.
784 // It would be really nice to reuse switch lowering here but we can't change
785 // the CFG at this point.
787 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
788 // after bounds check.
789 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
791 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
792 reinterpret_cast<const unsigned char *>(Str.end()));
794 // Make sure the bit field we're about to create fits in a register on the
796 // FIXME: On a 64 bit architecture this prevents us from using the
797 // interesting range of alpha ascii chars. We could do better by emitting
798 // two bitfields or shifting the range by 64 if no lower chars are used.
799 if (!DL.fitsInLegalInteger(Max + 1))
802 // For the bit field use a power-of-2 type with at least 8 bits to avoid
803 // creating unnecessary illegal types.
804 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
806 // Now build the bit field.
807 APInt Bitfield(Width, 0);
809 Bitfield.setBit((unsigned char)C);
810 Value *BitfieldC = B.getInt(Bitfield);
812 // First check that the bit field access is within bounds.
813 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
814 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
817 // Create code that checks if the given bit is set in the field.
818 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
819 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
821 // Finally merge both checks and cast to pointer type. The inttoptr
822 // implicitly zexts the i1 to intptr type.
823 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
826 // Check if all arguments are constants. If so, we can constant fold.
830 // Compute the offset.
831 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
832 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
833 return Constant::getNullValue(CI->getType());
835 // memchr(s+n,c,l) -> gep(s+n+i,c)
836 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
839 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
840 Function *Callee = CI->getCalledFunction();
841 FunctionType *FT = Callee->getFunctionType();
842 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
843 !FT->getParamType(1)->isPointerTy() ||
844 !FT->getReturnType()->isIntegerTy(32))
847 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
849 if (LHS == RHS) // memcmp(s,s,x) -> 0
850 return Constant::getNullValue(CI->getType());
852 // Make sure we have a constant length.
853 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
856 uint64_t Len = LenC->getZExtValue();
858 if (Len == 0) // memcmp(s1,s2,0) -> 0
859 return Constant::getNullValue(CI->getType());
861 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
863 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
864 CI->getType(), "lhsv");
865 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
866 CI->getType(), "rhsv");
867 return B.CreateSub(LHSV, RHSV, "chardiff");
870 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
871 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
873 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
874 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
876 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
877 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
880 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
882 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
884 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
885 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
887 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
891 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
892 StringRef LHSStr, RHSStr;
893 if (getConstantStringInfo(LHS, LHSStr) &&
894 getConstantStringInfo(RHS, RHSStr)) {
895 // Make sure we're not reading out-of-bounds memory.
896 if (Len > LHSStr.size() || Len > RHSStr.size())
898 // Fold the memcmp and normalize the result. This way we get consistent
899 // results across multiple platforms.
901 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
906 return ConstantInt::get(CI->getType(), Ret);
912 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
913 Function *Callee = CI->getCalledFunction();
915 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
918 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
919 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
920 CI->getArgOperand(2), 1);
921 return CI->getArgOperand(0);
924 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
925 Function *Callee = CI->getCalledFunction();
927 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
930 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
931 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
932 CI->getArgOperand(2), 1);
933 return CI->getArgOperand(0);
936 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
937 Function *Callee = CI->getCalledFunction();
939 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
942 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
943 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
944 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
945 return CI->getArgOperand(0);
948 //===----------------------------------------------------------------------===//
949 // Math Library Optimizations
950 //===----------------------------------------------------------------------===//
952 /// Return a variant of Val with float type.
953 /// Currently this works in two cases: If Val is an FPExtension of a float
954 /// value to something bigger, simply return the operand.
955 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
956 /// loss of precision do so.
957 static Value *valueHasFloatPrecision(Value *Val) {
958 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
959 Value *Op = Cast->getOperand(0);
960 if (Op->getType()->isFloatTy())
963 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
964 APFloat F = Const->getValueAPF();
966 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
969 return ConstantFP::get(Const->getContext(), F);
974 //===----------------------------------------------------------------------===//
975 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
977 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
979 Function *Callee = CI->getCalledFunction();
980 FunctionType *FT = Callee->getFunctionType();
981 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
982 !FT->getParamType(0)->isDoubleTy())
986 // Check if all the uses for function like 'sin' are converted to float.
987 for (User *U : CI->users()) {
988 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
989 if (!Cast || !Cast->getType()->isFloatTy())
994 // If this is something like 'floor((double)floatval)', convert to floorf.
995 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
999 // floor((double)floatval) -> (double)floorf(floatval)
1000 if (Callee->isIntrinsic()) {
1001 Module *M = CI->getParent()->getParent()->getParent();
1002 Intrinsic::ID IID = Callee->getIntrinsicID();
1003 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1004 V = B.CreateCall(F, V);
1006 // The call is a library call rather than an intrinsic.
1007 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1010 return B.CreateFPExt(V, B.getDoubleTy());
1013 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1014 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1015 Function *Callee = CI->getCalledFunction();
1016 FunctionType *FT = Callee->getFunctionType();
1017 // Just make sure this has 2 arguments of the same FP type, which match the
1019 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1020 FT->getParamType(0) != FT->getParamType(1) ||
1021 !FT->getParamType(0)->isFloatingPointTy())
1024 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1025 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1026 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1029 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1033 // fmin((double)floatval1, (double)floatval2)
1034 // -> (double)fminf(floatval1, floatval2)
1035 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1036 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1037 Callee->getAttributes());
1038 return B.CreateFPExt(V, B.getDoubleTy());
1041 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1042 Function *Callee = CI->getCalledFunction();
1043 Value *Ret = nullptr;
1044 StringRef Name = Callee->getName();
1045 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1046 Ret = optimizeUnaryDoubleFP(CI, B, true);
1048 FunctionType *FT = Callee->getFunctionType();
1049 // Just make sure this has 1 argument of FP type, which matches the
1051 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1052 !FT->getParamType(0)->isFloatingPointTy())
1055 // cos(-x) -> cos(x)
1056 Value *Op1 = CI->getArgOperand(0);
1057 if (BinaryOperator::isFNeg(Op1)) {
1058 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1059 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1064 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1065 Function *Callee = CI->getCalledFunction();
1066 Value *Ret = nullptr;
1067 StringRef Name = Callee->getName();
1068 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1069 Ret = optimizeUnaryDoubleFP(CI, B, true);
1071 FunctionType *FT = Callee->getFunctionType();
1072 // Just make sure this has 2 arguments of the same FP type, which match the
1074 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1075 FT->getParamType(0) != FT->getParamType(1) ||
1076 !FT->getParamType(0)->isFloatingPointTy())
1079 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1080 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1081 // pow(1.0, x) -> 1.0
1082 if (Op1C->isExactlyValue(1.0))
1084 // pow(2.0, x) -> exp2(x)
1085 if (Op1C->isExactlyValue(2.0) &&
1086 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1088 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1089 Callee->getAttributes());
1090 // pow(10.0, x) -> exp10(x)
1091 if (Op1C->isExactlyValue(10.0) &&
1092 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1094 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1095 Callee->getAttributes());
1098 bool unsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1100 // pow(exp(x), y) -> exp(x*y)
1101 // pow(exp2(x), y) -> exp2(x * y)
1102 // We enable these only under fast-math. Besides rounding
1103 // differences the transformation changes overflow and
1104 // underflow behavior quite dramatically.
1105 // Example: x = 1000, y = 0.001.
1106 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1108 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1109 IRBuilder<>::FastMathFlagGuard Guard(B);
1111 FMF.setUnsafeAlgebra();
1112 B.SetFastMathFlags(FMF);
1115 Function *OpCCallee = OpC->getCalledFunction();
1116 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1117 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2))
1118 return EmitUnaryFloatFnCall(
1119 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"),
1120 OpCCallee->getName(), B, OpCCallee->getAttributes());
1124 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1128 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1129 return ConstantFP::get(CI->getType(), 1.0);
1131 if (Op2C->isExactlyValue(0.5) &&
1132 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1134 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1137 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1139 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1140 Callee->getAttributes());
1142 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1143 // This is faster than calling pow, and still handles negative zero
1144 // and negative infinity correctly.
1145 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1146 Value *Inf = ConstantFP::getInfinity(CI->getType());
1147 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1148 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1150 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1151 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1152 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1156 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1158 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1159 return B.CreateFMul(Op1, Op1, "pow2");
1160 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1161 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1165 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1166 Function *Callee = CI->getCalledFunction();
1167 Function *Caller = CI->getParent()->getParent();
1168 Value *Ret = nullptr;
1169 StringRef Name = Callee->getName();
1170 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1171 Ret = optimizeUnaryDoubleFP(CI, B, true);
1173 FunctionType *FT = Callee->getFunctionType();
1174 // Just make sure this has 1 argument of FP type, which matches the
1176 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1177 !FT->getParamType(0)->isFloatingPointTy())
1180 Value *Op = CI->getArgOperand(0);
1181 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1182 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1183 LibFunc::Func LdExp = LibFunc::ldexpl;
1184 if (Op->getType()->isFloatTy())
1185 LdExp = LibFunc::ldexpf;
1186 else if (Op->getType()->isDoubleTy())
1187 LdExp = LibFunc::ldexp;
1189 if (TLI->has(LdExp)) {
1190 Value *LdExpArg = nullptr;
1191 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1192 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1193 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1194 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1195 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1196 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1200 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1201 if (!Op->getType()->isFloatTy())
1202 One = ConstantExpr::getFPExtend(One, Op->getType());
1204 Module *M = Caller->getParent();
1206 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1207 Op->getType(), B.getInt32Ty(), nullptr);
1208 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1209 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1210 CI->setCallingConv(F->getCallingConv());
1218 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1219 Function *Callee = CI->getCalledFunction();
1220 Value *Ret = nullptr;
1221 StringRef Name = Callee->getName();
1222 if (Name == "fabs" && hasFloatVersion(Name))
1223 Ret = optimizeUnaryDoubleFP(CI, B, false);
1225 FunctionType *FT = Callee->getFunctionType();
1226 // Make sure this has 1 argument of FP type which matches the result type.
1227 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1228 !FT->getParamType(0)->isFloatingPointTy())
1231 Value *Op = CI->getArgOperand(0);
1232 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1233 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1234 if (I->getOpcode() == Instruction::FMul)
1235 if (I->getOperand(0) == I->getOperand(1))
1241 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1242 // If we can shrink the call to a float function rather than a double
1243 // function, do that first.
1244 Function *Callee = CI->getCalledFunction();
1245 StringRef Name = Callee->getName();
1246 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1247 (Name == "fmax" && hasFloatVersion(Name))) {
1248 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1253 // Make sure this has 2 arguments of FP type which match the result type.
1254 FunctionType *FT = Callee->getFunctionType();
1255 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1256 FT->getParamType(0) != FT->getParamType(1) ||
1257 !FT->getParamType(0)->isFloatingPointTy())
1260 IRBuilder<>::FastMathFlagGuard Guard(B);
1262 Function *F = CI->getParent()->getParent();
1263 if (canUseUnsafeFPMath(F)) {
1264 // Unsafe algebra sets all fast-math-flags to true.
1265 FMF.setUnsafeAlgebra();
1267 // At a minimum, no-nans-fp-math must be true.
1268 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
1269 if (Attr.getValueAsString() != "true")
1271 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1272 // "Ideally, fmax would be sensitive to the sign of zero, for example
1273 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1274 // might be impractical."
1275 FMF.setNoSignedZeros();
1278 B.SetFastMathFlags(FMF);
1280 // We have a relaxed floating-point environment. We can ignore NaN-handling
1281 // and transform to a compare and select. We do not have to consider errno or
1282 // exceptions, because fmin/fmax do not have those.
1283 Value *Op0 = CI->getArgOperand(0);
1284 Value *Op1 = CI->getArgOperand(1);
1285 Value *Cmp = Callee->getName().startswith("fmin") ?
1286 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1287 return B.CreateSelect(Cmp, Op0, Op1);
1290 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1291 Function *Callee = CI->getCalledFunction();
1293 Value *Ret = nullptr;
1294 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1295 Callee->getIntrinsicID() == Intrinsic::sqrt))
1296 Ret = optimizeUnaryDoubleFP(CI, B, true);
1297 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1300 Value *Op = CI->getArgOperand(0);
1301 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1302 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1303 // We're looking for a repeated factor in a multiplication tree,
1304 // so we can do this fold: sqrt(x * x) -> fabs(x);
1305 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1306 Value *Op0 = I->getOperand(0);
1307 Value *Op1 = I->getOperand(1);
1308 Value *RepeatOp = nullptr;
1309 Value *OtherOp = nullptr;
1311 // Simple match: the operands of the multiply are identical.
1314 // Look for a more complicated pattern: one of the operands is itself
1315 // a multiply, so search for a common factor in that multiply.
1316 // Note: We don't bother looking any deeper than this first level or for
1317 // variations of this pattern because instcombine's visitFMUL and/or the
1318 // reassociation pass should give us this form.
1319 Value *OtherMul0, *OtherMul1;
1320 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1321 // Pattern: sqrt((x * y) * z)
1322 if (OtherMul0 == OtherMul1) {
1323 // Matched: sqrt((x * x) * z)
1324 RepeatOp = OtherMul0;
1330 // Fast math flags for any created instructions should match the sqrt
1332 // FIXME: We're not checking the sqrt because it doesn't have
1333 // fast-math-flags (see earlier comment).
1334 IRBuilder<>::FastMathFlagGuard Guard(B);
1335 B.SetFastMathFlags(I->getFastMathFlags());
1336 // If we found a repeated factor, hoist it out of the square root and
1337 // replace it with the fabs of that factor.
1338 Module *M = Callee->getParent();
1339 Type *ArgType = Op->getType();
1340 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1341 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1343 // If we found a non-repeated factor, we still need to get its square
1344 // root. We then multiply that by the value that was simplified out
1345 // of the square root calculation.
1346 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1347 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1348 return B.CreateFMul(FabsCall, SqrtCall);
1357 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1358 Function *Callee = CI->getCalledFunction();
1359 Value *Ret = nullptr;
1360 StringRef Name = Callee->getName();
1361 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1362 Ret = optimizeUnaryDoubleFP(CI, B, true);
1363 FunctionType *FT = Callee->getFunctionType();
1365 // Just make sure this has 1 argument of FP type, which matches the
1367 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1368 !FT->getParamType(0)->isFloatingPointTy())
1371 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1373 Value *Op1 = CI->getArgOperand(0);
1374 auto *OpC = dyn_cast<CallInst>(Op1);
1378 // tan(atan(x)) -> x
1379 // tanf(atanf(x)) -> x
1380 // tanl(atanl(x)) -> x
1382 Function *F = OpC->getCalledFunction();
1383 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1384 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1385 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1386 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1387 Ret = OpC->getArgOperand(0);
1391 static bool isTrigLibCall(CallInst *CI);
1392 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1393 bool UseFloat, Value *&Sin, Value *&Cos,
1396 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1398 // Make sure the prototype is as expected, otherwise the rest of the
1399 // function is probably invalid and likely to abort.
1400 if (!isTrigLibCall(CI))
1403 Value *Arg = CI->getArgOperand(0);
1404 SmallVector<CallInst *, 1> SinCalls;
1405 SmallVector<CallInst *, 1> CosCalls;
1406 SmallVector<CallInst *, 1> SinCosCalls;
1408 bool IsFloat = Arg->getType()->isFloatTy();
1410 // Look for all compatible sinpi, cospi and sincospi calls with the same
1411 // argument. If there are enough (in some sense) we can make the
1413 for (User *U : Arg->users())
1414 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1417 // It's only worthwhile if both sinpi and cospi are actually used.
1418 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1421 Value *Sin, *Cos, *SinCos;
1422 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1424 replaceTrigInsts(SinCalls, Sin);
1425 replaceTrigInsts(CosCalls, Cos);
1426 replaceTrigInsts(SinCosCalls, SinCos);
1431 static bool isTrigLibCall(CallInst *CI) {
1432 Function *Callee = CI->getCalledFunction();
1433 FunctionType *FT = Callee->getFunctionType();
1435 // We can only hope to do anything useful if we can ignore things like errno
1436 // and floating-point exceptions.
1437 bool AttributesSafe =
1438 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1440 // Other than that we need float(float) or double(double)
1441 return AttributesSafe && FT->getNumParams() == 1 &&
1442 FT->getReturnType() == FT->getParamType(0) &&
1443 (FT->getParamType(0)->isFloatTy() ||
1444 FT->getParamType(0)->isDoubleTy());
1448 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1449 SmallVectorImpl<CallInst *> &SinCalls,
1450 SmallVectorImpl<CallInst *> &CosCalls,
1451 SmallVectorImpl<CallInst *> &SinCosCalls) {
1452 CallInst *CI = dyn_cast<CallInst>(Val);
1457 Function *Callee = CI->getCalledFunction();
1459 if (Callee && (!TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1460 !isTrigLibCall(CI)))
1464 if (Func == LibFunc::sinpif)
1465 SinCalls.push_back(CI);
1466 else if (Func == LibFunc::cospif)
1467 CosCalls.push_back(CI);
1468 else if (Func == LibFunc::sincospif_stret)
1469 SinCosCalls.push_back(CI);
1471 if (Func == LibFunc::sinpi)
1472 SinCalls.push_back(CI);
1473 else if (Func == LibFunc::cospi)
1474 CosCalls.push_back(CI);
1475 else if (Func == LibFunc::sincospi_stret)
1476 SinCosCalls.push_back(CI);
1480 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1482 for (CallInst *C : Calls)
1483 replaceAllUsesWith(C, Res);
1486 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1487 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1488 Type *ArgTy = Arg->getType();
1492 Triple T(OrigCallee->getParent()->getTargetTriple());
1494 Name = "__sincospif_stret";
1496 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1497 // x86_64 can't use {float, float} since that would be returned in both
1498 // xmm0 and xmm1, which isn't what a real struct would do.
1499 ResTy = T.getArch() == Triple::x86_64
1500 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1501 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1503 Name = "__sincospi_stret";
1504 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1507 Module *M = OrigCallee->getParent();
1508 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1509 ResTy, ArgTy, nullptr);
1511 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1512 // If the argument is an instruction, it must dominate all uses so put our
1513 // sincos call there.
1514 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1516 // Otherwise (e.g. for a constant) the beginning of the function is as
1517 // good a place as any.
1518 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1519 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1522 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1524 if (SinCos->getType()->isStructTy()) {
1525 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1526 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1528 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1530 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1535 //===----------------------------------------------------------------------===//
1536 // Integer Library Call Optimizations
1537 //===----------------------------------------------------------------------===//
1539 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1540 FunctionType *FT = Callee->getFunctionType();
1541 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1542 FT->getParamType(0)->isIntegerTy();
1545 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1546 Function *Callee = CI->getCalledFunction();
1547 if (!checkIntUnaryReturnAndParam(Callee))
1549 Value *Op = CI->getArgOperand(0);
1552 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1553 if (CI->isZero()) // ffs(0) -> 0.
1554 return B.getInt32(0);
1555 // ffs(c) -> cttz(c)+1
1556 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1559 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1560 Type *ArgType = Op->getType();
1562 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1563 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1564 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1565 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1567 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1568 return B.CreateSelect(Cond, V, B.getInt32(0));
1571 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1572 Function *Callee = CI->getCalledFunction();
1573 FunctionType *FT = Callee->getFunctionType();
1574 // We require integer(integer) where the types agree.
1575 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1576 FT->getParamType(0) != FT->getReturnType())
1579 // abs(x) -> x >s -1 ? x : -x
1580 Value *Op = CI->getArgOperand(0);
1582 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1583 Value *Neg = B.CreateNeg(Op, "neg");
1584 return B.CreateSelect(Pos, Op, Neg);
1587 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1588 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1591 // isdigit(c) -> (c-'0') <u 10
1592 Value *Op = CI->getArgOperand(0);
1593 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1594 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1595 return B.CreateZExt(Op, CI->getType());
1598 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1599 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1602 // isascii(c) -> c <u 128
1603 Value *Op = CI->getArgOperand(0);
1604 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1605 return B.CreateZExt(Op, CI->getType());
1608 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1609 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1612 // toascii(c) -> c & 0x7f
1613 return B.CreateAnd(CI->getArgOperand(0),
1614 ConstantInt::get(CI->getType(), 0x7F));
1617 //===----------------------------------------------------------------------===//
1618 // Formatting and IO Library Call Optimizations
1619 //===----------------------------------------------------------------------===//
1621 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1623 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1625 // Error reporting calls should be cold, mark them as such.
1626 // This applies even to non-builtin calls: it is only a hint and applies to
1627 // functions that the frontend might not understand as builtins.
1629 // This heuristic was suggested in:
1630 // Improving Static Branch Prediction in a Compiler
1631 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1632 // Proceedings of PACT'98, Oct. 1998, IEEE
1633 Function *Callee = CI->getCalledFunction();
1635 if (!CI->hasFnAttr(Attribute::Cold) &&
1636 isReportingError(Callee, CI, StreamArg)) {
1637 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1643 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1644 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1650 // These functions might be considered cold, but only if their stream
1651 // argument is stderr.
1653 if (StreamArg >= (int)CI->getNumArgOperands())
1655 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1658 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1659 if (!GV || !GV->isDeclaration())
1661 return GV->getName() == "stderr";
1664 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1665 // Check for a fixed format string.
1666 StringRef FormatStr;
1667 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1670 // Empty format string -> noop.
1671 if (FormatStr.empty()) // Tolerate printf's declared void.
1672 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1674 // Do not do any of the following transformations if the printf return value
1675 // is used, in general the printf return value is not compatible with either
1676 // putchar() or puts().
1677 if (!CI->use_empty())
1680 // printf("x") -> putchar('x'), even for '%'.
1681 if (FormatStr.size() == 1) {
1682 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1683 if (CI->use_empty() || !Res)
1685 return B.CreateIntCast(Res, CI->getType(), true);
1688 // printf("foo\n") --> puts("foo")
1689 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1690 FormatStr.find('%') == StringRef::npos) { // No format characters.
1691 // Create a string literal with no \n on it. We expect the constant merge
1692 // pass to be run after this pass, to merge duplicate strings.
1693 FormatStr = FormatStr.drop_back();
1694 Value *GV = B.CreateGlobalString(FormatStr, "str");
1695 Value *NewCI = EmitPutS(GV, B, TLI);
1696 return (CI->use_empty() || !NewCI)
1698 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1701 // Optimize specific format strings.
1702 // printf("%c", chr) --> putchar(chr)
1703 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1704 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1705 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1707 if (CI->use_empty() || !Res)
1709 return B.CreateIntCast(Res, CI->getType(), true);
1712 // printf("%s\n", str) --> puts(str)
1713 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1714 CI->getArgOperand(1)->getType()->isPointerTy()) {
1715 return EmitPutS(CI->getArgOperand(1), B, TLI);
1720 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1722 Function *Callee = CI->getCalledFunction();
1723 // Require one fixed pointer argument and an integer/void result.
1724 FunctionType *FT = Callee->getFunctionType();
1725 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1726 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1729 if (Value *V = optimizePrintFString(CI, B)) {
1733 // printf(format, ...) -> iprintf(format, ...) if no floating point
1735 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1736 Module *M = B.GetInsertBlock()->getParent()->getParent();
1737 Constant *IPrintFFn =
1738 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1739 CallInst *New = cast<CallInst>(CI->clone());
1740 New->setCalledFunction(IPrintFFn);
1747 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1748 // Check for a fixed format string.
1749 StringRef FormatStr;
1750 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1753 // If we just have a format string (nothing else crazy) transform it.
1754 if (CI->getNumArgOperands() == 2) {
1755 // Make sure there's no % in the constant array. We could try to handle
1756 // %% -> % in the future if we cared.
1757 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1758 if (FormatStr[i] == '%')
1759 return nullptr; // we found a format specifier, bail out.
1761 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1762 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1763 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1764 FormatStr.size() + 1),
1765 1); // Copy the null byte.
1766 return ConstantInt::get(CI->getType(), FormatStr.size());
1769 // The remaining optimizations require the format string to be "%s" or "%c"
1770 // and have an extra operand.
1771 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1772 CI->getNumArgOperands() < 3)
1775 // Decode the second character of the format string.
1776 if (FormatStr[1] == 'c') {
1777 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1778 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1780 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1781 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1782 B.CreateStore(V, Ptr);
1783 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1784 B.CreateStore(B.getInt8(0), Ptr);
1786 return ConstantInt::get(CI->getType(), 1);
1789 if (FormatStr[1] == 's') {
1790 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1791 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1794 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1798 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1799 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1801 // The sprintf result is the unincremented number of bytes in the string.
1802 return B.CreateIntCast(Len, CI->getType(), false);
1807 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1808 Function *Callee = CI->getCalledFunction();
1809 // Require two fixed pointer arguments and an integer result.
1810 FunctionType *FT = Callee->getFunctionType();
1811 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1812 !FT->getParamType(1)->isPointerTy() ||
1813 !FT->getReturnType()->isIntegerTy())
1816 if (Value *V = optimizeSPrintFString(CI, B)) {
1820 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1822 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1823 Module *M = B.GetInsertBlock()->getParent()->getParent();
1824 Constant *SIPrintFFn =
1825 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1826 CallInst *New = cast<CallInst>(CI->clone());
1827 New->setCalledFunction(SIPrintFFn);
1834 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1835 optimizeErrorReporting(CI, B, 0);
1837 // All the optimizations depend on the format string.
1838 StringRef FormatStr;
1839 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1842 // Do not do any of the following transformations if the fprintf return
1843 // value is used, in general the fprintf return value is not compatible
1844 // with fwrite(), fputc() or fputs().
1845 if (!CI->use_empty())
1848 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1849 if (CI->getNumArgOperands() == 2) {
1850 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1851 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1852 return nullptr; // We found a format specifier.
1855 CI->getArgOperand(1),
1856 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1857 CI->getArgOperand(0), B, DL, TLI);
1860 // The remaining optimizations require the format string to be "%s" or "%c"
1861 // and have an extra operand.
1862 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1863 CI->getNumArgOperands() < 3)
1866 // Decode the second character of the format string.
1867 if (FormatStr[1] == 'c') {
1868 // fprintf(F, "%c", chr) --> fputc(chr, F)
1869 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1871 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1874 if (FormatStr[1] == 's') {
1875 // fprintf(F, "%s", str) --> fputs(str, F)
1876 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1878 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1883 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1884 Function *Callee = CI->getCalledFunction();
1885 // Require two fixed paramters as pointers and integer result.
1886 FunctionType *FT = Callee->getFunctionType();
1887 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1888 !FT->getParamType(1)->isPointerTy() ||
1889 !FT->getReturnType()->isIntegerTy())
1892 if (Value *V = optimizeFPrintFString(CI, B)) {
1896 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1897 // floating point arguments.
1898 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1899 Module *M = B.GetInsertBlock()->getParent()->getParent();
1900 Constant *FIPrintFFn =
1901 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1902 CallInst *New = cast<CallInst>(CI->clone());
1903 New->setCalledFunction(FIPrintFFn);
1910 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1911 optimizeErrorReporting(CI, B, 3);
1913 Function *Callee = CI->getCalledFunction();
1914 // Require a pointer, an integer, an integer, a pointer, returning integer.
1915 FunctionType *FT = Callee->getFunctionType();
1916 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1917 !FT->getParamType(1)->isIntegerTy() ||
1918 !FT->getParamType(2)->isIntegerTy() ||
1919 !FT->getParamType(3)->isPointerTy() ||
1920 !FT->getReturnType()->isIntegerTy())
1923 // Get the element size and count.
1924 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1925 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1926 if (!SizeC || !CountC)
1928 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1930 // If this is writing zero records, remove the call (it's a noop).
1932 return ConstantInt::get(CI->getType(), 0);
1934 // If this is writing one byte, turn it into fputc.
1935 // This optimisation is only valid, if the return value is unused.
1936 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1937 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1938 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1939 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1945 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1946 optimizeErrorReporting(CI, B, 1);
1948 Function *Callee = CI->getCalledFunction();
1950 // Require two pointers. Also, we can't optimize if return value is used.
1951 FunctionType *FT = Callee->getFunctionType();
1952 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1953 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1956 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1957 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1961 // Known to have no uses (see above).
1963 CI->getArgOperand(0),
1964 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1965 CI->getArgOperand(1), B, DL, TLI);
1968 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1969 Function *Callee = CI->getCalledFunction();
1970 // Require one fixed pointer argument and an integer/void result.
1971 FunctionType *FT = Callee->getFunctionType();
1972 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1973 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1976 // Check for a constant string.
1978 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1981 if (Str.empty() && CI->use_empty()) {
1982 // puts("") -> putchar('\n')
1983 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1984 if (CI->use_empty() || !Res)
1986 return B.CreateIntCast(Res, CI->getType(), true);
1992 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1994 SmallString<20> FloatFuncName = FuncName;
1995 FloatFuncName += 'f';
1996 if (TLI->getLibFunc(FloatFuncName, Func))
1997 return TLI->has(Func);
2001 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2002 IRBuilder<> &Builder) {
2004 Function *Callee = CI->getCalledFunction();
2005 StringRef FuncName = Callee->getName();
2007 // Check for string/memory library functions.
2008 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2009 // Make sure we never change the calling convention.
2010 assert((ignoreCallingConv(Func) ||
2011 CI->getCallingConv() == llvm::CallingConv::C) &&
2012 "Optimizing string/memory libcall would change the calling convention");
2014 case LibFunc::strcat:
2015 return optimizeStrCat(CI, Builder);
2016 case LibFunc::strncat:
2017 return optimizeStrNCat(CI, Builder);
2018 case LibFunc::strchr:
2019 return optimizeStrChr(CI, Builder);
2020 case LibFunc::strrchr:
2021 return optimizeStrRChr(CI, Builder);
2022 case LibFunc::strcmp:
2023 return optimizeStrCmp(CI, Builder);
2024 case LibFunc::strncmp:
2025 return optimizeStrNCmp(CI, Builder);
2026 case LibFunc::strcpy:
2027 return optimizeStrCpy(CI, Builder);
2028 case LibFunc::stpcpy:
2029 return optimizeStpCpy(CI, Builder);
2030 case LibFunc::strncpy:
2031 return optimizeStrNCpy(CI, Builder);
2032 case LibFunc::strlen:
2033 return optimizeStrLen(CI, Builder);
2034 case LibFunc::strpbrk:
2035 return optimizeStrPBrk(CI, Builder);
2036 case LibFunc::strtol:
2037 case LibFunc::strtod:
2038 case LibFunc::strtof:
2039 case LibFunc::strtoul:
2040 case LibFunc::strtoll:
2041 case LibFunc::strtold:
2042 case LibFunc::strtoull:
2043 return optimizeStrTo(CI, Builder);
2044 case LibFunc::strspn:
2045 return optimizeStrSpn(CI, Builder);
2046 case LibFunc::strcspn:
2047 return optimizeStrCSpn(CI, Builder);
2048 case LibFunc::strstr:
2049 return optimizeStrStr(CI, Builder);
2050 case LibFunc::memchr:
2051 return optimizeMemChr(CI, Builder);
2052 case LibFunc::memcmp:
2053 return optimizeMemCmp(CI, Builder);
2054 case LibFunc::memcpy:
2055 return optimizeMemCpy(CI, Builder);
2056 case LibFunc::memmove:
2057 return optimizeMemMove(CI, Builder);
2058 case LibFunc::memset:
2059 return optimizeMemSet(CI, Builder);
2067 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2068 if (CI->isNoBuiltin())
2072 Function *Callee = CI->getCalledFunction();
2073 StringRef FuncName = Callee->getName();
2074 IRBuilder<> Builder(CI);
2075 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2077 // Command-line parameter overrides function attribute.
2078 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2079 UnsafeFPShrink = EnableUnsafeFPShrink;
2080 else if (canUseUnsafeFPMath(Callee))
2081 UnsafeFPShrink = true;
2083 // First, check for intrinsics.
2084 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2085 if (!isCallingConvC)
2087 switch (II->getIntrinsicID()) {
2088 case Intrinsic::pow:
2089 return optimizePow(CI, Builder);
2090 case Intrinsic::exp2:
2091 return optimizeExp2(CI, Builder);
2092 case Intrinsic::fabs:
2093 return optimizeFabs(CI, Builder);
2094 case Intrinsic::sqrt:
2095 return optimizeSqrt(CI, Builder);
2101 // Also try to simplify calls to fortified library functions.
2102 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2103 // Try to further simplify the result.
2104 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2105 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2106 // Use an IR Builder from SimplifiedCI if available instead of CI
2107 // to guarantee we reach all uses we might replace later on.
2108 IRBuilder<> TmpBuilder(SimplifiedCI);
2109 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2110 // If we were able to further simplify, remove the now redundant call.
2111 SimplifiedCI->replaceAllUsesWith(V);
2112 SimplifiedCI->eraseFromParent();
2116 return SimplifiedFortifiedCI;
2119 // Then check for known library functions.
2120 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2121 // We never change the calling convention.
2122 if (!ignoreCallingConv(Func) && !isCallingConvC)
2124 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2130 return optimizeCos(CI, Builder);
2131 case LibFunc::sinpif:
2132 case LibFunc::sinpi:
2133 case LibFunc::cospif:
2134 case LibFunc::cospi:
2135 return optimizeSinCosPi(CI, Builder);
2139 return optimizePow(CI, Builder);
2140 case LibFunc::exp2l:
2142 case LibFunc::exp2f:
2143 return optimizeExp2(CI, Builder);
2144 case LibFunc::fabsf:
2146 case LibFunc::fabsl:
2147 return optimizeFabs(CI, Builder);
2148 case LibFunc::sqrtf:
2150 case LibFunc::sqrtl:
2151 return optimizeSqrt(CI, Builder);
2154 case LibFunc::ffsll:
2155 return optimizeFFS(CI, Builder);
2158 case LibFunc::llabs:
2159 return optimizeAbs(CI, Builder);
2160 case LibFunc::isdigit:
2161 return optimizeIsDigit(CI, Builder);
2162 case LibFunc::isascii:
2163 return optimizeIsAscii(CI, Builder);
2164 case LibFunc::toascii:
2165 return optimizeToAscii(CI, Builder);
2166 case LibFunc::printf:
2167 return optimizePrintF(CI, Builder);
2168 case LibFunc::sprintf:
2169 return optimizeSPrintF(CI, Builder);
2170 case LibFunc::fprintf:
2171 return optimizeFPrintF(CI, Builder);
2172 case LibFunc::fwrite:
2173 return optimizeFWrite(CI, Builder);
2174 case LibFunc::fputs:
2175 return optimizeFPuts(CI, Builder);
2177 return optimizePuts(CI, Builder);
2181 return optimizeTan(CI, Builder);
2182 case LibFunc::perror:
2183 return optimizeErrorReporting(CI, Builder);
2184 case LibFunc::vfprintf:
2185 case LibFunc::fiprintf:
2186 return optimizeErrorReporting(CI, Builder, 0);
2187 case LibFunc::fputc:
2188 return optimizeErrorReporting(CI, Builder, 1);
2190 case LibFunc::floor:
2192 case LibFunc::round:
2193 case LibFunc::nearbyint:
2194 case LibFunc::trunc:
2195 if (hasFloatVersion(FuncName))
2196 return optimizeUnaryDoubleFP(CI, Builder, false);
2199 case LibFunc::acosh:
2201 case LibFunc::asinh:
2203 case LibFunc::atanh:
2207 case LibFunc::exp10:
2208 case LibFunc::expm1:
2210 case LibFunc::log10:
2211 case LibFunc::log1p:
2217 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2218 return optimizeUnaryDoubleFP(CI, Builder, true);
2220 case LibFunc::copysign:
2221 if (hasFloatVersion(FuncName))
2222 return optimizeBinaryDoubleFP(CI, Builder);
2224 case LibFunc::fminf:
2226 case LibFunc::fminl:
2227 case LibFunc::fmaxf:
2229 case LibFunc::fmaxl:
2230 return optimizeFMinFMax(CI, Builder);
2238 LibCallSimplifier::LibCallSimplifier(
2239 const DataLayout &DL, const TargetLibraryInfo *TLI,
2240 function_ref<void(Instruction *, Value *)> Replacer)
2241 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2242 Replacer(Replacer) {}
2244 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2245 // Indirect through the replacer used in this instance.
2250 // Additional cases that we need to add to this file:
2253 // * cbrt(expN(X)) -> expN(x/3)
2254 // * cbrt(sqrt(x)) -> pow(x,1/6)
2255 // * cbrt(cbrt(x)) -> pow(x,1/9)
2258 // * exp(log(x)) -> x
2261 // * log(exp(x)) -> x
2262 // * log(x**y) -> y*log(x)
2263 // * log(exp(y)) -> y*log(e)
2264 // * log(exp2(y)) -> y*log(2)
2265 // * log(exp10(y)) -> y*log(10)
2266 // * log(sqrt(x)) -> 0.5*log(x)
2267 // * log(pow(x,y)) -> y*log(x)
2269 // lround, lroundf, lroundl:
2270 // * lround(cnst) -> cnst'
2273 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2274 // * pow(pow(x,y),z)-> pow(x,y*z)
2276 // round, roundf, roundl:
2277 // * round(cnst) -> cnst'
2280 // * signbit(cnst) -> cnst'
2281 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2283 // sqrt, sqrtf, sqrtl:
2284 // * sqrt(expN(x)) -> expN(x*0.5)
2285 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2286 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2288 // trunc, truncf, truncl:
2289 // * trunc(cnst) -> cnst'
2293 //===----------------------------------------------------------------------===//
2294 // Fortified Library Call Optimizations
2295 //===----------------------------------------------------------------------===//
2297 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2301 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2303 if (ConstantInt *ObjSizeCI =
2304 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2305 if (ObjSizeCI->isAllOnesValue())
2307 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2308 if (OnlyLowerUnknownSize)
2311 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2312 // If the length is 0 we don't know how long it is and so we can't
2313 // remove the check.
2316 return ObjSizeCI->getZExtValue() >= Len;
2318 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2319 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2324 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2325 Function *Callee = CI->getCalledFunction();
2327 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2330 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2331 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2332 CI->getArgOperand(2), 1);
2333 return CI->getArgOperand(0);
2338 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2339 Function *Callee = CI->getCalledFunction();
2341 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2344 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2345 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2346 CI->getArgOperand(2), 1);
2347 return CI->getArgOperand(0);
2352 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2353 Function *Callee = CI->getCalledFunction();
2355 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2358 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2359 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2360 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2361 return CI->getArgOperand(0);
2366 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2368 LibFunc::Func Func) {
2369 Function *Callee = CI->getCalledFunction();
2370 StringRef Name = Callee->getName();
2371 const DataLayout &DL = CI->getModule()->getDataLayout();
2373 if (!checkStringCopyLibFuncSignature(Callee, Func))
2376 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2377 *ObjSize = CI->getArgOperand(2);
2379 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2380 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2381 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2382 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2385 // If a) we don't have any length information, or b) we know this will
2386 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2387 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2388 // TODO: It might be nice to get a maximum length out of the possible
2389 // string lengths for varying.
2390 if (isFortifiedCallFoldable(CI, 2, 1, true))
2391 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2393 if (OnlyLowerUnknownSize)
2396 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2397 uint64_t Len = GetStringLength(Src);
2401 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2402 Value *LenV = ConstantInt::get(SizeTTy, Len);
2403 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2404 // If the function was an __stpcpy_chk, and we were able to fold it into
2405 // a __memcpy_chk, we still need to return the correct end pointer.
2406 if (Ret && Func == LibFunc::stpcpy_chk)
2407 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2411 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2413 LibFunc::Func Func) {
2414 Function *Callee = CI->getCalledFunction();
2415 StringRef Name = Callee->getName();
2417 if (!checkStringCopyLibFuncSignature(Callee, Func))
2419 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2420 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2421 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2427 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2428 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2429 // Some clang users checked for _chk libcall availability using:
2430 // __has_builtin(__builtin___memcpy_chk)
2431 // When compiling with -fno-builtin, this is always true.
2432 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2433 // end up with fortified libcalls, which isn't acceptable in a freestanding
2434 // environment which only provides their non-fortified counterparts.
2436 // Until we change clang and/or teach external users to check for availability
2437 // differently, disregard the "nobuiltin" attribute and TLI::has.
2442 Function *Callee = CI->getCalledFunction();
2443 StringRef FuncName = Callee->getName();
2444 IRBuilder<> Builder(CI);
2445 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2447 // First, check that this is a known library functions.
2448 if (!TLI->getLibFunc(FuncName, Func))
2451 // We never change the calling convention.
2452 if (!ignoreCallingConv(Func) && !isCallingConvC)
2456 case LibFunc::memcpy_chk:
2457 return optimizeMemCpyChk(CI, Builder);
2458 case LibFunc::memmove_chk:
2459 return optimizeMemMoveChk(CI, Builder);
2460 case LibFunc::memset_chk:
2461 return optimizeMemSetChk(CI, Builder);
2462 case LibFunc::stpcpy_chk:
2463 case LibFunc::strcpy_chk:
2464 return optimizeStrpCpyChk(CI, Builder, Func);
2465 case LibFunc::stpncpy_chk:
2466 case LibFunc::strncpy_chk:
2467 return optimizeStrpNCpyChk(CI, Builder, Func);
2474 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2475 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2476 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}