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 Returns whether \p F matches the signature expected for the
121 /// string/memory copying library function \p Func.
122 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
123 /// Their fortified (_chk) counterparts are also accepted.
124 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
125 const DataLayout &DL = F->getParent()->getDataLayout();
126 FunctionType *FT = F->getFunctionType();
127 LLVMContext &Context = F->getContext();
128 Type *PCharTy = Type::getInt8PtrTy(Context);
129 Type *SizeTTy = DL.getIntPtrType(Context);
130 unsigned NumParams = FT->getNumParams();
132 // All string libfuncs return the same type as the first parameter.
133 if (FT->getReturnType() != FT->getParamType(0))
138 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
139 case LibFunc::stpncpy_chk:
140 case LibFunc::strncpy_chk:
141 --NumParams; // fallthrough
142 case LibFunc::stpncpy:
143 case LibFunc::strncpy: {
144 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
145 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
149 case LibFunc::strcpy_chk:
150 case LibFunc::stpcpy_chk:
151 --NumParams; // fallthrough
152 case LibFunc::stpcpy:
153 case LibFunc::strcpy: {
154 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
155 FT->getParamType(0) != PCharTy)
159 case LibFunc::memmove_chk:
160 case LibFunc::memcpy_chk:
161 --NumParams; // fallthrough
162 case LibFunc::memmove:
163 case LibFunc::memcpy: {
164 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
165 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
169 case LibFunc::memset_chk:
170 --NumParams; // fallthrough
171 case LibFunc::memset: {
172 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
173 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
178 // If this is a fortified libcall, the last parameter is a size_t.
179 if (NumParams == FT->getNumParams() - 1)
180 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
184 //===----------------------------------------------------------------------===//
185 // String and Memory Library Call Optimizations
186 //===----------------------------------------------------------------------===//
188 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
189 Function *Callee = CI->getCalledFunction();
190 // Verify the "strcat" function prototype.
191 FunctionType *FT = Callee->getFunctionType();
192 if (FT->getNumParams() != 2||
193 FT->getReturnType() != B.getInt8PtrTy() ||
194 FT->getParamType(0) != FT->getReturnType() ||
195 FT->getParamType(1) != FT->getReturnType())
198 // Extract some information from the instruction
199 Value *Dst = CI->getArgOperand(0);
200 Value *Src = CI->getArgOperand(1);
202 // See if we can get the length of the input string.
203 uint64_t Len = GetStringLength(Src);
206 --Len; // Unbias length.
208 // Handle the simple, do-nothing case: strcat(x, "") -> x
212 return emitStrLenMemCpy(Src, Dst, Len, B);
215 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
217 // We need to find the end of the destination string. That's where the
218 // memory is to be moved to. We just generate a call to strlen.
219 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
223 // Now that we have the destination's length, we must index into the
224 // destination's pointer to get the actual memcpy destination (end of
225 // the string .. we're concatenating).
226 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
228 // We have enough information to now generate the memcpy call to do the
229 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
230 B.CreateMemCpy(CpyDst, Src,
231 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
236 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
237 Function *Callee = CI->getCalledFunction();
238 // Verify the "strncat" function prototype.
239 FunctionType *FT = Callee->getFunctionType();
240 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
241 FT->getParamType(0) != FT->getReturnType() ||
242 FT->getParamType(1) != FT->getReturnType() ||
243 !FT->getParamType(2)->isIntegerTy())
246 // Extract some information from the instruction
247 Value *Dst = CI->getArgOperand(0);
248 Value *Src = CI->getArgOperand(1);
251 // We don't do anything if length is not constant
252 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
253 Len = LengthArg->getZExtValue();
257 // See if we can get the length of the input string.
258 uint64_t SrcLen = GetStringLength(Src);
261 --SrcLen; // Unbias length.
263 // Handle the simple, do-nothing cases:
264 // strncat(x, "", c) -> x
265 // strncat(x, c, 0) -> x
266 if (SrcLen == 0 || Len == 0)
269 // We don't optimize this case
273 // strncat(x, s, c) -> strcat(x, s)
274 // s is constant so the strcat can be optimized further
275 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
278 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
279 Function *Callee = CI->getCalledFunction();
280 // Verify the "strchr" function prototype.
281 FunctionType *FT = Callee->getFunctionType();
282 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
283 FT->getParamType(0) != FT->getReturnType() ||
284 !FT->getParamType(1)->isIntegerTy(32))
287 Value *SrcStr = CI->getArgOperand(0);
289 // If the second operand is non-constant, see if we can compute the length
290 // of the input string and turn this into memchr.
291 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
293 uint64_t Len = GetStringLength(SrcStr);
294 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
297 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
298 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
302 // Otherwise, the character is a constant, see if the first argument is
303 // a string literal. If so, we can constant fold.
305 if (!getConstantStringInfo(SrcStr, Str)) {
306 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
307 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
311 // Compute the offset, make sure to handle the case when we're searching for
312 // zero (a weird way to spell strlen).
313 size_t I = (0xFF & CharC->getSExtValue()) == 0
315 : Str.find(CharC->getSExtValue());
316 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
317 return Constant::getNullValue(CI->getType());
319 // strchr(s+n,c) -> gep(s+n+i,c)
320 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
323 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
324 Function *Callee = CI->getCalledFunction();
325 // Verify the "strrchr" function prototype.
326 FunctionType *FT = Callee->getFunctionType();
327 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
328 FT->getParamType(0) != FT->getReturnType() ||
329 !FT->getParamType(1)->isIntegerTy(32))
332 Value *SrcStr = CI->getArgOperand(0);
333 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
335 // Cannot fold anything if we're not looking for a constant.
340 if (!getConstantStringInfo(SrcStr, Str)) {
341 // strrchr(s, 0) -> strchr(s, 0)
343 return EmitStrChr(SrcStr, '\0', B, TLI);
347 // Compute the offset.
348 size_t I = (0xFF & CharC->getSExtValue()) == 0
350 : Str.rfind(CharC->getSExtValue());
351 if (I == StringRef::npos) // Didn't find the char. Return null.
352 return Constant::getNullValue(CI->getType());
354 // strrchr(s+n,c) -> gep(s+n+i,c)
355 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
358 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
359 Function *Callee = CI->getCalledFunction();
360 // Verify the "strcmp" function prototype.
361 FunctionType *FT = Callee->getFunctionType();
362 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
363 FT->getParamType(0) != FT->getParamType(1) ||
364 FT->getParamType(0) != B.getInt8PtrTy())
367 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
368 if (Str1P == Str2P) // strcmp(x,x) -> 0
369 return ConstantInt::get(CI->getType(), 0);
371 StringRef Str1, Str2;
372 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
373 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
375 // strcmp(x, y) -> cnst (if both x and y are constant strings)
376 if (HasStr1 && HasStr2)
377 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
379 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
381 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
383 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
384 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
386 // strcmp(P, "x") -> memcmp(P, "x", 2)
387 uint64_t Len1 = GetStringLength(Str1P);
388 uint64_t Len2 = GetStringLength(Str2P);
390 return EmitMemCmp(Str1P, Str2P,
391 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
392 std::min(Len1, Len2)),
399 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
400 Function *Callee = CI->getCalledFunction();
401 // Verify the "strncmp" function prototype.
402 FunctionType *FT = Callee->getFunctionType();
403 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
404 FT->getParamType(0) != FT->getParamType(1) ||
405 FT->getParamType(0) != B.getInt8PtrTy() ||
406 !FT->getParamType(2)->isIntegerTy())
409 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
410 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
411 return ConstantInt::get(CI->getType(), 0);
413 // Get the length argument if it is constant.
415 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
416 Length = LengthArg->getZExtValue();
420 if (Length == 0) // strncmp(x,y,0) -> 0
421 return ConstantInt::get(CI->getType(), 0);
423 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
424 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
426 StringRef Str1, Str2;
427 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
428 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
430 // strncmp(x, y) -> cnst (if both x and y are constant strings)
431 if (HasStr1 && HasStr2) {
432 StringRef SubStr1 = Str1.substr(0, Length);
433 StringRef SubStr2 = Str2.substr(0, Length);
434 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
437 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
439 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
441 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
442 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
447 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
448 Function *Callee = CI->getCalledFunction();
450 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
453 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
454 if (Dst == Src) // strcpy(x,x) -> x
457 // See if we can get the length of the input string.
458 uint64_t Len = GetStringLength(Src);
462 // We have enough information to now generate the memcpy call to do the
463 // copy for us. Make a memcpy to copy the nul byte with align = 1.
464 B.CreateMemCpy(Dst, Src,
465 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
469 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
470 Function *Callee = CI->getCalledFunction();
471 // Verify the "stpcpy" function prototype.
472 FunctionType *FT = Callee->getFunctionType();
474 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
477 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
478 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
479 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
480 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
483 // See if we can get the length of the input string.
484 uint64_t Len = GetStringLength(Src);
488 Type *PT = FT->getParamType(0);
489 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
491 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
493 // We have enough information to now generate the memcpy call to do the
494 // copy for us. Make a memcpy to copy the nul byte with align = 1.
495 B.CreateMemCpy(Dst, Src, LenV, 1);
499 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
500 Function *Callee = CI->getCalledFunction();
501 FunctionType *FT = Callee->getFunctionType();
503 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
506 Value *Dst = CI->getArgOperand(0);
507 Value *Src = CI->getArgOperand(1);
508 Value *LenOp = CI->getArgOperand(2);
510 // See if we can get the length of the input string.
511 uint64_t SrcLen = GetStringLength(Src);
517 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
518 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
523 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
524 Len = LengthArg->getZExtValue();
529 return Dst; // strncpy(x, y, 0) -> x
531 // Let strncpy handle the zero padding
532 if (Len > SrcLen + 1)
535 Type *PT = FT->getParamType(0);
536 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
537 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
542 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
543 Function *Callee = CI->getCalledFunction();
544 FunctionType *FT = Callee->getFunctionType();
545 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
546 !FT->getReturnType()->isIntegerTy())
549 Value *Src = CI->getArgOperand(0);
551 // Constant folding: strlen("xyz") -> 3
552 if (uint64_t Len = GetStringLength(Src))
553 return ConstantInt::get(CI->getType(), Len - 1);
555 // strlen(x?"foo":"bars") --> x ? 3 : 4
556 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
557 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
558 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
559 if (LenTrue && LenFalse) {
560 Function *Caller = CI->getParent()->getParent();
561 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
563 "folded strlen(select) to select of constants");
564 return B.CreateSelect(SI->getCondition(),
565 ConstantInt::get(CI->getType(), LenTrue - 1),
566 ConstantInt::get(CI->getType(), LenFalse - 1));
570 // strlen(x) != 0 --> *x != 0
571 // strlen(x) == 0 --> *x == 0
572 if (isOnlyUsedInZeroEqualityComparison(CI))
573 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
578 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
579 Function *Callee = CI->getCalledFunction();
580 FunctionType *FT = Callee->getFunctionType();
581 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
582 FT->getParamType(1) != FT->getParamType(0) ||
583 FT->getReturnType() != FT->getParamType(0))
587 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
588 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
590 // strpbrk(s, "") -> nullptr
591 // strpbrk("", s) -> nullptr
592 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
593 return Constant::getNullValue(CI->getType());
596 if (HasS1 && HasS2) {
597 size_t I = S1.find_first_of(S2);
598 if (I == StringRef::npos) // No match.
599 return Constant::getNullValue(CI->getType());
601 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
604 // strpbrk(s, "a") -> strchr(s, 'a')
605 if (HasS2 && S2.size() == 1)
606 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
611 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
612 Function *Callee = CI->getCalledFunction();
613 FunctionType *FT = Callee->getFunctionType();
614 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
615 !FT->getParamType(0)->isPointerTy() ||
616 !FT->getParamType(1)->isPointerTy())
619 Value *EndPtr = CI->getArgOperand(1);
620 if (isa<ConstantPointerNull>(EndPtr)) {
621 // With a null EndPtr, this function won't capture the main argument.
622 // It would be readonly too, except that it still may write to errno.
623 CI->addAttribute(1, Attribute::NoCapture);
629 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
630 Function *Callee = CI->getCalledFunction();
631 FunctionType *FT = Callee->getFunctionType();
632 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
633 FT->getParamType(1) != FT->getParamType(0) ||
634 !FT->getReturnType()->isIntegerTy())
638 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
639 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
641 // strspn(s, "") -> 0
642 // strspn("", s) -> 0
643 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
644 return Constant::getNullValue(CI->getType());
647 if (HasS1 && HasS2) {
648 size_t Pos = S1.find_first_not_of(S2);
649 if (Pos == StringRef::npos)
651 return ConstantInt::get(CI->getType(), Pos);
657 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
658 Function *Callee = CI->getCalledFunction();
659 FunctionType *FT = Callee->getFunctionType();
660 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
661 FT->getParamType(1) != FT->getParamType(0) ||
662 !FT->getReturnType()->isIntegerTy())
666 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
667 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
669 // strcspn("", s) -> 0
670 if (HasS1 && S1.empty())
671 return Constant::getNullValue(CI->getType());
674 if (HasS1 && HasS2) {
675 size_t Pos = S1.find_first_of(S2);
676 if (Pos == StringRef::npos)
678 return ConstantInt::get(CI->getType(), Pos);
681 // strcspn(s, "") -> strlen(s)
682 if (HasS2 && S2.empty())
683 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
688 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
689 Function *Callee = CI->getCalledFunction();
690 FunctionType *FT = Callee->getFunctionType();
691 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
692 !FT->getParamType(1)->isPointerTy() ||
693 !FT->getReturnType()->isPointerTy())
696 // fold strstr(x, x) -> x.
697 if (CI->getArgOperand(0) == CI->getArgOperand(1))
698 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
700 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
701 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
702 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
705 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
709 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
710 ICmpInst *Old = cast<ICmpInst>(*UI++);
712 B.CreateICmp(Old->getPredicate(), StrNCmp,
713 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
714 replaceAllUsesWith(Old, Cmp);
719 // See if either input string is a constant string.
720 StringRef SearchStr, ToFindStr;
721 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
722 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
724 // fold strstr(x, "") -> x.
725 if (HasStr2 && ToFindStr.empty())
726 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
728 // If both strings are known, constant fold it.
729 if (HasStr1 && HasStr2) {
730 size_t Offset = SearchStr.find(ToFindStr);
732 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
733 return Constant::getNullValue(CI->getType());
735 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
736 Value *Result = CastToCStr(CI->getArgOperand(0), B);
737 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
738 return B.CreateBitCast(Result, CI->getType());
741 // fold strstr(x, "y") -> strchr(x, 'y').
742 if (HasStr2 && ToFindStr.size() == 1) {
743 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
744 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
749 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
750 Function *Callee = CI->getCalledFunction();
751 FunctionType *FT = Callee->getFunctionType();
752 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
753 !FT->getParamType(1)->isIntegerTy(32) ||
754 !FT->getParamType(2)->isIntegerTy() ||
755 !FT->getReturnType()->isPointerTy())
758 Value *SrcStr = CI->getArgOperand(0);
759 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
760 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
762 // memchr(x, y, 0) -> null
763 if (LenC && LenC->isNullValue())
764 return Constant::getNullValue(CI->getType());
766 // From now on we need at least constant length and string.
768 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
771 // Truncate the string to LenC. If Str is smaller than LenC we will still only
772 // scan the string, as reading past the end of it is undefined and we can just
773 // return null if we don't find the char.
774 Str = Str.substr(0, LenC->getZExtValue());
776 // If the char is variable but the input str and length are not we can turn
777 // this memchr call into a simple bit field test. Of course this only works
778 // when the return value is only checked against null.
780 // It would be really nice to reuse switch lowering here but we can't change
781 // the CFG at this point.
783 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
784 // after bounds check.
785 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
787 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
788 reinterpret_cast<const unsigned char *>(Str.end()));
790 // Make sure the bit field we're about to create fits in a register on the
792 // FIXME: On a 64 bit architecture this prevents us from using the
793 // interesting range of alpha ascii chars. We could do better by emitting
794 // two bitfields or shifting the range by 64 if no lower chars are used.
795 if (!DL.fitsInLegalInteger(Max + 1))
798 // For the bit field use a power-of-2 type with at least 8 bits to avoid
799 // creating unnecessary illegal types.
800 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
802 // Now build the bit field.
803 APInt Bitfield(Width, 0);
805 Bitfield.setBit((unsigned char)C);
806 Value *BitfieldC = B.getInt(Bitfield);
808 // First check that the bit field access is within bounds.
809 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
810 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
813 // Create code that checks if the given bit is set in the field.
814 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
815 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
817 // Finally merge both checks and cast to pointer type. The inttoptr
818 // implicitly zexts the i1 to intptr type.
819 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
822 // Check if all arguments are constants. If so, we can constant fold.
826 // Compute the offset.
827 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
828 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
829 return Constant::getNullValue(CI->getType());
831 // memchr(s+n,c,l) -> gep(s+n+i,c)
832 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
835 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
836 Function *Callee = CI->getCalledFunction();
837 FunctionType *FT = Callee->getFunctionType();
838 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
839 !FT->getParamType(1)->isPointerTy() ||
840 !FT->getReturnType()->isIntegerTy(32))
843 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
845 if (LHS == RHS) // memcmp(s,s,x) -> 0
846 return Constant::getNullValue(CI->getType());
848 // Make sure we have a constant length.
849 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
852 uint64_t Len = LenC->getZExtValue();
854 if (Len == 0) // memcmp(s1,s2,0) -> 0
855 return Constant::getNullValue(CI->getType());
857 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
859 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
860 CI->getType(), "lhsv");
861 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
862 CI->getType(), "rhsv");
863 return B.CreateSub(LHSV, RHSV, "chardiff");
866 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
867 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
869 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
870 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
872 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
873 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
876 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
878 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
880 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
881 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
883 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
887 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
888 StringRef LHSStr, RHSStr;
889 if (getConstantStringInfo(LHS, LHSStr) &&
890 getConstantStringInfo(RHS, RHSStr)) {
891 // Make sure we're not reading out-of-bounds memory.
892 if (Len > LHSStr.size() || Len > RHSStr.size())
894 // Fold the memcmp and normalize the result. This way we get consistent
895 // results across multiple platforms.
897 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
902 return ConstantInt::get(CI->getType(), Ret);
908 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
909 Function *Callee = CI->getCalledFunction();
911 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
914 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
915 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
916 CI->getArgOperand(2), 1);
917 return CI->getArgOperand(0);
920 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
921 Function *Callee = CI->getCalledFunction();
923 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
926 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
927 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
928 CI->getArgOperand(2), 1);
929 return CI->getArgOperand(0);
932 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
933 Function *Callee = CI->getCalledFunction();
935 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
938 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
939 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
940 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
941 return CI->getArgOperand(0);
944 //===----------------------------------------------------------------------===//
945 // Math Library Optimizations
946 //===----------------------------------------------------------------------===//
948 /// Return a variant of Val with float type.
949 /// Currently this works in two cases: If Val is an FPExtension of a float
950 /// value to something bigger, simply return the operand.
951 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
952 /// loss of precision do so.
953 static Value *valueHasFloatPrecision(Value *Val) {
954 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
955 Value *Op = Cast->getOperand(0);
956 if (Op->getType()->isFloatTy())
959 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
960 APFloat F = Const->getValueAPF();
962 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
965 return ConstantFP::get(Const->getContext(), F);
970 //===----------------------------------------------------------------------===//
971 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
973 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
975 Function *Callee = CI->getCalledFunction();
976 FunctionType *FT = Callee->getFunctionType();
977 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
978 !FT->getParamType(0)->isDoubleTy())
982 // Check if all the uses for function like 'sin' are converted to float.
983 for (User *U : CI->users()) {
984 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
985 if (!Cast || !Cast->getType()->isFloatTy())
990 // If this is something like 'floor((double)floatval)', convert to floorf.
991 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
995 // floor((double)floatval) -> (double)floorf(floatval)
996 if (Callee->isIntrinsic()) {
997 Module *M = CI->getParent()->getParent()->getParent();
998 Intrinsic::ID IID = Callee->getIntrinsicID();
999 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1000 V = B.CreateCall(F, V);
1002 // The call is a library call rather than an intrinsic.
1003 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1006 return B.CreateFPExt(V, B.getDoubleTy());
1009 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1010 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1011 Function *Callee = CI->getCalledFunction();
1012 FunctionType *FT = Callee->getFunctionType();
1013 // Just make sure this has 2 arguments of the same FP type, which match the
1015 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1016 FT->getParamType(0) != FT->getParamType(1) ||
1017 !FT->getParamType(0)->isFloatingPointTy())
1020 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1021 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1022 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1025 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1029 // fmin((double)floatval1, (double)floatval2)
1030 // -> (double)fminf(floatval1, floatval2)
1031 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1032 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1033 Callee->getAttributes());
1034 return B.CreateFPExt(V, B.getDoubleTy());
1037 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1038 Function *Callee = CI->getCalledFunction();
1039 Value *Ret = nullptr;
1040 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1041 Ret = optimizeUnaryDoubleFP(CI, B, true);
1044 FunctionType *FT = Callee->getFunctionType();
1045 // Just make sure this has 1 argument of FP type, which matches the
1047 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1048 !FT->getParamType(0)->isFloatingPointTy())
1051 // cos(-x) -> cos(x)
1052 Value *Op1 = CI->getArgOperand(0);
1053 if (BinaryOperator::isFNeg(Op1)) {
1054 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1055 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1060 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1061 Function *Callee = CI->getCalledFunction();
1063 Value *Ret = nullptr;
1064 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1065 Ret = optimizeUnaryDoubleFP(CI, B, true);
1068 FunctionType *FT = Callee->getFunctionType();
1069 // Just make sure this has 2 arguments of the same FP type, which match the
1071 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1072 FT->getParamType(0) != FT->getParamType(1) ||
1073 !FT->getParamType(0)->isFloatingPointTy())
1076 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1077 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1078 // pow(1.0, x) -> 1.0
1079 if (Op1C->isExactlyValue(1.0))
1081 // pow(2.0, x) -> exp2(x)
1082 if (Op1C->isExactlyValue(2.0) &&
1083 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1085 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1086 // pow(10.0, x) -> exp10(x)
1087 if (Op1C->isExactlyValue(10.0) &&
1088 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1090 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1091 Callee->getAttributes());
1094 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1098 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1099 return ConstantFP::get(CI->getType(), 1.0);
1101 if (Op2C->isExactlyValue(0.5) &&
1102 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1104 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1106 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1107 // This is faster than calling pow, and still handles negative zero
1108 // and negative infinity correctly.
1109 // TODO: In fast-math mode, this could be just sqrt(x).
1110 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1111 Value *Inf = ConstantFP::getInfinity(CI->getType());
1112 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1113 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1115 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1116 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1117 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1121 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1123 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1124 return B.CreateFMul(Op1, Op1, "pow2");
1125 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1126 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1130 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1131 Function *Callee = CI->getCalledFunction();
1132 Function *Caller = CI->getParent()->getParent();
1134 Value *Ret = nullptr;
1135 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1136 TLI->has(LibFunc::exp2f)) {
1137 Ret = optimizeUnaryDoubleFP(CI, B, true);
1140 FunctionType *FT = Callee->getFunctionType();
1141 // Just make sure this has 1 argument of FP type, which matches the
1143 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1144 !FT->getParamType(0)->isFloatingPointTy())
1147 Value *Op = CI->getArgOperand(0);
1148 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1149 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1150 LibFunc::Func LdExp = LibFunc::ldexpl;
1151 if (Op->getType()->isFloatTy())
1152 LdExp = LibFunc::ldexpf;
1153 else if (Op->getType()->isDoubleTy())
1154 LdExp = LibFunc::ldexp;
1156 if (TLI->has(LdExp)) {
1157 Value *LdExpArg = nullptr;
1158 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1159 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1160 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1161 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1162 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1163 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1167 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1168 if (!Op->getType()->isFloatTy())
1169 One = ConstantExpr::getFPExtend(One, Op->getType());
1171 Module *M = Caller->getParent();
1173 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1174 Op->getType(), B.getInt32Ty(), nullptr);
1175 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1176 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1177 CI->setCallingConv(F->getCallingConv());
1185 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1186 Function *Callee = CI->getCalledFunction();
1188 Value *Ret = nullptr;
1189 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1190 Ret = optimizeUnaryDoubleFP(CI, B, false);
1193 FunctionType *FT = Callee->getFunctionType();
1194 // Make sure this has 1 argument of FP type which matches the result type.
1195 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1196 !FT->getParamType(0)->isFloatingPointTy())
1199 Value *Op = CI->getArgOperand(0);
1200 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1201 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1202 if (I->getOpcode() == Instruction::FMul)
1203 if (I->getOperand(0) == I->getOperand(1))
1209 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1210 // If we can shrink the call to a float function rather than a double
1211 // function, do that first.
1212 Function *Callee = CI->getCalledFunction();
1213 if ((Callee->getName() == "fmin" && TLI->has(LibFunc::fminf)) ||
1214 (Callee->getName() == "fmax" && TLI->has(LibFunc::fmaxf))) {
1215 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1220 // Make sure this has 2 arguments of FP type which match the result type.
1221 FunctionType *FT = Callee->getFunctionType();
1222 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1223 FT->getParamType(0) != FT->getParamType(1) ||
1224 !FT->getParamType(0)->isFloatingPointTy())
1227 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1228 // fast-math flag decorations that are applied to FP instructions. For now,
1229 // we have to rely on the function-level attributes to do this optimization
1230 // because there's no other way to express that the calls can be relaxed.
1231 IRBuilder<>::FastMathFlagGuard Guard(B);
1233 Function *F = CI->getParent()->getParent();
1234 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1235 if (Attr.getValueAsString() == "true") {
1236 // Unsafe algebra sets all fast-math-flags to true.
1237 FMF.setUnsafeAlgebra();
1239 // At a minimum, no-nans-fp-math must be true.
1240 Attr = F->getFnAttribute("no-nans-fp-math");
1241 if (Attr.getValueAsString() != "true")
1243 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1244 // "Ideally, fmax would be sensitive to the sign of zero, for example
1245 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1246 // might be impractical."
1247 FMF.setNoSignedZeros();
1250 B.SetFastMathFlags(FMF);
1252 // We have a relaxed floating-point environment. We can ignore NaN-handling
1253 // and transform to a compare and select. We do not have to consider errno or
1254 // exceptions, because fmin/fmax do not have those.
1255 Value *Op0 = CI->getArgOperand(0);
1256 Value *Op1 = CI->getArgOperand(1);
1257 Value *Cmp = Callee->getName().startswith("fmin") ?
1258 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1259 return B.CreateSelect(Cmp, Op0, Op1);
1262 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1263 Function *Callee = CI->getCalledFunction();
1265 Value *Ret = nullptr;
1266 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1267 Callee->getIntrinsicID() == Intrinsic::sqrt))
1268 Ret = optimizeUnaryDoubleFP(CI, B, true);
1270 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1271 // fast-math flag decorations that are applied to FP instructions. For now,
1272 // we have to rely on the function-level unsafe-fp-math attribute to do this
1273 // optimization because there's no other way to express that the sqrt can be
1275 Function *F = CI->getParent()->getParent();
1276 if (F->hasFnAttribute("unsafe-fp-math")) {
1277 // Check for unsafe-fp-math = true.
1278 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1279 if (Attr.getValueAsString() != "true")
1282 Value *Op = CI->getArgOperand(0);
1283 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1284 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1285 // We're looking for a repeated factor in a multiplication tree,
1286 // so we can do this fold: sqrt(x * x) -> fabs(x);
1287 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1288 Value *Op0 = I->getOperand(0);
1289 Value *Op1 = I->getOperand(1);
1290 Value *RepeatOp = nullptr;
1291 Value *OtherOp = nullptr;
1293 // Simple match: the operands of the multiply are identical.
1296 // Look for a more complicated pattern: one of the operands is itself
1297 // a multiply, so search for a common factor in that multiply.
1298 // Note: We don't bother looking any deeper than this first level or for
1299 // variations of this pattern because instcombine's visitFMUL and/or the
1300 // reassociation pass should give us this form.
1301 Value *OtherMul0, *OtherMul1;
1302 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1303 // Pattern: sqrt((x * y) * z)
1304 if (OtherMul0 == OtherMul1) {
1305 // Matched: sqrt((x * x) * z)
1306 RepeatOp = OtherMul0;
1312 // Fast math flags for any created instructions should match the sqrt
1314 // FIXME: We're not checking the sqrt because it doesn't have
1315 // fast-math-flags (see earlier comment).
1316 IRBuilder<>::FastMathFlagGuard Guard(B);
1317 B.SetFastMathFlags(I->getFastMathFlags());
1318 // If we found a repeated factor, hoist it out of the square root and
1319 // replace it with the fabs of that factor.
1320 Module *M = Callee->getParent();
1321 Type *ArgType = Op->getType();
1322 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1323 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1325 // If we found a non-repeated factor, we still need to get its square
1326 // root. We then multiply that by the value that was simplified out
1327 // of the square root calculation.
1328 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1329 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1330 return B.CreateFMul(FabsCall, SqrtCall);
1339 static bool isTrigLibCall(CallInst *CI);
1340 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1341 bool UseFloat, Value *&Sin, Value *&Cos,
1344 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1346 // Make sure the prototype is as expected, otherwise the rest of the
1347 // function is probably invalid and likely to abort.
1348 if (!isTrigLibCall(CI))
1351 Value *Arg = CI->getArgOperand(0);
1352 SmallVector<CallInst *, 1> SinCalls;
1353 SmallVector<CallInst *, 1> CosCalls;
1354 SmallVector<CallInst *, 1> SinCosCalls;
1356 bool IsFloat = Arg->getType()->isFloatTy();
1358 // Look for all compatible sinpi, cospi and sincospi calls with the same
1359 // argument. If there are enough (in some sense) we can make the
1361 for (User *U : Arg->users())
1362 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1365 // It's only worthwhile if both sinpi and cospi are actually used.
1366 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1369 Value *Sin, *Cos, *SinCos;
1370 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1372 replaceTrigInsts(SinCalls, Sin);
1373 replaceTrigInsts(CosCalls, Cos);
1374 replaceTrigInsts(SinCosCalls, SinCos);
1379 static bool isTrigLibCall(CallInst *CI) {
1380 Function *Callee = CI->getCalledFunction();
1381 FunctionType *FT = Callee->getFunctionType();
1383 // We can only hope to do anything useful if we can ignore things like errno
1384 // and floating-point exceptions.
1385 bool AttributesSafe =
1386 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1388 // Other than that we need float(float) or double(double)
1389 return AttributesSafe && FT->getNumParams() == 1 &&
1390 FT->getReturnType() == FT->getParamType(0) &&
1391 (FT->getParamType(0)->isFloatTy() ||
1392 FT->getParamType(0)->isDoubleTy());
1396 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1397 SmallVectorImpl<CallInst *> &SinCalls,
1398 SmallVectorImpl<CallInst *> &CosCalls,
1399 SmallVectorImpl<CallInst *> &SinCosCalls) {
1400 CallInst *CI = dyn_cast<CallInst>(Val);
1405 Function *Callee = CI->getCalledFunction();
1406 StringRef FuncName = Callee->getName();
1408 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1412 if (Func == LibFunc::sinpif)
1413 SinCalls.push_back(CI);
1414 else if (Func == LibFunc::cospif)
1415 CosCalls.push_back(CI);
1416 else if (Func == LibFunc::sincospif_stret)
1417 SinCosCalls.push_back(CI);
1419 if (Func == LibFunc::sinpi)
1420 SinCalls.push_back(CI);
1421 else if (Func == LibFunc::cospi)
1422 CosCalls.push_back(CI);
1423 else if (Func == LibFunc::sincospi_stret)
1424 SinCosCalls.push_back(CI);
1428 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1430 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1432 replaceAllUsesWith(*I, Res);
1436 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1437 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1438 Type *ArgTy = Arg->getType();
1442 Triple T(OrigCallee->getParent()->getTargetTriple());
1444 Name = "__sincospif_stret";
1446 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1447 // x86_64 can't use {float, float} since that would be returned in both
1448 // xmm0 and xmm1, which isn't what a real struct would do.
1449 ResTy = T.getArch() == Triple::x86_64
1450 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1451 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1453 Name = "__sincospi_stret";
1454 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1457 Module *M = OrigCallee->getParent();
1458 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1459 ResTy, ArgTy, nullptr);
1461 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1462 // If the argument is an instruction, it must dominate all uses so put our
1463 // sincos call there.
1464 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1466 // Otherwise (e.g. for a constant) the beginning of the function is as
1467 // good a place as any.
1468 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1469 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1472 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1474 if (SinCos->getType()->isStructTy()) {
1475 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1476 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1478 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1480 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1485 //===----------------------------------------------------------------------===//
1486 // Integer Library Call Optimizations
1487 //===----------------------------------------------------------------------===//
1489 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1490 Function *Callee = CI->getCalledFunction();
1491 FunctionType *FT = Callee->getFunctionType();
1492 // Just make sure this has 2 arguments of the same FP type, which match the
1494 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1495 !FT->getParamType(0)->isIntegerTy())
1498 Value *Op = CI->getArgOperand(0);
1501 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1502 if (CI->isZero()) // ffs(0) -> 0.
1503 return B.getInt32(0);
1504 // ffs(c) -> cttz(c)+1
1505 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1508 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1509 Type *ArgType = Op->getType();
1511 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1512 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1513 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1514 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1516 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1517 return B.CreateSelect(Cond, V, B.getInt32(0));
1520 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1521 Function *Callee = CI->getCalledFunction();
1522 FunctionType *FT = Callee->getFunctionType();
1523 // We require integer(integer) where the types agree.
1524 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1525 FT->getParamType(0) != FT->getReturnType())
1528 // abs(x) -> x >s -1 ? x : -x
1529 Value *Op = CI->getArgOperand(0);
1531 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1532 Value *Neg = B.CreateNeg(Op, "neg");
1533 return B.CreateSelect(Pos, Op, Neg);
1536 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1537 Function *Callee = CI->getCalledFunction();
1538 FunctionType *FT = Callee->getFunctionType();
1539 // We require integer(i32)
1540 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1541 !FT->getParamType(0)->isIntegerTy(32))
1544 // isdigit(c) -> (c-'0') <u 10
1545 Value *Op = CI->getArgOperand(0);
1546 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1547 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1548 return B.CreateZExt(Op, CI->getType());
1551 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1552 Function *Callee = CI->getCalledFunction();
1553 FunctionType *FT = Callee->getFunctionType();
1554 // We require integer(i32)
1555 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1556 !FT->getParamType(0)->isIntegerTy(32))
1559 // isascii(c) -> c <u 128
1560 Value *Op = CI->getArgOperand(0);
1561 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1562 return B.CreateZExt(Op, CI->getType());
1565 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1566 Function *Callee = CI->getCalledFunction();
1567 FunctionType *FT = Callee->getFunctionType();
1568 // We require i32(i32)
1569 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1570 !FT->getParamType(0)->isIntegerTy(32))
1573 // toascii(c) -> c & 0x7f
1574 return B.CreateAnd(CI->getArgOperand(0),
1575 ConstantInt::get(CI->getType(), 0x7F));
1578 //===----------------------------------------------------------------------===//
1579 // Formatting and IO Library Call Optimizations
1580 //===----------------------------------------------------------------------===//
1582 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1584 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1586 // Error reporting calls should be cold, mark them as such.
1587 // This applies even to non-builtin calls: it is only a hint and applies to
1588 // functions that the frontend might not understand as builtins.
1590 // This heuristic was suggested in:
1591 // Improving Static Branch Prediction in a Compiler
1592 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1593 // Proceedings of PACT'98, Oct. 1998, IEEE
1594 Function *Callee = CI->getCalledFunction();
1596 if (!CI->hasFnAttr(Attribute::Cold) &&
1597 isReportingError(Callee, CI, StreamArg)) {
1598 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1604 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1605 if (!ColdErrorCalls)
1608 if (!Callee || !Callee->isDeclaration())
1614 // These functions might be considered cold, but only if their stream
1615 // argument is stderr.
1617 if (StreamArg >= (int)CI->getNumArgOperands())
1619 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1622 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1623 if (!GV || !GV->isDeclaration())
1625 return GV->getName() == "stderr";
1628 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1629 // Check for a fixed format string.
1630 StringRef FormatStr;
1631 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1634 // Empty format string -> noop.
1635 if (FormatStr.empty()) // Tolerate printf's declared void.
1636 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1638 // Do not do any of the following transformations if the printf return value
1639 // is used, in general the printf return value is not compatible with either
1640 // putchar() or puts().
1641 if (!CI->use_empty())
1644 // printf("x") -> putchar('x'), even for '%'.
1645 if (FormatStr.size() == 1) {
1646 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1647 if (CI->use_empty() || !Res)
1649 return B.CreateIntCast(Res, CI->getType(), true);
1652 // printf("foo\n") --> puts("foo")
1653 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1654 FormatStr.find('%') == StringRef::npos) { // No format characters.
1655 // Create a string literal with no \n on it. We expect the constant merge
1656 // pass to be run after this pass, to merge duplicate strings.
1657 FormatStr = FormatStr.drop_back();
1658 Value *GV = B.CreateGlobalString(FormatStr, "str");
1659 Value *NewCI = EmitPutS(GV, B, TLI);
1660 return (CI->use_empty() || !NewCI)
1662 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1665 // Optimize specific format strings.
1666 // printf("%c", chr) --> putchar(chr)
1667 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1668 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1669 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1671 if (CI->use_empty() || !Res)
1673 return B.CreateIntCast(Res, CI->getType(), true);
1676 // printf("%s\n", str) --> puts(str)
1677 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1678 CI->getArgOperand(1)->getType()->isPointerTy()) {
1679 return EmitPutS(CI->getArgOperand(1), B, TLI);
1684 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1686 Function *Callee = CI->getCalledFunction();
1687 // Require one fixed pointer argument and an integer/void result.
1688 FunctionType *FT = Callee->getFunctionType();
1689 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1690 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1693 if (Value *V = optimizePrintFString(CI, B)) {
1697 // printf(format, ...) -> iprintf(format, ...) if no floating point
1699 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1700 Module *M = B.GetInsertBlock()->getParent()->getParent();
1701 Constant *IPrintFFn =
1702 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1703 CallInst *New = cast<CallInst>(CI->clone());
1704 New->setCalledFunction(IPrintFFn);
1711 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1712 // Check for a fixed format string.
1713 StringRef FormatStr;
1714 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1717 // If we just have a format string (nothing else crazy) transform it.
1718 if (CI->getNumArgOperands() == 2) {
1719 // Make sure there's no % in the constant array. We could try to handle
1720 // %% -> % in the future if we cared.
1721 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1722 if (FormatStr[i] == '%')
1723 return nullptr; // we found a format specifier, bail out.
1725 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1726 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1727 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1728 FormatStr.size() + 1),
1729 1); // Copy the null byte.
1730 return ConstantInt::get(CI->getType(), FormatStr.size());
1733 // The remaining optimizations require the format string to be "%s" or "%c"
1734 // and have an extra operand.
1735 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1736 CI->getNumArgOperands() < 3)
1739 // Decode the second character of the format string.
1740 if (FormatStr[1] == 'c') {
1741 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1742 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1744 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1745 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1746 B.CreateStore(V, Ptr);
1747 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1748 B.CreateStore(B.getInt8(0), Ptr);
1750 return ConstantInt::get(CI->getType(), 1);
1753 if (FormatStr[1] == 's') {
1754 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1755 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1758 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1762 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1763 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1765 // The sprintf result is the unincremented number of bytes in the string.
1766 return B.CreateIntCast(Len, CI->getType(), false);
1771 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1772 Function *Callee = CI->getCalledFunction();
1773 // Require two fixed pointer arguments and an integer result.
1774 FunctionType *FT = Callee->getFunctionType();
1775 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1776 !FT->getParamType(1)->isPointerTy() ||
1777 !FT->getReturnType()->isIntegerTy())
1780 if (Value *V = optimizeSPrintFString(CI, B)) {
1784 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1786 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1787 Module *M = B.GetInsertBlock()->getParent()->getParent();
1788 Constant *SIPrintFFn =
1789 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1790 CallInst *New = cast<CallInst>(CI->clone());
1791 New->setCalledFunction(SIPrintFFn);
1798 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1799 optimizeErrorReporting(CI, B, 0);
1801 // All the optimizations depend on the format string.
1802 StringRef FormatStr;
1803 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1806 // Do not do any of the following transformations if the fprintf return
1807 // value is used, in general the fprintf return value is not compatible
1808 // with fwrite(), fputc() or fputs().
1809 if (!CI->use_empty())
1812 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1813 if (CI->getNumArgOperands() == 2) {
1814 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1815 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1816 return nullptr; // We found a format specifier.
1819 CI->getArgOperand(1),
1820 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1821 CI->getArgOperand(0), B, DL, TLI);
1824 // The remaining optimizations require the format string to be "%s" or "%c"
1825 // and have an extra operand.
1826 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1827 CI->getNumArgOperands() < 3)
1830 // Decode the second character of the format string.
1831 if (FormatStr[1] == 'c') {
1832 // fprintf(F, "%c", chr) --> fputc(chr, F)
1833 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1835 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1838 if (FormatStr[1] == 's') {
1839 // fprintf(F, "%s", str) --> fputs(str, F)
1840 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1842 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1847 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1848 Function *Callee = CI->getCalledFunction();
1849 // Require two fixed paramters as pointers and integer result.
1850 FunctionType *FT = Callee->getFunctionType();
1851 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1852 !FT->getParamType(1)->isPointerTy() ||
1853 !FT->getReturnType()->isIntegerTy())
1856 if (Value *V = optimizeFPrintFString(CI, B)) {
1860 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1861 // floating point arguments.
1862 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1863 Module *M = B.GetInsertBlock()->getParent()->getParent();
1864 Constant *FIPrintFFn =
1865 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1866 CallInst *New = cast<CallInst>(CI->clone());
1867 New->setCalledFunction(FIPrintFFn);
1874 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1875 optimizeErrorReporting(CI, B, 3);
1877 Function *Callee = CI->getCalledFunction();
1878 // Require a pointer, an integer, an integer, a pointer, returning integer.
1879 FunctionType *FT = Callee->getFunctionType();
1880 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1881 !FT->getParamType(1)->isIntegerTy() ||
1882 !FT->getParamType(2)->isIntegerTy() ||
1883 !FT->getParamType(3)->isPointerTy() ||
1884 !FT->getReturnType()->isIntegerTy())
1887 // Get the element size and count.
1888 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1889 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1890 if (!SizeC || !CountC)
1892 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1894 // If this is writing zero records, remove the call (it's a noop).
1896 return ConstantInt::get(CI->getType(), 0);
1898 // If this is writing one byte, turn it into fputc.
1899 // This optimisation is only valid, if the return value is unused.
1900 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1901 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1902 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1903 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1909 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1910 optimizeErrorReporting(CI, B, 1);
1912 Function *Callee = CI->getCalledFunction();
1914 // Require two pointers. Also, we can't optimize if return value is used.
1915 FunctionType *FT = Callee->getFunctionType();
1916 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1917 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1920 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1921 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1925 // Known to have no uses (see above).
1927 CI->getArgOperand(0),
1928 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
1929 CI->getArgOperand(1), B, DL, TLI);
1932 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1933 Function *Callee = CI->getCalledFunction();
1934 // Require one fixed pointer argument and an integer/void result.
1935 FunctionType *FT = Callee->getFunctionType();
1936 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1937 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1940 // Check for a constant string.
1942 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1945 if (Str.empty() && CI->use_empty()) {
1946 // puts("") -> putchar('\n')
1947 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
1948 if (CI->use_empty() || !Res)
1950 return B.CreateIntCast(Res, CI->getType(), true);
1956 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1958 SmallString<20> FloatFuncName = FuncName;
1959 FloatFuncName += 'f';
1960 if (TLI->getLibFunc(FloatFuncName, Func))
1961 return TLI->has(Func);
1965 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1966 IRBuilder<> &Builder) {
1968 Function *Callee = CI->getCalledFunction();
1969 StringRef FuncName = Callee->getName();
1971 // Check for string/memory library functions.
1972 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1973 // Make sure we never change the calling convention.
1974 assert((ignoreCallingConv(Func) ||
1975 CI->getCallingConv() == llvm::CallingConv::C) &&
1976 "Optimizing string/memory libcall would change the calling convention");
1978 case LibFunc::strcat:
1979 return optimizeStrCat(CI, Builder);
1980 case LibFunc::strncat:
1981 return optimizeStrNCat(CI, Builder);
1982 case LibFunc::strchr:
1983 return optimizeStrChr(CI, Builder);
1984 case LibFunc::strrchr:
1985 return optimizeStrRChr(CI, Builder);
1986 case LibFunc::strcmp:
1987 return optimizeStrCmp(CI, Builder);
1988 case LibFunc::strncmp:
1989 return optimizeStrNCmp(CI, Builder);
1990 case LibFunc::strcpy:
1991 return optimizeStrCpy(CI, Builder);
1992 case LibFunc::stpcpy:
1993 return optimizeStpCpy(CI, Builder);
1994 case LibFunc::strncpy:
1995 return optimizeStrNCpy(CI, Builder);
1996 case LibFunc::strlen:
1997 return optimizeStrLen(CI, Builder);
1998 case LibFunc::strpbrk:
1999 return optimizeStrPBrk(CI, Builder);
2000 case LibFunc::strtol:
2001 case LibFunc::strtod:
2002 case LibFunc::strtof:
2003 case LibFunc::strtoul:
2004 case LibFunc::strtoll:
2005 case LibFunc::strtold:
2006 case LibFunc::strtoull:
2007 return optimizeStrTo(CI, Builder);
2008 case LibFunc::strspn:
2009 return optimizeStrSpn(CI, Builder);
2010 case LibFunc::strcspn:
2011 return optimizeStrCSpn(CI, Builder);
2012 case LibFunc::strstr:
2013 return optimizeStrStr(CI, Builder);
2014 case LibFunc::memchr:
2015 return optimizeMemChr(CI, Builder);
2016 case LibFunc::memcmp:
2017 return optimizeMemCmp(CI, Builder);
2018 case LibFunc::memcpy:
2019 return optimizeMemCpy(CI, Builder);
2020 case LibFunc::memmove:
2021 return optimizeMemMove(CI, Builder);
2022 case LibFunc::memset:
2023 return optimizeMemSet(CI, Builder);
2031 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2032 if (CI->isNoBuiltin())
2036 Function *Callee = CI->getCalledFunction();
2037 StringRef FuncName = Callee->getName();
2038 IRBuilder<> Builder(CI);
2039 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2041 // Command-line parameter overrides function attribute.
2042 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2043 UnsafeFPShrink = EnableUnsafeFPShrink;
2044 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2045 // FIXME: This is the same problem as described in optimizeSqrt().
2046 // If calls gain access to IR-level FMF, then use that instead of a
2047 // function attribute.
2049 // Check for unsafe-fp-math = true.
2050 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2051 if (Attr.getValueAsString() == "true")
2052 UnsafeFPShrink = true;
2055 // First, check for intrinsics.
2056 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2057 if (!isCallingConvC)
2059 switch (II->getIntrinsicID()) {
2060 case Intrinsic::pow:
2061 return optimizePow(CI, Builder);
2062 case Intrinsic::exp2:
2063 return optimizeExp2(CI, Builder);
2064 case Intrinsic::fabs:
2065 return optimizeFabs(CI, Builder);
2066 case Intrinsic::sqrt:
2067 return optimizeSqrt(CI, Builder);
2073 // Also try to simplify calls to fortified library functions.
2074 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2075 // Try to further simplify the result.
2076 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2077 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2078 // Use an IR Builder from SimplifiedCI if available instead of CI
2079 // to guarantee we reach all uses we might replace later on.
2080 IRBuilder<> TmpBuilder(SimplifiedCI);
2081 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2082 // If we were able to further simplify, remove the now redundant call.
2083 SimplifiedCI->replaceAllUsesWith(V);
2084 SimplifiedCI->eraseFromParent();
2088 return SimplifiedFortifiedCI;
2091 // Then check for known library functions.
2092 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2093 // We never change the calling convention.
2094 if (!ignoreCallingConv(Func) && !isCallingConvC)
2096 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2102 return optimizeCos(CI, Builder);
2103 case LibFunc::sinpif:
2104 case LibFunc::sinpi:
2105 case LibFunc::cospif:
2106 case LibFunc::cospi:
2107 return optimizeSinCosPi(CI, Builder);
2111 return optimizePow(CI, Builder);
2112 case LibFunc::exp2l:
2114 case LibFunc::exp2f:
2115 return optimizeExp2(CI, Builder);
2116 case LibFunc::fabsf:
2118 case LibFunc::fabsl:
2119 return optimizeFabs(CI, Builder);
2120 case LibFunc::sqrtf:
2122 case LibFunc::sqrtl:
2123 return optimizeSqrt(CI, Builder);
2126 case LibFunc::ffsll:
2127 return optimizeFFS(CI, Builder);
2130 case LibFunc::llabs:
2131 return optimizeAbs(CI, Builder);
2132 case LibFunc::isdigit:
2133 return optimizeIsDigit(CI, Builder);
2134 case LibFunc::isascii:
2135 return optimizeIsAscii(CI, Builder);
2136 case LibFunc::toascii:
2137 return optimizeToAscii(CI, Builder);
2138 case LibFunc::printf:
2139 return optimizePrintF(CI, Builder);
2140 case LibFunc::sprintf:
2141 return optimizeSPrintF(CI, Builder);
2142 case LibFunc::fprintf:
2143 return optimizeFPrintF(CI, Builder);
2144 case LibFunc::fwrite:
2145 return optimizeFWrite(CI, Builder);
2146 case LibFunc::fputs:
2147 return optimizeFPuts(CI, Builder);
2149 return optimizePuts(CI, Builder);
2150 case LibFunc::perror:
2151 return optimizeErrorReporting(CI, Builder);
2152 case LibFunc::vfprintf:
2153 case LibFunc::fiprintf:
2154 return optimizeErrorReporting(CI, Builder, 0);
2155 case LibFunc::fputc:
2156 return optimizeErrorReporting(CI, Builder, 1);
2158 case LibFunc::floor:
2160 case LibFunc::round:
2161 case LibFunc::nearbyint:
2162 case LibFunc::trunc:
2163 if (hasFloatVersion(FuncName))
2164 return optimizeUnaryDoubleFP(CI, Builder, false);
2167 case LibFunc::acosh:
2169 case LibFunc::asinh:
2171 case LibFunc::atanh:
2175 case LibFunc::exp10:
2176 case LibFunc::expm1:
2178 case LibFunc::log10:
2179 case LibFunc::log1p:
2186 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2187 return optimizeUnaryDoubleFP(CI, Builder, true);
2189 case LibFunc::copysign:
2190 if (hasFloatVersion(FuncName))
2191 return optimizeBinaryDoubleFP(CI, Builder);
2193 case LibFunc::fminf:
2195 case LibFunc::fminl:
2196 case LibFunc::fmaxf:
2198 case LibFunc::fmaxl:
2199 return optimizeFMinFMax(CI, Builder);
2207 LibCallSimplifier::LibCallSimplifier(
2208 const DataLayout &DL, const TargetLibraryInfo *TLI,
2209 function_ref<void(Instruction *, Value *)> Replacer)
2210 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2211 Replacer(Replacer) {}
2213 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2214 // Indirect through the replacer used in this instance.
2218 /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2220 I->replaceAllUsesWith(With);
2221 I->eraseFromParent();
2225 // Additional cases that we need to add to this file:
2228 // * cbrt(expN(X)) -> expN(x/3)
2229 // * cbrt(sqrt(x)) -> pow(x,1/6)
2230 // * cbrt(cbrt(x)) -> pow(x,1/9)
2233 // * exp(log(x)) -> x
2236 // * log(exp(x)) -> x
2237 // * log(x**y) -> y*log(x)
2238 // * log(exp(y)) -> y*log(e)
2239 // * log(exp2(y)) -> y*log(2)
2240 // * log(exp10(y)) -> y*log(10)
2241 // * log(sqrt(x)) -> 0.5*log(x)
2242 // * log(pow(x,y)) -> y*log(x)
2244 // lround, lroundf, lroundl:
2245 // * lround(cnst) -> cnst'
2248 // * pow(exp(x),y) -> exp(x*y)
2249 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2250 // * pow(pow(x,y),z)-> pow(x,y*z)
2252 // round, roundf, roundl:
2253 // * round(cnst) -> cnst'
2256 // * signbit(cnst) -> cnst'
2257 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2259 // sqrt, sqrtf, sqrtl:
2260 // * sqrt(expN(x)) -> expN(x*0.5)
2261 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2262 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2265 // * tan(atan(x)) -> x
2267 // trunc, truncf, truncl:
2268 // * trunc(cnst) -> cnst'
2272 //===----------------------------------------------------------------------===//
2273 // Fortified Library Call Optimizations
2274 //===----------------------------------------------------------------------===//
2276 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2280 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2282 if (ConstantInt *ObjSizeCI =
2283 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2284 if (ObjSizeCI->isAllOnesValue())
2286 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2287 if (OnlyLowerUnknownSize)
2290 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2291 // If the length is 0 we don't know how long it is and so we can't
2292 // remove the check.
2295 return ObjSizeCI->getZExtValue() >= Len;
2297 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2298 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2303 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2304 Function *Callee = CI->getCalledFunction();
2306 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2309 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2310 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2311 CI->getArgOperand(2), 1);
2312 return CI->getArgOperand(0);
2317 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2318 Function *Callee = CI->getCalledFunction();
2320 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2323 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2324 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2325 CI->getArgOperand(2), 1);
2326 return CI->getArgOperand(0);
2331 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2332 Function *Callee = CI->getCalledFunction();
2334 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2337 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2338 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2339 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2340 return CI->getArgOperand(0);
2345 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2347 LibFunc::Func Func) {
2348 Function *Callee = CI->getCalledFunction();
2349 StringRef Name = Callee->getName();
2350 const DataLayout &DL = CI->getModule()->getDataLayout();
2352 if (!checkStringCopyLibFuncSignature(Callee, Func))
2355 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2356 *ObjSize = CI->getArgOperand(2);
2358 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2359 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2360 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2361 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2364 // If a) we don't have any length information, or b) we know this will
2365 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2366 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2367 // TODO: It might be nice to get a maximum length out of the possible
2368 // string lengths for varying.
2369 if (isFortifiedCallFoldable(CI, 2, 1, true))
2370 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2372 if (OnlyLowerUnknownSize)
2375 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2376 uint64_t Len = GetStringLength(Src);
2380 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2381 Value *LenV = ConstantInt::get(SizeTTy, Len);
2382 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2383 // If the function was an __stpcpy_chk, and we were able to fold it into
2384 // a __memcpy_chk, we still need to return the correct end pointer.
2385 if (Ret && Func == LibFunc::stpcpy_chk)
2386 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2390 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2392 LibFunc::Func Func) {
2393 Function *Callee = CI->getCalledFunction();
2394 StringRef Name = Callee->getName();
2396 if (!checkStringCopyLibFuncSignature(Callee, Func))
2398 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2399 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2400 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2406 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2407 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2408 // Some clang users checked for _chk libcall availability using:
2409 // __has_builtin(__builtin___memcpy_chk)
2410 // When compiling with -fno-builtin, this is always true.
2411 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2412 // end up with fortified libcalls, which isn't acceptable in a freestanding
2413 // environment which only provides their non-fortified counterparts.
2415 // Until we change clang and/or teach external users to check for availability
2416 // differently, disregard the "nobuiltin" attribute and TLI::has.
2421 Function *Callee = CI->getCalledFunction();
2422 StringRef FuncName = Callee->getName();
2423 IRBuilder<> Builder(CI);
2424 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2426 // First, check that this is a known library functions.
2427 if (!TLI->getLibFunc(FuncName, Func))
2430 // We never change the calling convention.
2431 if (!ignoreCallingConv(Func) && !isCallingConvC)
2435 case LibFunc::memcpy_chk:
2436 return optimizeMemCpyChk(CI, Builder);
2437 case LibFunc::memmove_chk:
2438 return optimizeMemMoveChk(CI, Builder);
2439 case LibFunc::memset_chk:
2440 return optimizeMemSetChk(CI, Builder);
2441 case LibFunc::stpcpy_chk:
2442 case LibFunc::strcpy_chk:
2443 return optimizeStrpCpyChk(CI, Builder, Func);
2444 case LibFunc::stpncpy_chk:
2445 case LibFunc::strncpy_chk:
2446 return optimizeStrpNCpyChk(CI, Builder, Func);
2453 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2454 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2455 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}