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/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Analysis/TargetLibraryInfo.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) {
65 llvm_unreachable("All cases should be covered in the switch.");
68 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
69 /// value is equal or not-equal to zero.
70 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
71 for (User *U : V->users()) {
72 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
74 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
77 // Unknown instruction.
83 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
84 /// comparisons with With.
85 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
86 for (User *U : V->users()) {
87 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
88 if (IC->isEquality() && IC->getOperand(1) == With)
90 // Unknown instruction.
96 static bool callHasFloatingPointArgument(const CallInst *CI) {
97 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
99 if ((*it)->getType()->isFloatingPointTy())
105 /// \brief Check whether the overloaded unary floating point function
106 /// corresponding to \a Ty is available.
107 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
108 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
109 LibFunc::Func LongDoubleFn) {
110 switch (Ty->getTypeID()) {
111 case Type::FloatTyID:
112 return TLI->has(FloatFn);
113 case Type::DoubleTyID:
114 return TLI->has(DoubleFn);
116 return TLI->has(LongDoubleFn);
120 /// \brief Check whether we can use unsafe floating point math for
121 /// the function passed as input.
122 static bool canUseUnsafeFPMath(Function *F) {
124 // FIXME: For finer-grain optimization, we need intrinsics to have the same
125 // fast-math flag decorations that are applied to FP instructions. For now,
126 // we have to rely on the function-level unsafe-fp-math attribute to do this
127 // optimization because there's no other way to express that the sqrt can be
129 if (F->hasFnAttribute("unsafe-fp-math")) {
130 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
131 if (Attr.getValueAsString() == "true")
137 /// \brief Returns whether \p F matches the signature expected for the
138 /// string/memory copying library function \p Func.
139 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
140 /// Their fortified (_chk) counterparts are also accepted.
141 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
142 const DataLayout &DL = F->getParent()->getDataLayout();
143 FunctionType *FT = F->getFunctionType();
144 LLVMContext &Context = F->getContext();
145 Type *PCharTy = Type::getInt8PtrTy(Context);
146 Type *SizeTTy = DL.getIntPtrType(Context);
147 unsigned NumParams = FT->getNumParams();
149 // All string libfuncs return the same type as the first parameter.
150 if (FT->getReturnType() != FT->getParamType(0))
155 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
156 case LibFunc::stpncpy_chk:
157 case LibFunc::strncpy_chk:
158 --NumParams; // fallthrough
159 case LibFunc::stpncpy:
160 case LibFunc::strncpy: {
161 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
162 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
166 case LibFunc::strcpy_chk:
167 case LibFunc::stpcpy_chk:
168 --NumParams; // fallthrough
169 case LibFunc::stpcpy:
170 case LibFunc::strcpy: {
171 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
172 FT->getParamType(0) != PCharTy)
176 case LibFunc::memmove_chk:
177 case LibFunc::memcpy_chk:
178 --NumParams; // fallthrough
179 case LibFunc::memmove:
180 case LibFunc::memcpy: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
186 case LibFunc::memset_chk:
187 --NumParams; // fallthrough
188 case LibFunc::memset: {
189 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
190 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
195 // If this is a fortified libcall, the last parameter is a size_t.
196 if (NumParams == FT->getNumParams() - 1)
197 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
201 //===----------------------------------------------------------------------===//
202 // String and Memory Library Call Optimizations
203 //===----------------------------------------------------------------------===//
205 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
206 Function *Callee = CI->getCalledFunction();
207 // Verify the "strcat" function prototype.
208 FunctionType *FT = Callee->getFunctionType();
209 if (FT->getNumParams() != 2||
210 FT->getReturnType() != B.getInt8PtrTy() ||
211 FT->getParamType(0) != FT->getReturnType() ||
212 FT->getParamType(1) != FT->getReturnType())
215 // Extract some information from the instruction
216 Value *Dst = CI->getArgOperand(0);
217 Value *Src = CI->getArgOperand(1);
219 // See if we can get the length of the input string.
220 uint64_t Len = GetStringLength(Src);
223 --Len; // Unbias length.
225 // Handle the simple, do-nothing case: strcat(x, "") -> x
229 return emitStrLenMemCpy(Src, Dst, Len, B);
232 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
234 // We need to find the end of the destination string. That's where the
235 // memory is to be moved to. We just generate a call to strlen.
236 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
240 // Now that we have the destination's length, we must index into the
241 // destination's pointer to get the actual memcpy destination (end of
242 // the string .. we're concatenating).
243 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
245 // We have enough information to now generate the memcpy call to do the
246 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
247 B.CreateMemCpy(CpyDst, Src,
248 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
253 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
254 Function *Callee = CI->getCalledFunction();
255 // Verify the "strncat" function prototype.
256 FunctionType *FT = Callee->getFunctionType();
257 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
258 FT->getParamType(0) != FT->getReturnType() ||
259 FT->getParamType(1) != FT->getReturnType() ||
260 !FT->getParamType(2)->isIntegerTy())
263 // Extract some information from the instruction
264 Value *Dst = CI->getArgOperand(0);
265 Value *Src = CI->getArgOperand(1);
268 // We don't do anything if length is not constant
269 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
270 Len = LengthArg->getZExtValue();
274 // See if we can get the length of the input string.
275 uint64_t SrcLen = GetStringLength(Src);
278 --SrcLen; // Unbias length.
280 // Handle the simple, do-nothing cases:
281 // strncat(x, "", c) -> x
282 // strncat(x, c, 0) -> x
283 if (SrcLen == 0 || Len == 0)
286 // We don't optimize this case
290 // strncat(x, s, c) -> strcat(x, s)
291 // s is constant so the strcat can be optimized further
292 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
295 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
296 Function *Callee = CI->getCalledFunction();
297 // Verify the "strchr" function prototype.
298 FunctionType *FT = Callee->getFunctionType();
299 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
300 FT->getParamType(0) != FT->getReturnType() ||
301 !FT->getParamType(1)->isIntegerTy(32))
304 Value *SrcStr = CI->getArgOperand(0);
306 // If the second operand is non-constant, see if we can compute the length
307 // of the input string and turn this into memchr.
308 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
310 uint64_t Len = GetStringLength(SrcStr);
311 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
314 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
315 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
319 // Otherwise, the character is a constant, see if the first argument is
320 // a string literal. If so, we can constant fold.
322 if (!getConstantStringInfo(SrcStr, Str)) {
323 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
324 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
328 // Compute the offset, make sure to handle the case when we're searching for
329 // zero (a weird way to spell strlen).
330 size_t I = (0xFF & CharC->getSExtValue()) == 0
332 : Str.find(CharC->getSExtValue());
333 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
334 return Constant::getNullValue(CI->getType());
336 // strchr(s+n,c) -> gep(s+n+i,c)
337 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
340 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
341 Function *Callee = CI->getCalledFunction();
342 // Verify the "strrchr" function prototype.
343 FunctionType *FT = Callee->getFunctionType();
344 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
345 FT->getParamType(0) != FT->getReturnType() ||
346 !FT->getParamType(1)->isIntegerTy(32))
349 Value *SrcStr = CI->getArgOperand(0);
350 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
352 // Cannot fold anything if we're not looking for a constant.
357 if (!getConstantStringInfo(SrcStr, Str)) {
358 // strrchr(s, 0) -> strchr(s, 0)
360 return EmitStrChr(SrcStr, '\0', B, TLI);
364 // Compute the offset.
365 size_t I = (0xFF & CharC->getSExtValue()) == 0
367 : Str.rfind(CharC->getSExtValue());
368 if (I == StringRef::npos) // Didn't find the char. Return null.
369 return Constant::getNullValue(CI->getType());
371 // strrchr(s+n,c) -> gep(s+n+i,c)
372 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
375 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
376 Function *Callee = CI->getCalledFunction();
377 // Verify the "strcmp" function prototype.
378 FunctionType *FT = Callee->getFunctionType();
379 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
380 FT->getParamType(0) != FT->getParamType(1) ||
381 FT->getParamType(0) != B.getInt8PtrTy())
384 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
385 if (Str1P == Str2P) // strcmp(x,x) -> 0
386 return ConstantInt::get(CI->getType(), 0);
388 StringRef Str1, Str2;
389 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
390 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
392 // strcmp(x, y) -> cnst (if both x and y are constant strings)
393 if (HasStr1 && HasStr2)
394 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
396 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
398 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
400 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
401 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
403 // strcmp(P, "x") -> memcmp(P, "x", 2)
404 uint64_t Len1 = GetStringLength(Str1P);
405 uint64_t Len2 = GetStringLength(Str2P);
407 return EmitMemCmp(Str1P, Str2P,
408 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
409 std::min(Len1, Len2)),
416 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
417 Function *Callee = CI->getCalledFunction();
418 // Verify the "strncmp" function prototype.
419 FunctionType *FT = Callee->getFunctionType();
420 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
421 FT->getParamType(0) != FT->getParamType(1) ||
422 FT->getParamType(0) != B.getInt8PtrTy() ||
423 !FT->getParamType(2)->isIntegerTy())
426 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
427 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
428 return ConstantInt::get(CI->getType(), 0);
430 // Get the length argument if it is constant.
432 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
433 Length = LengthArg->getZExtValue();
437 if (Length == 0) // strncmp(x,y,0) -> 0
438 return ConstantInt::get(CI->getType(), 0);
440 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
441 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
443 StringRef Str1, Str2;
444 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
445 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
447 // strncmp(x, y) -> cnst (if both x and y are constant strings)
448 if (HasStr1 && HasStr2) {
449 StringRef SubStr1 = Str1.substr(0, Length);
450 StringRef SubStr2 = Str2.substr(0, Length);
451 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
454 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
456 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
458 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
459 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
464 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
465 Function *Callee = CI->getCalledFunction();
467 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
470 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
471 if (Dst == Src) // strcpy(x,x) -> x
474 // See if we can get the length of the input string.
475 uint64_t Len = GetStringLength(Src);
479 // We have enough information to now generate the memcpy call to do the
480 // copy for us. Make a memcpy to copy the nul byte with align = 1.
481 B.CreateMemCpy(Dst, Src,
482 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
486 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
487 Function *Callee = CI->getCalledFunction();
488 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
491 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
492 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
493 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
494 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
497 // See if we can get the length of the input string.
498 uint64_t Len = GetStringLength(Src);
502 Type *PT = Callee->getFunctionType()->getParamType(0);
503 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
505 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
507 // We have enough information to now generate the memcpy call to do the
508 // copy for us. Make a memcpy to copy the nul byte with align = 1.
509 B.CreateMemCpy(Dst, Src, LenV, 1);
513 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
514 Function *Callee = CI->getCalledFunction();
515 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
518 Value *Dst = CI->getArgOperand(0);
519 Value *Src = CI->getArgOperand(1);
520 Value *LenOp = CI->getArgOperand(2);
522 // See if we can get the length of the input string.
523 uint64_t SrcLen = GetStringLength(Src);
529 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
530 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
535 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
536 Len = LengthArg->getZExtValue();
541 return Dst; // strncpy(x, y, 0) -> x
543 // Let strncpy handle the zero padding
544 if (Len > SrcLen + 1)
547 Type *PT = Callee->getFunctionType()->getParamType(0);
548 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
549 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
554 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
555 Function *Callee = CI->getCalledFunction();
556 FunctionType *FT = Callee->getFunctionType();
557 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
558 !FT->getReturnType()->isIntegerTy())
561 Value *Src = CI->getArgOperand(0);
563 // Constant folding: strlen("xyz") -> 3
564 if (uint64_t Len = GetStringLength(Src))
565 return ConstantInt::get(CI->getType(), Len - 1);
567 // strlen(x?"foo":"bars") --> x ? 3 : 4
568 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
569 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
570 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
571 if (LenTrue && LenFalse) {
572 Function *Caller = CI->getParent()->getParent();
573 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
575 "folded strlen(select) to select of constants");
576 return B.CreateSelect(SI->getCondition(),
577 ConstantInt::get(CI->getType(), LenTrue - 1),
578 ConstantInt::get(CI->getType(), LenFalse - 1));
582 // strlen(x) != 0 --> *x != 0
583 // strlen(x) == 0 --> *x == 0
584 if (isOnlyUsedInZeroEqualityComparison(CI))
585 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
590 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
591 Function *Callee = CI->getCalledFunction();
592 FunctionType *FT = Callee->getFunctionType();
593 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
594 FT->getParamType(1) != FT->getParamType(0) ||
595 FT->getReturnType() != FT->getParamType(0))
599 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
600 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
602 // strpbrk(s, "") -> nullptr
603 // strpbrk("", s) -> nullptr
604 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
605 return Constant::getNullValue(CI->getType());
608 if (HasS1 && HasS2) {
609 size_t I = S1.find_first_of(S2);
610 if (I == StringRef::npos) // No match.
611 return Constant::getNullValue(CI->getType());
613 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
616 // strpbrk(s, "a") -> strchr(s, 'a')
617 if (HasS2 && S2.size() == 1)
618 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
623 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
624 Function *Callee = CI->getCalledFunction();
625 FunctionType *FT = Callee->getFunctionType();
626 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
627 !FT->getParamType(0)->isPointerTy() ||
628 !FT->getParamType(1)->isPointerTy())
631 Value *EndPtr = CI->getArgOperand(1);
632 if (isa<ConstantPointerNull>(EndPtr)) {
633 // With a null EndPtr, this function won't capture the main argument.
634 // It would be readonly too, except that it still may write to errno.
635 CI->addAttribute(1, Attribute::NoCapture);
641 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
642 Function *Callee = CI->getCalledFunction();
643 FunctionType *FT = Callee->getFunctionType();
644 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
645 FT->getParamType(1) != FT->getParamType(0) ||
646 !FT->getReturnType()->isIntegerTy())
650 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
651 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
653 // strspn(s, "") -> 0
654 // strspn("", s) -> 0
655 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
656 return Constant::getNullValue(CI->getType());
659 if (HasS1 && HasS2) {
660 size_t Pos = S1.find_first_not_of(S2);
661 if (Pos == StringRef::npos)
663 return ConstantInt::get(CI->getType(), Pos);
669 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
670 Function *Callee = CI->getCalledFunction();
671 FunctionType *FT = Callee->getFunctionType();
672 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
673 FT->getParamType(1) != FT->getParamType(0) ||
674 !FT->getReturnType()->isIntegerTy())
678 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
679 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
681 // strcspn("", s) -> 0
682 if (HasS1 && S1.empty())
683 return Constant::getNullValue(CI->getType());
686 if (HasS1 && HasS2) {
687 size_t Pos = S1.find_first_of(S2);
688 if (Pos == StringRef::npos)
690 return ConstantInt::get(CI->getType(), Pos);
693 // strcspn(s, "") -> strlen(s)
694 if (HasS2 && S2.empty())
695 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
700 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
701 Function *Callee = CI->getCalledFunction();
702 FunctionType *FT = Callee->getFunctionType();
703 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
704 !FT->getParamType(1)->isPointerTy() ||
705 !FT->getReturnType()->isPointerTy())
708 // fold strstr(x, x) -> x.
709 if (CI->getArgOperand(0) == CI->getArgOperand(1))
710 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
712 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
713 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
714 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
717 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
721 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
722 ICmpInst *Old = cast<ICmpInst>(*UI++);
724 B.CreateICmp(Old->getPredicate(), StrNCmp,
725 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
726 replaceAllUsesWith(Old, Cmp);
731 // See if either input string is a constant string.
732 StringRef SearchStr, ToFindStr;
733 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
734 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
736 // fold strstr(x, "") -> x.
737 if (HasStr2 && ToFindStr.empty())
738 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
740 // If both strings are known, constant fold it.
741 if (HasStr1 && HasStr2) {
742 size_t Offset = SearchStr.find(ToFindStr);
744 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
745 return Constant::getNullValue(CI->getType());
747 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
748 Value *Result = CastToCStr(CI->getArgOperand(0), B);
749 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
750 return B.CreateBitCast(Result, CI->getType());
753 // fold strstr(x, "y") -> strchr(x, 'y').
754 if (HasStr2 && ToFindStr.size() == 1) {
755 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
756 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
761 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
762 Function *Callee = CI->getCalledFunction();
763 FunctionType *FT = Callee->getFunctionType();
764 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
765 !FT->getParamType(1)->isIntegerTy(32) ||
766 !FT->getParamType(2)->isIntegerTy() ||
767 !FT->getReturnType()->isPointerTy())
770 Value *SrcStr = CI->getArgOperand(0);
771 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
772 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
774 // memchr(x, y, 0) -> null
775 if (LenC && LenC->isNullValue())
776 return Constant::getNullValue(CI->getType());
778 // From now on we need at least constant length and string.
780 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
783 // Truncate the string to LenC. If Str is smaller than LenC we will still only
784 // scan the string, as reading past the end of it is undefined and we can just
785 // return null if we don't find the char.
786 Str = Str.substr(0, LenC->getZExtValue());
788 // If the char is variable but the input str and length are not we can turn
789 // this memchr call into a simple bit field test. Of course this only works
790 // when the return value is only checked against null.
792 // It would be really nice to reuse switch lowering here but we can't change
793 // the CFG at this point.
795 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
796 // after bounds check.
797 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
799 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
800 reinterpret_cast<const unsigned char *>(Str.end()));
802 // Make sure the bit field we're about to create fits in a register on the
804 // FIXME: On a 64 bit architecture this prevents us from using the
805 // interesting range of alpha ascii chars. We could do better by emitting
806 // two bitfields or shifting the range by 64 if no lower chars are used.
807 if (!DL.fitsInLegalInteger(Max + 1))
810 // For the bit field use a power-of-2 type with at least 8 bits to avoid
811 // creating unnecessary illegal types.
812 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
814 // Now build the bit field.
815 APInt Bitfield(Width, 0);
817 Bitfield.setBit((unsigned char)C);
818 Value *BitfieldC = B.getInt(Bitfield);
820 // First check that the bit field access is within bounds.
821 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
822 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
825 // Create code that checks if the given bit is set in the field.
826 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
827 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
829 // Finally merge both checks and cast to pointer type. The inttoptr
830 // implicitly zexts the i1 to intptr type.
831 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
834 // Check if all arguments are constants. If so, we can constant fold.
838 // Compute the offset.
839 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
840 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
841 return Constant::getNullValue(CI->getType());
843 // memchr(s+n,c,l) -> gep(s+n+i,c)
844 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
847 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
848 Function *Callee = CI->getCalledFunction();
849 FunctionType *FT = Callee->getFunctionType();
850 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
851 !FT->getParamType(1)->isPointerTy() ||
852 !FT->getReturnType()->isIntegerTy(32))
855 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
857 if (LHS == RHS) // memcmp(s,s,x) -> 0
858 return Constant::getNullValue(CI->getType());
860 // Make sure we have a constant length.
861 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
864 uint64_t Len = LenC->getZExtValue();
866 if (Len == 0) // memcmp(s1,s2,0) -> 0
867 return Constant::getNullValue(CI->getType());
869 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
871 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
872 CI->getType(), "lhsv");
873 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
874 CI->getType(), "rhsv");
875 return B.CreateSub(LHSV, RHSV, "chardiff");
878 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
879 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
881 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
882 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
884 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
885 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
888 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
890 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
892 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
893 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
895 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
899 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
900 StringRef LHSStr, RHSStr;
901 if (getConstantStringInfo(LHS, LHSStr) &&
902 getConstantStringInfo(RHS, RHSStr)) {
903 // Make sure we're not reading out-of-bounds memory.
904 if (Len > LHSStr.size() || Len > RHSStr.size())
906 // Fold the memcmp and normalize the result. This way we get consistent
907 // results across multiple platforms.
909 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
914 return ConstantInt::get(CI->getType(), Ret);
920 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
921 Function *Callee = CI->getCalledFunction();
923 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
926 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
927 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
928 CI->getArgOperand(2), 1);
929 return CI->getArgOperand(0);
932 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
933 Function *Callee = CI->getCalledFunction();
935 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
938 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
939 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
940 CI->getArgOperand(2), 1);
941 return CI->getArgOperand(0);
944 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
945 Function *Callee = CI->getCalledFunction();
947 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
950 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
951 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
952 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
953 return CI->getArgOperand(0);
956 //===----------------------------------------------------------------------===//
957 // Math Library Optimizations
958 //===----------------------------------------------------------------------===//
960 /// Return a variant of Val with float type.
961 /// Currently this works in two cases: If Val is an FPExtension of a float
962 /// value to something bigger, simply return the operand.
963 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
964 /// loss of precision do so.
965 static Value *valueHasFloatPrecision(Value *Val) {
966 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
967 Value *Op = Cast->getOperand(0);
968 if (Op->getType()->isFloatTy())
971 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
972 APFloat F = Const->getValueAPF();
974 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
977 return ConstantFP::get(Const->getContext(), F);
982 //===----------------------------------------------------------------------===//
983 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
985 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
987 Function *Callee = CI->getCalledFunction();
988 FunctionType *FT = Callee->getFunctionType();
989 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
990 !FT->getParamType(0)->isDoubleTy())
994 // Check if all the uses for function like 'sin' are converted to float.
995 for (User *U : CI->users()) {
996 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
997 if (!Cast || !Cast->getType()->isFloatTy())
1002 // If this is something like 'floor((double)floatval)', convert to floorf.
1003 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1007 // floor((double)floatval) -> (double)floorf(floatval)
1008 if (Callee->isIntrinsic()) {
1009 Module *M = CI->getParent()->getParent()->getParent();
1010 Intrinsic::ID IID = Callee->getIntrinsicID();
1011 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1012 V = B.CreateCall(F, V);
1014 // The call is a library call rather than an intrinsic.
1015 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1018 return B.CreateFPExt(V, B.getDoubleTy());
1021 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1022 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1023 Function *Callee = CI->getCalledFunction();
1024 FunctionType *FT = Callee->getFunctionType();
1025 // Just make sure this has 2 arguments of the same FP type, which match the
1027 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1028 FT->getParamType(0) != FT->getParamType(1) ||
1029 !FT->getParamType(0)->isFloatingPointTy())
1032 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1033 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1034 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1037 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1041 // fmin((double)floatval1, (double)floatval2)
1042 // -> (double)fminf(floatval1, floatval2)
1043 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1044 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1045 Callee->getAttributes());
1046 return B.CreateFPExt(V, B.getDoubleTy());
1049 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1050 Function *Callee = CI->getCalledFunction();
1051 Value *Ret = nullptr;
1052 StringRef Name = Callee->getName();
1053 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1054 Ret = optimizeUnaryDoubleFP(CI, B, true);
1056 FunctionType *FT = Callee->getFunctionType();
1057 // Just make sure this has 1 argument of FP type, which matches the
1059 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1060 !FT->getParamType(0)->isFloatingPointTy())
1063 // cos(-x) -> cos(x)
1064 Value *Op1 = CI->getArgOperand(0);
1065 if (BinaryOperator::isFNeg(Op1)) {
1066 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1067 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1072 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1073 Function *Callee = CI->getCalledFunction();
1074 Value *Ret = nullptr;
1075 StringRef Name = Callee->getName();
1076 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1077 Ret = optimizeUnaryDoubleFP(CI, B, true);
1079 FunctionType *FT = Callee->getFunctionType();
1080 // Just make sure this has 2 arguments of the same FP type, which match the
1082 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1083 FT->getParamType(0) != FT->getParamType(1) ||
1084 !FT->getParamType(0)->isFloatingPointTy())
1087 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1088 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1089 // pow(1.0, x) -> 1.0
1090 if (Op1C->isExactlyValue(1.0))
1092 // pow(2.0, x) -> exp2(x)
1093 if (Op1C->isExactlyValue(2.0) &&
1094 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1096 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1097 Callee->getAttributes());
1098 // pow(10.0, x) -> exp10(x)
1099 if (Op1C->isExactlyValue(10.0) &&
1100 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1102 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1103 Callee->getAttributes());
1106 // pow(exp(x), y) -> exp(x*y)
1107 // pow(exp2(x), y) -> exp2(x * y)
1108 // We enable these only under fast-math. Besides rounding
1109 // differences the transformation changes overflow and
1110 // underflow behavior quite dramatically.
1111 // Example: x = 1000, y = 0.001.
1112 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1113 if (canUseUnsafeFPMath(CI->getParent()->getParent())) {
1114 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1115 IRBuilder<>::FastMathFlagGuard Guard(B);
1117 FMF.setUnsafeAlgebra();
1118 B.SetFastMathFlags(FMF);
1121 Function *Callee = OpC->getCalledFunction();
1122 StringRef FuncName = Callee->getName();
1124 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1125 (Func == LibFunc::exp || Func == LibFunc::exp2))
1126 return EmitUnaryFloatFnCall(
1127 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"), FuncName, B,
1128 Callee->getAttributes());
1132 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1136 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1137 return ConstantFP::get(CI->getType(), 1.0);
1139 if (Op2C->isExactlyValue(0.5) &&
1140 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1142 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1144 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1145 // This is faster than calling pow, and still handles negative zero
1146 // and negative infinity correctly.
1147 // TODO: In fast-math mode, this could be just sqrt(x).
1148 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1149 Value *Inf = ConstantFP::getInfinity(CI->getType());
1150 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1151 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1153 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1154 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1155 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1159 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1161 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1162 return B.CreateFMul(Op1, Op1, "pow2");
1163 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1164 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1168 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1169 Function *Callee = CI->getCalledFunction();
1170 Function *Caller = CI->getParent()->getParent();
1171 Value *Ret = nullptr;
1172 StringRef Name = Callee->getName();
1173 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1174 Ret = optimizeUnaryDoubleFP(CI, B, true);
1176 FunctionType *FT = Callee->getFunctionType();
1177 // Just make sure this has 1 argument of FP type, which matches the
1179 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1180 !FT->getParamType(0)->isFloatingPointTy())
1183 Value *Op = CI->getArgOperand(0);
1184 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1185 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1186 LibFunc::Func LdExp = LibFunc::ldexpl;
1187 if (Op->getType()->isFloatTy())
1188 LdExp = LibFunc::ldexpf;
1189 else if (Op->getType()->isDoubleTy())
1190 LdExp = LibFunc::ldexp;
1192 if (TLI->has(LdExp)) {
1193 Value *LdExpArg = nullptr;
1194 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1195 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1196 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1197 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1198 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1199 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1203 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1204 if (!Op->getType()->isFloatTy())
1205 One = ConstantExpr::getFPExtend(One, Op->getType());
1207 Module *M = Caller->getParent();
1209 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1210 Op->getType(), B.getInt32Ty(), nullptr);
1211 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1212 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1213 CI->setCallingConv(F->getCallingConv());
1221 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1222 Function *Callee = CI->getCalledFunction();
1223 Value *Ret = nullptr;
1224 StringRef Name = Callee->getName();
1225 if (Name == "fabs" && hasFloatVersion(Name))
1226 Ret = optimizeUnaryDoubleFP(CI, B, false);
1228 FunctionType *FT = Callee->getFunctionType();
1229 // Make sure this has 1 argument of FP type which matches the result type.
1230 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1231 !FT->getParamType(0)->isFloatingPointTy())
1234 Value *Op = CI->getArgOperand(0);
1235 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1236 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1237 if (I->getOpcode() == Instruction::FMul)
1238 if (I->getOperand(0) == I->getOperand(1))
1244 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1245 // If we can shrink the call to a float function rather than a double
1246 // function, do that first.
1247 Function *Callee = CI->getCalledFunction();
1248 StringRef Name = Callee->getName();
1249 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1250 (Name == "fmax" && hasFloatVersion(Name))) {
1251 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1256 // Make sure this has 2 arguments of FP type which match the result type.
1257 FunctionType *FT = Callee->getFunctionType();
1258 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1259 FT->getParamType(0) != FT->getParamType(1) ||
1260 !FT->getParamType(0)->isFloatingPointTy())
1263 IRBuilder<>::FastMathFlagGuard Guard(B);
1265 Function *F = CI->getParent()->getParent();
1266 if (canUseUnsafeFPMath(F)) {
1267 // Unsafe algebra sets all fast-math-flags to true.
1268 FMF.setUnsafeAlgebra();
1270 // At a minimum, no-nans-fp-math must be true.
1271 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
1272 if (Attr.getValueAsString() != "true")
1274 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1275 // "Ideally, fmax would be sensitive to the sign of zero, for example
1276 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1277 // might be impractical."
1278 FMF.setNoSignedZeros();
1281 B.SetFastMathFlags(FMF);
1283 // We have a relaxed floating-point environment. We can ignore NaN-handling
1284 // and transform to a compare and select. We do not have to consider errno or
1285 // exceptions, because fmin/fmax do not have those.
1286 Value *Op0 = CI->getArgOperand(0);
1287 Value *Op1 = CI->getArgOperand(1);
1288 Value *Cmp = Callee->getName().startswith("fmin") ?
1289 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1290 return B.CreateSelect(Cmp, Op0, Op1);
1293 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1294 Function *Callee = CI->getCalledFunction();
1296 Value *Ret = nullptr;
1297 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1298 Callee->getIntrinsicID() == Intrinsic::sqrt))
1299 Ret = optimizeUnaryDoubleFP(CI, B, true);
1300 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1303 Value *Op = CI->getArgOperand(0);
1304 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1305 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1306 // We're looking for a repeated factor in a multiplication tree,
1307 // so we can do this fold: sqrt(x * x) -> fabs(x);
1308 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1309 Value *Op0 = I->getOperand(0);
1310 Value *Op1 = I->getOperand(1);
1311 Value *RepeatOp = nullptr;
1312 Value *OtherOp = nullptr;
1314 // Simple match: the operands of the multiply are identical.
1317 // Look for a more complicated pattern: one of the operands is itself
1318 // a multiply, so search for a common factor in that multiply.
1319 // Note: We don't bother looking any deeper than this first level or for
1320 // variations of this pattern because instcombine's visitFMUL and/or the
1321 // reassociation pass should give us this form.
1322 Value *OtherMul0, *OtherMul1;
1323 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1324 // Pattern: sqrt((x * y) * z)
1325 if (OtherMul0 == OtherMul1) {
1326 // Matched: sqrt((x * x) * z)
1327 RepeatOp = OtherMul0;
1333 // Fast math flags for any created instructions should match the sqrt
1335 // FIXME: We're not checking the sqrt because it doesn't have
1336 // fast-math-flags (see earlier comment).
1337 IRBuilder<>::FastMathFlagGuard Guard(B);
1338 B.SetFastMathFlags(I->getFastMathFlags());
1339 // If we found a repeated factor, hoist it out of the square root and
1340 // replace it with the fabs of that factor.
1341 Module *M = Callee->getParent();
1342 Type *ArgType = Op->getType();
1343 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1344 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1346 // If we found a non-repeated factor, we still need to get its square
1347 // root. We then multiply that by the value that was simplified out
1348 // of the square root calculation.
1349 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1350 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1351 return B.CreateFMul(FabsCall, SqrtCall);
1360 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1361 Function *Callee = CI->getCalledFunction();
1362 Value *Ret = nullptr;
1363 StringRef Name = Callee->getName();
1364 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1365 Ret = optimizeUnaryDoubleFP(CI, B, true);
1366 FunctionType *FT = Callee->getFunctionType();
1368 // Just make sure this has 1 argument of FP type, which matches the
1370 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1371 !FT->getParamType(0)->isFloatingPointTy())
1374 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1376 Value *Op1 = CI->getArgOperand(0);
1377 auto *OpC = dyn_cast<CallInst>(Op1);
1381 // tan(atan(x)) -> x
1382 // tanf(atanf(x)) -> x
1383 // tanl(atanl(x)) -> x
1385 Function *F = OpC->getCalledFunction();
1386 StringRef FuncName = F->getName();
1387 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1388 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1389 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1390 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1391 Ret = OpC->getArgOperand(0);
1395 static bool isTrigLibCall(CallInst *CI);
1396 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1397 bool UseFloat, Value *&Sin, Value *&Cos,
1400 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1402 // Make sure the prototype is as expected, otherwise the rest of the
1403 // function is probably invalid and likely to abort.
1404 if (!isTrigLibCall(CI))
1407 Value *Arg = CI->getArgOperand(0);
1408 SmallVector<CallInst *, 1> SinCalls;
1409 SmallVector<CallInst *, 1> CosCalls;
1410 SmallVector<CallInst *, 1> SinCosCalls;
1412 bool IsFloat = Arg->getType()->isFloatTy();
1414 // Look for all compatible sinpi, cospi and sincospi calls with the same
1415 // argument. If there are enough (in some sense) we can make the
1417 for (User *U : Arg->users())
1418 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1421 // It's only worthwhile if both sinpi and cospi are actually used.
1422 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1425 Value *Sin, *Cos, *SinCos;
1426 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1428 replaceTrigInsts(SinCalls, Sin);
1429 replaceTrigInsts(CosCalls, Cos);
1430 replaceTrigInsts(SinCosCalls, SinCos);
1435 static bool isTrigLibCall(CallInst *CI) {
1436 Function *Callee = CI->getCalledFunction();
1437 FunctionType *FT = Callee->getFunctionType();
1439 // We can only hope to do anything useful if we can ignore things like errno
1440 // and floating-point exceptions.
1441 bool AttributesSafe =
1442 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1444 // Other than that we need float(float) or double(double)
1445 return AttributesSafe && FT->getNumParams() == 1 &&
1446 FT->getReturnType() == FT->getParamType(0) &&
1447 (FT->getParamType(0)->isFloatTy() ||
1448 FT->getParamType(0)->isDoubleTy());
1452 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1453 SmallVectorImpl<CallInst *> &SinCalls,
1454 SmallVectorImpl<CallInst *> &CosCalls,
1455 SmallVectorImpl<CallInst *> &SinCosCalls) {
1456 CallInst *CI = dyn_cast<CallInst>(Val);
1461 Function *Callee = CI->getCalledFunction();
1462 StringRef FuncName = Callee->getName();
1464 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1468 if (Func == LibFunc::sinpif)
1469 SinCalls.push_back(CI);
1470 else if (Func == LibFunc::cospif)
1471 CosCalls.push_back(CI);
1472 else if (Func == LibFunc::sincospif_stret)
1473 SinCosCalls.push_back(CI);
1475 if (Func == LibFunc::sinpi)
1476 SinCalls.push_back(CI);
1477 else if (Func == LibFunc::cospi)
1478 CosCalls.push_back(CI);
1479 else if (Func == LibFunc::sincospi_stret)
1480 SinCosCalls.push_back(CI);
1484 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1486 for (CallInst *C : Calls)
1487 replaceAllUsesWith(C, Res);
1490 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1491 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1492 Type *ArgTy = Arg->getType();
1496 Triple T(OrigCallee->getParent()->getTargetTriple());
1498 Name = "__sincospif_stret";
1500 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1501 // x86_64 can't use {float, float} since that would be returned in both
1502 // xmm0 and xmm1, which isn't what a real struct would do.
1503 ResTy = T.getArch() == Triple::x86_64
1504 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1505 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1507 Name = "__sincospi_stret";
1508 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1511 Module *M = OrigCallee->getParent();
1512 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1513 ResTy, ArgTy, nullptr);
1515 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1516 // If the argument is an instruction, it must dominate all uses so put our
1517 // sincos call there.
1518 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1520 // Otherwise (e.g. for a constant) the beginning of the function is as
1521 // good a place as any.
1522 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1523 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1526 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1528 if (SinCos->getType()->isStructTy()) {
1529 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1530 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1532 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1534 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1539 //===----------------------------------------------------------------------===//
1540 // Integer Library Call Optimizations
1541 //===----------------------------------------------------------------------===//
1543 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1544 FunctionType *FT = Callee->getFunctionType();
1545 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1546 FT->getParamType(0)->isIntegerTy();
1549 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1550 Function *Callee = CI->getCalledFunction();
1551 if (!checkIntUnaryReturnAndParam(Callee))
1553 Value *Op = CI->getArgOperand(0);
1556 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1557 if (CI->isZero()) // ffs(0) -> 0.
1558 return B.getInt32(0);
1559 // ffs(c) -> cttz(c)+1
1560 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1563 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1564 Type *ArgType = Op->getType();
1566 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1567 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1568 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1569 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1571 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1572 return B.CreateSelect(Cond, V, B.getInt32(0));
1575 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1576 Function *Callee = CI->getCalledFunction();
1577 FunctionType *FT = Callee->getFunctionType();
1578 // We require integer(integer) where the types agree.
1579 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1580 FT->getParamType(0) != FT->getReturnType())
1583 // abs(x) -> x >s -1 ? x : -x
1584 Value *Op = CI->getArgOperand(0);
1586 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1587 Value *Neg = B.CreateNeg(Op, "neg");
1588 return B.CreateSelect(Pos, Op, Neg);
1591 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1592 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1595 // isdigit(c) -> (c-'0') <u 10
1596 Value *Op = CI->getArgOperand(0);
1597 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1598 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1599 return B.CreateZExt(Op, CI->getType());
1602 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1603 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1606 // isascii(c) -> c <u 128
1607 Value *Op = CI->getArgOperand(0);
1608 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1609 return B.CreateZExt(Op, CI->getType());
1612 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1613 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1616 // toascii(c) -> c & 0x7f
1617 return B.CreateAnd(CI->getArgOperand(0),
1618 ConstantInt::get(CI->getType(), 0x7F));
1621 //===----------------------------------------------------------------------===//
1622 // Formatting and IO Library Call Optimizations
1623 //===----------------------------------------------------------------------===//
1625 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1627 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1629 // Error reporting calls should be cold, mark them as such.
1630 // This applies even to non-builtin calls: it is only a hint and applies to
1631 // functions that the frontend might not understand as builtins.
1633 // This heuristic was suggested in:
1634 // Improving Static Branch Prediction in a Compiler
1635 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1636 // Proceedings of PACT'98, Oct. 1998, IEEE
1637 Function *Callee = CI->getCalledFunction();
1639 if (!CI->hasFnAttr(Attribute::Cold) &&
1640 isReportingError(Callee, CI, StreamArg)) {
1641 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1647 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1648 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1654 // These functions might be considered cold, but only if their stream
1655 // argument is stderr.
1657 if (StreamArg >= (int)CI->getNumArgOperands())
1659 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1662 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1663 if (!GV || !GV->isDeclaration())
1665 return GV->getName() == "stderr";
1668 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1669 // Check for a fixed format string.
1670 StringRef FormatStr;
1671 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1674 // Empty format string -> noop.
1675 if (FormatStr.empty()) // Tolerate printf's declared void.
1676 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1678 // Do not do any of the following transformations if the printf return value
1679 // is used, in general the printf return value is not compatible with either
1680 // putchar() or puts().
1681 if (!CI->use_empty())
1684 // printf("x") -> putchar('x'), even for '%'.
1685 if (FormatStr.size() == 1) {
1686 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1687 if (CI->use_empty() || !Res)
1689 return B.CreateIntCast(Res, CI->getType(), true);
1692 // printf("foo\n") --> puts("foo")
1693 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1694 FormatStr.find('%') == StringRef::npos) { // No format characters.
1695 // Create a string literal with no \n on it. We expect the constant merge
1696 // pass to be run after this pass, to merge duplicate strings.
1697 FormatStr = FormatStr.drop_back();
1698 Value *GV = B.CreateGlobalString(FormatStr, "str");
1699 Value *NewCI = EmitPutS(GV, B, TLI);
1700 return (CI->use_empty() || !NewCI)
1702 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1705 // Optimize specific format strings.
1706 // printf("%c", chr) --> putchar(chr)
1707 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1708 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1709 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1711 if (CI->use_empty() || !Res)
1713 return B.CreateIntCast(Res, CI->getType(), true);
1716 // printf("%s\n", str) --> puts(str)
1717 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1718 CI->getArgOperand(1)->getType()->isPointerTy()) {
1719 return EmitPutS(CI->getArgOperand(1), B, TLI);
1724 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1726 Function *Callee = CI->getCalledFunction();
1727 // Require one fixed pointer argument and an integer/void result.
1728 FunctionType *FT = Callee->getFunctionType();
1729 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1730 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1733 if (Value *V = optimizePrintFString(CI, B)) {
1737 // printf(format, ...) -> iprintf(format, ...) if no floating point
1739 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1740 Module *M = B.GetInsertBlock()->getParent()->getParent();
1741 Constant *IPrintFFn =
1742 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1743 CallInst *New = cast<CallInst>(CI->clone());
1744 New->setCalledFunction(IPrintFFn);
1751 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1752 // Check for a fixed format string.
1753 StringRef FormatStr;
1754 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1757 // If we just have a format string (nothing else crazy) transform it.
1758 if (CI->getNumArgOperands() == 2) {
1759 // Make sure there's no % in the constant array. We could try to handle
1760 // %% -> % in the future if we cared.
1761 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1762 if (FormatStr[i] == '%')
1763 return nullptr; // we found a format specifier, bail out.
1765 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1766 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1767 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1768 FormatStr.size() + 1),
1769 1); // Copy the null byte.
1770 return ConstantInt::get(CI->getType(), FormatStr.size());
1773 // The remaining optimizations require the format string to be "%s" or "%c"
1774 // and have an extra operand.
1775 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1776 CI->getNumArgOperands() < 3)
1779 // Decode the second character of the format string.
1780 if (FormatStr[1] == 'c') {
1781 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1782 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1784 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1785 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1786 B.CreateStore(V, Ptr);
1787 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1788 B.CreateStore(B.getInt8(0), Ptr);
1790 return ConstantInt::get(CI->getType(), 1);
1793 if (FormatStr[1] == 's') {
1794 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1795 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1798 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1802 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1803 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1805 // The sprintf result is the unincremented number of bytes in the string.
1806 return B.CreateIntCast(Len, CI->getType(), false);
1811 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1812 Function *Callee = CI->getCalledFunction();
1813 // Require two fixed pointer arguments and an integer result.
1814 FunctionType *FT = Callee->getFunctionType();
1815 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1816 !FT->getParamType(1)->isPointerTy() ||
1817 !FT->getReturnType()->isIntegerTy())
1820 if (Value *V = optimizeSPrintFString(CI, B)) {
1824 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1826 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1827 Module *M = B.GetInsertBlock()->getParent()->getParent();
1828 Constant *SIPrintFFn =
1829 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1830 CallInst *New = cast<CallInst>(CI->clone());
1831 New->setCalledFunction(SIPrintFFn);
1838 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1839 optimizeErrorReporting(CI, B, 0);
1841 // All the optimizations depend on the format string.
1842 StringRef FormatStr;
1843 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1846 // Do not do any of the following transformations if the fprintf return
1847 // value is used, in general the fprintf return value is not compatible
1848 // with fwrite(), fputc() or fputs().
1849 if (!CI->use_empty())
1852 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1853 if (CI->getNumArgOperands() == 2) {
1854 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1855 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1856 return nullptr; // We found a format specifier.
1859 CI->getArgOperand(1),
1860 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1861 CI->getArgOperand(0), B, DL, TLI);
1864 // The remaining optimizations require the format string to be "%s" or "%c"
1865 // and have an extra operand.
1866 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1867 CI->getNumArgOperands() < 3)
1870 // Decode the second character of the format string.
1871 if (FormatStr[1] == 'c') {
1872 // fprintf(F, "%c", chr) --> fputc(chr, F)
1873 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1875 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1878 if (FormatStr[1] == 's') {
1879 // fprintf(F, "%s", str) --> fputs(str, F)
1880 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1882 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1887 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1888 Function *Callee = CI->getCalledFunction();
1889 // Require two fixed paramters as pointers and integer result.
1890 FunctionType *FT = Callee->getFunctionType();
1891 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1892 !FT->getParamType(1)->isPointerTy() ||
1893 !FT->getReturnType()->isIntegerTy())
1896 if (Value *V = optimizeFPrintFString(CI, B)) {
1900 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1901 // floating point arguments.
1902 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1903 Module *M = B.GetInsertBlock()->getParent()->getParent();
1904 Constant *FIPrintFFn =
1905 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1906 CallInst *New = cast<CallInst>(CI->clone());
1907 New->setCalledFunction(FIPrintFFn);
1914 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1915 optimizeErrorReporting(CI, B, 3);
1917 Function *Callee = CI->getCalledFunction();
1918 // Require a pointer, an integer, an integer, a pointer, returning integer.
1919 FunctionType *FT = Callee->getFunctionType();
1920 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1921 !FT->getParamType(1)->isIntegerTy() ||
1922 !FT->getParamType(2)->isIntegerTy() ||
1923 !FT->getParamType(3)->isPointerTy() ||
1924 !FT->getReturnType()->isIntegerTy())
1927 // Get the element size and count.
1928 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1929 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1930 if (!SizeC || !CountC)
1932 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1934 // If this is writing zero records, remove the call (it's a noop).
1936 return ConstantInt::get(CI->getType(), 0);
1938 // If this is writing one byte, turn it into fputc.
1939 // This optimisation is only valid, if the return value is unused.
1940 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1941 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1942 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1943 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1949 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1950 optimizeErrorReporting(CI, B, 1);
1952 Function *Callee = CI->getCalledFunction();
1954 // Require two pointers. Also, we can't optimize if return value is used.
1955 FunctionType *FT = Callee->getFunctionType();
1956 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1957 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1960 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1961 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1965 // Known to have no uses (see above).
1967 CI->getArgOperand(0),
1968 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1969 CI->getArgOperand(1), B, DL, TLI);
1972 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1973 Function *Callee = CI->getCalledFunction();
1974 // Require one fixed pointer argument and an integer/void result.
1975 FunctionType *FT = Callee->getFunctionType();
1976 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1977 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1980 // Check for a constant string.
1982 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1985 if (Str.empty() && CI->use_empty()) {
1986 // puts("") -> putchar('\n')
1987 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1988 if (CI->use_empty() || !Res)
1990 return B.CreateIntCast(Res, CI->getType(), true);
1996 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1998 SmallString<20> FloatFuncName = FuncName;
1999 FloatFuncName += 'f';
2000 if (TLI->getLibFunc(FloatFuncName, Func))
2001 return TLI->has(Func);
2005 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2006 IRBuilder<> &Builder) {
2008 Function *Callee = CI->getCalledFunction();
2009 StringRef FuncName = Callee->getName();
2011 // Check for string/memory library functions.
2012 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2013 // Make sure we never change the calling convention.
2014 assert((ignoreCallingConv(Func) ||
2015 CI->getCallingConv() == llvm::CallingConv::C) &&
2016 "Optimizing string/memory libcall would change the calling convention");
2018 case LibFunc::strcat:
2019 return optimizeStrCat(CI, Builder);
2020 case LibFunc::strncat:
2021 return optimizeStrNCat(CI, Builder);
2022 case LibFunc::strchr:
2023 return optimizeStrChr(CI, Builder);
2024 case LibFunc::strrchr:
2025 return optimizeStrRChr(CI, Builder);
2026 case LibFunc::strcmp:
2027 return optimizeStrCmp(CI, Builder);
2028 case LibFunc::strncmp:
2029 return optimizeStrNCmp(CI, Builder);
2030 case LibFunc::strcpy:
2031 return optimizeStrCpy(CI, Builder);
2032 case LibFunc::stpcpy:
2033 return optimizeStpCpy(CI, Builder);
2034 case LibFunc::strncpy:
2035 return optimizeStrNCpy(CI, Builder);
2036 case LibFunc::strlen:
2037 return optimizeStrLen(CI, Builder);
2038 case LibFunc::strpbrk:
2039 return optimizeStrPBrk(CI, Builder);
2040 case LibFunc::strtol:
2041 case LibFunc::strtod:
2042 case LibFunc::strtof:
2043 case LibFunc::strtoul:
2044 case LibFunc::strtoll:
2045 case LibFunc::strtold:
2046 case LibFunc::strtoull:
2047 return optimizeStrTo(CI, Builder);
2048 case LibFunc::strspn:
2049 return optimizeStrSpn(CI, Builder);
2050 case LibFunc::strcspn:
2051 return optimizeStrCSpn(CI, Builder);
2052 case LibFunc::strstr:
2053 return optimizeStrStr(CI, Builder);
2054 case LibFunc::memchr:
2055 return optimizeMemChr(CI, Builder);
2056 case LibFunc::memcmp:
2057 return optimizeMemCmp(CI, Builder);
2058 case LibFunc::memcpy:
2059 return optimizeMemCpy(CI, Builder);
2060 case LibFunc::memmove:
2061 return optimizeMemMove(CI, Builder);
2062 case LibFunc::memset:
2063 return optimizeMemSet(CI, Builder);
2071 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2072 if (CI->isNoBuiltin())
2076 Function *Callee = CI->getCalledFunction();
2077 StringRef FuncName = Callee->getName();
2078 IRBuilder<> Builder(CI);
2079 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2081 // Command-line parameter overrides function attribute.
2082 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2083 UnsafeFPShrink = EnableUnsafeFPShrink;
2084 else if (canUseUnsafeFPMath(Callee))
2085 UnsafeFPShrink = true;
2087 // First, check for intrinsics.
2088 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2089 if (!isCallingConvC)
2091 switch (II->getIntrinsicID()) {
2092 case Intrinsic::pow:
2093 return optimizePow(CI, Builder);
2094 case Intrinsic::exp2:
2095 return optimizeExp2(CI, Builder);
2096 case Intrinsic::fabs:
2097 return optimizeFabs(CI, Builder);
2098 case Intrinsic::sqrt:
2099 return optimizeSqrt(CI, Builder);
2105 // Also try to simplify calls to fortified library functions.
2106 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2107 // Try to further simplify the result.
2108 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2109 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2110 // Use an IR Builder from SimplifiedCI if available instead of CI
2111 // to guarantee we reach all uses we might replace later on.
2112 IRBuilder<> TmpBuilder(SimplifiedCI);
2113 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2114 // If we were able to further simplify, remove the now redundant call.
2115 SimplifiedCI->replaceAllUsesWith(V);
2116 SimplifiedCI->eraseFromParent();
2120 return SimplifiedFortifiedCI;
2123 // Then check for known library functions.
2124 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2125 // We never change the calling convention.
2126 if (!ignoreCallingConv(Func) && !isCallingConvC)
2128 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2134 return optimizeCos(CI, Builder);
2135 case LibFunc::sinpif:
2136 case LibFunc::sinpi:
2137 case LibFunc::cospif:
2138 case LibFunc::cospi:
2139 return optimizeSinCosPi(CI, Builder);
2143 return optimizePow(CI, Builder);
2144 case LibFunc::exp2l:
2146 case LibFunc::exp2f:
2147 return optimizeExp2(CI, Builder);
2148 case LibFunc::fabsf:
2150 case LibFunc::fabsl:
2151 return optimizeFabs(CI, Builder);
2152 case LibFunc::sqrtf:
2154 case LibFunc::sqrtl:
2155 return optimizeSqrt(CI, Builder);
2158 case LibFunc::ffsll:
2159 return optimizeFFS(CI, Builder);
2162 case LibFunc::llabs:
2163 return optimizeAbs(CI, Builder);
2164 case LibFunc::isdigit:
2165 return optimizeIsDigit(CI, Builder);
2166 case LibFunc::isascii:
2167 return optimizeIsAscii(CI, Builder);
2168 case LibFunc::toascii:
2169 return optimizeToAscii(CI, Builder);
2170 case LibFunc::printf:
2171 return optimizePrintF(CI, Builder);
2172 case LibFunc::sprintf:
2173 return optimizeSPrintF(CI, Builder);
2174 case LibFunc::fprintf:
2175 return optimizeFPrintF(CI, Builder);
2176 case LibFunc::fwrite:
2177 return optimizeFWrite(CI, Builder);
2178 case LibFunc::fputs:
2179 return optimizeFPuts(CI, Builder);
2181 return optimizePuts(CI, Builder);
2185 return optimizeTan(CI, Builder);
2186 case LibFunc::perror:
2187 return optimizeErrorReporting(CI, Builder);
2188 case LibFunc::vfprintf:
2189 case LibFunc::fiprintf:
2190 return optimizeErrorReporting(CI, Builder, 0);
2191 case LibFunc::fputc:
2192 return optimizeErrorReporting(CI, Builder, 1);
2194 case LibFunc::floor:
2196 case LibFunc::round:
2197 case LibFunc::nearbyint:
2198 case LibFunc::trunc:
2199 if (hasFloatVersion(FuncName))
2200 return optimizeUnaryDoubleFP(CI, Builder, false);
2203 case LibFunc::acosh:
2205 case LibFunc::asinh:
2207 case LibFunc::atanh:
2211 case LibFunc::exp10:
2212 case LibFunc::expm1:
2214 case LibFunc::log10:
2215 case LibFunc::log1p:
2221 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2222 return optimizeUnaryDoubleFP(CI, Builder, true);
2224 case LibFunc::copysign:
2225 if (hasFloatVersion(FuncName))
2226 return optimizeBinaryDoubleFP(CI, Builder);
2228 case LibFunc::fminf:
2230 case LibFunc::fminl:
2231 case LibFunc::fmaxf:
2233 case LibFunc::fmaxl:
2234 return optimizeFMinFMax(CI, Builder);
2242 LibCallSimplifier::LibCallSimplifier(
2243 const DataLayout &DL, const TargetLibraryInfo *TLI,
2244 function_ref<void(Instruction *, Value *)> Replacer)
2245 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2246 Replacer(Replacer) {}
2248 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2249 // Indirect through the replacer used in this instance.
2254 // Additional cases that we need to add to this file:
2257 // * cbrt(expN(X)) -> expN(x/3)
2258 // * cbrt(sqrt(x)) -> pow(x,1/6)
2259 // * cbrt(cbrt(x)) -> pow(x,1/9)
2262 // * exp(log(x)) -> x
2265 // * log(exp(x)) -> x
2266 // * log(x**y) -> y*log(x)
2267 // * log(exp(y)) -> y*log(e)
2268 // * log(exp2(y)) -> y*log(2)
2269 // * log(exp10(y)) -> y*log(10)
2270 // * log(sqrt(x)) -> 0.5*log(x)
2271 // * log(pow(x,y)) -> y*log(x)
2273 // lround, lroundf, lroundl:
2274 // * lround(cnst) -> cnst'
2277 // * pow(exp(x),y) -> exp(x*y)
2278 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2279 // * pow(pow(x,y),z)-> pow(x,y*z)
2281 // round, roundf, roundl:
2282 // * round(cnst) -> cnst'
2285 // * signbit(cnst) -> cnst'
2286 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2288 // sqrt, sqrtf, sqrtl:
2289 // * sqrt(expN(x)) -> expN(x*0.5)
2290 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2291 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2294 // * tan(atan(x)) -> x
2296 // trunc, truncf, truncl:
2297 // * trunc(cnst) -> cnst'
2301 //===----------------------------------------------------------------------===//
2302 // Fortified Library Call Optimizations
2303 //===----------------------------------------------------------------------===//
2305 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2309 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2311 if (ConstantInt *ObjSizeCI =
2312 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2313 if (ObjSizeCI->isAllOnesValue())
2315 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2316 if (OnlyLowerUnknownSize)
2319 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2320 // If the length is 0 we don't know how long it is and so we can't
2321 // remove the check.
2324 return ObjSizeCI->getZExtValue() >= Len;
2326 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2327 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2332 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2333 Function *Callee = CI->getCalledFunction();
2335 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2338 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2339 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2340 CI->getArgOperand(2), 1);
2341 return CI->getArgOperand(0);
2346 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2347 Function *Callee = CI->getCalledFunction();
2349 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2352 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2353 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2354 CI->getArgOperand(2), 1);
2355 return CI->getArgOperand(0);
2360 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2361 Function *Callee = CI->getCalledFunction();
2363 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2366 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2367 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2368 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2369 return CI->getArgOperand(0);
2374 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2376 LibFunc::Func Func) {
2377 Function *Callee = CI->getCalledFunction();
2378 StringRef Name = Callee->getName();
2379 const DataLayout &DL = CI->getModule()->getDataLayout();
2381 if (!checkStringCopyLibFuncSignature(Callee, Func))
2384 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2385 *ObjSize = CI->getArgOperand(2);
2387 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2388 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2389 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2390 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2393 // If a) we don't have any length information, or b) we know this will
2394 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2395 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2396 // TODO: It might be nice to get a maximum length out of the possible
2397 // string lengths for varying.
2398 if (isFortifiedCallFoldable(CI, 2, 1, true))
2399 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2401 if (OnlyLowerUnknownSize)
2404 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2405 uint64_t Len = GetStringLength(Src);
2409 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2410 Value *LenV = ConstantInt::get(SizeTTy, Len);
2411 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2412 // If the function was an __stpcpy_chk, and we were able to fold it into
2413 // a __memcpy_chk, we still need to return the correct end pointer.
2414 if (Ret && Func == LibFunc::stpcpy_chk)
2415 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2419 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2421 LibFunc::Func Func) {
2422 Function *Callee = CI->getCalledFunction();
2423 StringRef Name = Callee->getName();
2425 if (!checkStringCopyLibFuncSignature(Callee, Func))
2427 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2428 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2429 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2435 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2436 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2437 // Some clang users checked for _chk libcall availability using:
2438 // __has_builtin(__builtin___memcpy_chk)
2439 // When compiling with -fno-builtin, this is always true.
2440 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2441 // end up with fortified libcalls, which isn't acceptable in a freestanding
2442 // environment which only provides their non-fortified counterparts.
2444 // Until we change clang and/or teach external users to check for availability
2445 // differently, disregard the "nobuiltin" attribute and TLI::has.
2450 Function *Callee = CI->getCalledFunction();
2451 StringRef FuncName = Callee->getName();
2452 IRBuilder<> Builder(CI);
2453 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2455 // First, check that this is a known library functions.
2456 if (!TLI->getLibFunc(FuncName, Func))
2459 // We never change the calling convention.
2460 if (!ignoreCallingConv(Func) && !isCallingConvC)
2464 case LibFunc::memcpy_chk:
2465 return optimizeMemCpyChk(CI, Builder);
2466 case LibFunc::memmove_chk:
2467 return optimizeMemMoveChk(CI, Builder);
2468 case LibFunc::memset_chk:
2469 return optimizeMemSetChk(CI, Builder);
2470 case LibFunc::stpcpy_chk:
2471 case LibFunc::strcpy_chk:
2472 return optimizeStrpCpyChk(CI, Builder, Func);
2473 case LibFunc::stpncpy_chk:
2474 case LibFunc::strncpy_chk:
2475 return optimizeStrpNCpyChk(CI, Builder, Func);
2482 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2483 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2484 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}