1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification. If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/Transforms/Utils/Local.h"
38 using namespace PatternMatch;
41 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static bool ignoreCallingConv(LibFunc::Func Func) {
56 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
60 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
61 /// value is equal or not-equal to zero.
62 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
63 for (User *U : V->users()) {
64 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
66 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
69 // Unknown instruction.
75 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
76 /// comparisons with With.
77 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
78 for (User *U : V->users()) {
79 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
80 if (IC->isEquality() && IC->getOperand(1) == With)
82 // Unknown instruction.
88 static bool callHasFloatingPointArgument(const CallInst *CI) {
89 return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
90 return OI->getType()->isFloatingPointTy();
94 /// \brief Check whether the overloaded unary floating point function
95 /// corresponding to \a Ty is available.
96 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
97 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
98 LibFunc::Func LongDoubleFn) {
99 switch (Ty->getTypeID()) {
100 case Type::FloatTyID:
101 return TLI->has(FloatFn);
102 case Type::DoubleTyID:
103 return TLI->has(DoubleFn);
105 return TLI->has(LongDoubleFn);
109 /// \brief Check whether we can use unsafe floating point math for
110 /// the function passed as input.
111 static bool canUseUnsafeFPMath(Function *F) {
113 // FIXME: For finer-grain optimization, we need intrinsics to have the same
114 // fast-math flag decorations that are applied to FP instructions. For now,
115 // we have to rely on the function-level unsafe-fp-math attribute to do this
116 // optimization because there's no other way to express that the call can be
118 if (F->hasFnAttribute("unsafe-fp-math")) {
119 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
120 if (Attr.getValueAsString() == "true")
126 /// \brief Returns whether \p F matches the signature expected for the
127 /// string/memory copying library function \p Func.
128 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
129 /// Their fortified (_chk) counterparts are also accepted.
130 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
131 const DataLayout &DL = F->getParent()->getDataLayout();
132 FunctionType *FT = F->getFunctionType();
133 LLVMContext &Context = F->getContext();
134 Type *PCharTy = Type::getInt8PtrTy(Context);
135 Type *SizeTTy = DL.getIntPtrType(Context);
136 unsigned NumParams = FT->getNumParams();
138 // All string libfuncs return the same type as the first parameter.
139 if (FT->getReturnType() != FT->getParamType(0))
144 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
145 case LibFunc::stpncpy_chk:
146 case LibFunc::strncpy_chk:
147 --NumParams; // fallthrough
148 case LibFunc::stpncpy:
149 case LibFunc::strncpy: {
150 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
151 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
155 case LibFunc::strcpy_chk:
156 case LibFunc::stpcpy_chk:
157 --NumParams; // fallthrough
158 case LibFunc::stpcpy:
159 case LibFunc::strcpy: {
160 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
161 FT->getParamType(0) != PCharTy)
165 case LibFunc::memmove_chk:
166 case LibFunc::memcpy_chk:
167 --NumParams; // fallthrough
168 case LibFunc::memmove:
169 case LibFunc::memcpy: {
170 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
171 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
175 case LibFunc::memset_chk:
176 --NumParams; // fallthrough
177 case LibFunc::memset: {
178 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
179 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
184 // If this is a fortified libcall, the last parameter is a size_t.
185 if (NumParams == FT->getNumParams() - 1)
186 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
190 //===----------------------------------------------------------------------===//
191 // String and Memory Library Call Optimizations
192 //===----------------------------------------------------------------------===//
194 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
195 Function *Callee = CI->getCalledFunction();
196 // Verify the "strcat" function prototype.
197 FunctionType *FT = Callee->getFunctionType();
198 if (FT->getNumParams() != 2||
199 FT->getReturnType() != B.getInt8PtrTy() ||
200 FT->getParamType(0) != FT->getReturnType() ||
201 FT->getParamType(1) != FT->getReturnType())
204 // Extract some information from the instruction
205 Value *Dst = CI->getArgOperand(0);
206 Value *Src = CI->getArgOperand(1);
208 // See if we can get the length of the input string.
209 uint64_t Len = GetStringLength(Src);
212 --Len; // Unbias length.
214 // Handle the simple, do-nothing case: strcat(x, "") -> x
218 return emitStrLenMemCpy(Src, Dst, Len, B);
221 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
223 // We need to find the end of the destination string. That's where the
224 // memory is to be moved to. We just generate a call to strlen.
225 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
229 // Now that we have the destination's length, we must index into the
230 // destination's pointer to get the actual memcpy destination (end of
231 // the string .. we're concatenating).
232 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
234 // We have enough information to now generate the memcpy call to do the
235 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
236 B.CreateMemCpy(CpyDst, Src,
237 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
242 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
243 Function *Callee = CI->getCalledFunction();
244 // Verify the "strncat" function prototype.
245 FunctionType *FT = Callee->getFunctionType();
246 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
247 FT->getParamType(0) != FT->getReturnType() ||
248 FT->getParamType(1) != FT->getReturnType() ||
249 !FT->getParamType(2)->isIntegerTy())
252 // Extract some information from the instruction
253 Value *Dst = CI->getArgOperand(0);
254 Value *Src = CI->getArgOperand(1);
257 // We don't do anything if length is not constant
258 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
259 Len = LengthArg->getZExtValue();
263 // See if we can get the length of the input string.
264 uint64_t SrcLen = GetStringLength(Src);
267 --SrcLen; // Unbias length.
269 // Handle the simple, do-nothing cases:
270 // strncat(x, "", c) -> x
271 // strncat(x, c, 0) -> x
272 if (SrcLen == 0 || Len == 0)
275 // We don't optimize this case
279 // strncat(x, s, c) -> strcat(x, s)
280 // s is constant so the strcat can be optimized further
281 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
284 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
285 Function *Callee = CI->getCalledFunction();
286 // Verify the "strchr" function prototype.
287 FunctionType *FT = Callee->getFunctionType();
288 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
289 FT->getParamType(0) != FT->getReturnType() ||
290 !FT->getParamType(1)->isIntegerTy(32))
293 Value *SrcStr = CI->getArgOperand(0);
295 // If the second operand is non-constant, see if we can compute the length
296 // of the input string and turn this into memchr.
297 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
299 uint64_t Len = GetStringLength(SrcStr);
300 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
303 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
304 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
308 // Otherwise, the character is a constant, see if the first argument is
309 // a string literal. If so, we can constant fold.
311 if (!getConstantStringInfo(SrcStr, Str)) {
312 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
313 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
317 // Compute the offset, make sure to handle the case when we're searching for
318 // zero (a weird way to spell strlen).
319 size_t I = (0xFF & CharC->getSExtValue()) == 0
321 : Str.find(CharC->getSExtValue());
322 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
323 return Constant::getNullValue(CI->getType());
325 // strchr(s+n,c) -> gep(s+n+i,c)
326 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
329 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
330 Function *Callee = CI->getCalledFunction();
331 // Verify the "strrchr" function prototype.
332 FunctionType *FT = Callee->getFunctionType();
333 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
334 FT->getParamType(0) != FT->getReturnType() ||
335 !FT->getParamType(1)->isIntegerTy(32))
338 Value *SrcStr = CI->getArgOperand(0);
339 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
341 // Cannot fold anything if we're not looking for a constant.
346 if (!getConstantStringInfo(SrcStr, Str)) {
347 // strrchr(s, 0) -> strchr(s, 0)
349 return EmitStrChr(SrcStr, '\0', B, TLI);
353 // Compute the offset.
354 size_t I = (0xFF & CharC->getSExtValue()) == 0
356 : Str.rfind(CharC->getSExtValue());
357 if (I == StringRef::npos) // Didn't find the char. Return null.
358 return Constant::getNullValue(CI->getType());
360 // strrchr(s+n,c) -> gep(s+n+i,c)
361 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
364 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
365 Function *Callee = CI->getCalledFunction();
366 // Verify the "strcmp" function prototype.
367 FunctionType *FT = Callee->getFunctionType();
368 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
369 FT->getParamType(0) != FT->getParamType(1) ||
370 FT->getParamType(0) != B.getInt8PtrTy())
373 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
374 if (Str1P == Str2P) // strcmp(x,x) -> 0
375 return ConstantInt::get(CI->getType(), 0);
377 StringRef Str1, Str2;
378 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
379 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
381 // strcmp(x, y) -> cnst (if both x and y are constant strings)
382 if (HasStr1 && HasStr2)
383 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
385 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
387 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
389 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
390 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
392 // strcmp(P, "x") -> memcmp(P, "x", 2)
393 uint64_t Len1 = GetStringLength(Str1P);
394 uint64_t Len2 = GetStringLength(Str2P);
396 return EmitMemCmp(Str1P, Str2P,
397 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
398 std::min(Len1, Len2)),
405 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
406 Function *Callee = CI->getCalledFunction();
407 // Verify the "strncmp" function prototype.
408 FunctionType *FT = Callee->getFunctionType();
409 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
410 FT->getParamType(0) != FT->getParamType(1) ||
411 FT->getParamType(0) != B.getInt8PtrTy() ||
412 !FT->getParamType(2)->isIntegerTy())
415 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
416 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
417 return ConstantInt::get(CI->getType(), 0);
419 // Get the length argument if it is constant.
421 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
422 Length = LengthArg->getZExtValue();
426 if (Length == 0) // strncmp(x,y,0) -> 0
427 return ConstantInt::get(CI->getType(), 0);
429 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
430 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
432 StringRef Str1, Str2;
433 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
434 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
436 // strncmp(x, y) -> cnst (if both x and y are constant strings)
437 if (HasStr1 && HasStr2) {
438 StringRef SubStr1 = Str1.substr(0, Length);
439 StringRef SubStr2 = Str2.substr(0, Length);
440 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
443 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
445 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
447 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
448 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
453 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
454 Function *Callee = CI->getCalledFunction();
456 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
459 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
460 if (Dst == Src) // strcpy(x,x) -> x
463 // See if we can get the length of the input string.
464 uint64_t Len = GetStringLength(Src);
468 // We have enough information to now generate the memcpy call to do the
469 // copy for us. Make a memcpy to copy the nul byte with align = 1.
470 B.CreateMemCpy(Dst, Src,
471 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
475 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
476 Function *Callee = CI->getCalledFunction();
477 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
480 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
481 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
482 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
483 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
486 // See if we can get the length of the input string.
487 uint64_t Len = GetStringLength(Src);
491 Type *PT = Callee->getFunctionType()->getParamType(0);
492 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
494 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
496 // We have enough information to now generate the memcpy call to do the
497 // copy for us. Make a memcpy to copy the nul byte with align = 1.
498 B.CreateMemCpy(Dst, Src, LenV, 1);
502 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
503 Function *Callee = CI->getCalledFunction();
504 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
507 Value *Dst = CI->getArgOperand(0);
508 Value *Src = CI->getArgOperand(1);
509 Value *LenOp = CI->getArgOperand(2);
511 // See if we can get the length of the input string.
512 uint64_t SrcLen = GetStringLength(Src);
518 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
519 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
524 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
525 Len = LengthArg->getZExtValue();
530 return Dst; // strncpy(x, y, 0) -> x
532 // Let strncpy handle the zero padding
533 if (Len > SrcLen + 1)
536 Type *PT = Callee->getFunctionType()->getParamType(0);
537 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
538 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
543 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
544 Function *Callee = CI->getCalledFunction();
545 FunctionType *FT = Callee->getFunctionType();
546 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
547 !FT->getReturnType()->isIntegerTy())
550 Value *Src = CI->getArgOperand(0);
552 // Constant folding: strlen("xyz") -> 3
553 if (uint64_t Len = GetStringLength(Src))
554 return ConstantInt::get(CI->getType(), Len - 1);
556 // strlen(x?"foo":"bars") --> x ? 3 : 4
557 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
558 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
559 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
560 if (LenTrue && LenFalse) {
561 Function *Caller = CI->getParent()->getParent();
562 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
564 "folded strlen(select) to select of constants");
565 return B.CreateSelect(SI->getCondition(),
566 ConstantInt::get(CI->getType(), LenTrue - 1),
567 ConstantInt::get(CI->getType(), LenFalse - 1));
571 // strlen(x) != 0 --> *x != 0
572 // strlen(x) == 0 --> *x == 0
573 if (isOnlyUsedInZeroEqualityComparison(CI))
574 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
579 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
580 Function *Callee = CI->getCalledFunction();
581 FunctionType *FT = Callee->getFunctionType();
582 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
583 FT->getParamType(1) != FT->getParamType(0) ||
584 FT->getReturnType() != FT->getParamType(0))
588 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
589 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
591 // strpbrk(s, "") -> nullptr
592 // strpbrk("", s) -> nullptr
593 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
594 return Constant::getNullValue(CI->getType());
597 if (HasS1 && HasS2) {
598 size_t I = S1.find_first_of(S2);
599 if (I == StringRef::npos) // No match.
600 return Constant::getNullValue(CI->getType());
602 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
605 // strpbrk(s, "a") -> strchr(s, 'a')
606 if (HasS2 && S2.size() == 1)
607 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
612 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
613 Function *Callee = CI->getCalledFunction();
614 FunctionType *FT = Callee->getFunctionType();
615 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
616 !FT->getParamType(0)->isPointerTy() ||
617 !FT->getParamType(1)->isPointerTy())
620 Value *EndPtr = CI->getArgOperand(1);
621 if (isa<ConstantPointerNull>(EndPtr)) {
622 // With a null EndPtr, this function won't capture the main argument.
623 // It would be readonly too, except that it still may write to errno.
624 CI->addAttribute(1, Attribute::NoCapture);
630 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
631 Function *Callee = CI->getCalledFunction();
632 FunctionType *FT = Callee->getFunctionType();
633 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
634 FT->getParamType(1) != FT->getParamType(0) ||
635 !FT->getReturnType()->isIntegerTy())
639 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
640 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
642 // strspn(s, "") -> 0
643 // strspn("", s) -> 0
644 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
645 return Constant::getNullValue(CI->getType());
648 if (HasS1 && HasS2) {
649 size_t Pos = S1.find_first_not_of(S2);
650 if (Pos == StringRef::npos)
652 return ConstantInt::get(CI->getType(), Pos);
658 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
659 Function *Callee = CI->getCalledFunction();
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
662 FT->getParamType(1) != FT->getParamType(0) ||
663 !FT->getReturnType()->isIntegerTy())
667 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
668 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
670 // strcspn("", s) -> 0
671 if (HasS1 && S1.empty())
672 return Constant::getNullValue(CI->getType());
675 if (HasS1 && HasS2) {
676 size_t Pos = S1.find_first_of(S2);
677 if (Pos == StringRef::npos)
679 return ConstantInt::get(CI->getType(), Pos);
682 // strcspn(s, "") -> strlen(s)
683 if (HasS2 && S2.empty())
684 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
689 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
690 Function *Callee = CI->getCalledFunction();
691 FunctionType *FT = Callee->getFunctionType();
692 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
693 !FT->getParamType(1)->isPointerTy() ||
694 !FT->getReturnType()->isPointerTy())
697 // fold strstr(x, x) -> x.
698 if (CI->getArgOperand(0) == CI->getArgOperand(1))
699 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
701 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
702 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
703 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
706 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
710 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
711 ICmpInst *Old = cast<ICmpInst>(*UI++);
713 B.CreateICmp(Old->getPredicate(), StrNCmp,
714 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
715 replaceAllUsesWith(Old, Cmp);
720 // See if either input string is a constant string.
721 StringRef SearchStr, ToFindStr;
722 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
723 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
725 // fold strstr(x, "") -> x.
726 if (HasStr2 && ToFindStr.empty())
727 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
729 // If both strings are known, constant fold it.
730 if (HasStr1 && HasStr2) {
731 size_t Offset = SearchStr.find(ToFindStr);
733 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
734 return Constant::getNullValue(CI->getType());
736 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
737 Value *Result = CastToCStr(CI->getArgOperand(0), B);
738 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
739 return B.CreateBitCast(Result, CI->getType());
742 // fold strstr(x, "y") -> strchr(x, 'y').
743 if (HasStr2 && ToFindStr.size() == 1) {
744 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
745 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
750 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
751 Function *Callee = CI->getCalledFunction();
752 FunctionType *FT = Callee->getFunctionType();
753 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
754 !FT->getParamType(1)->isIntegerTy(32) ||
755 !FT->getParamType(2)->isIntegerTy() ||
756 !FT->getReturnType()->isPointerTy())
759 Value *SrcStr = CI->getArgOperand(0);
760 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
761 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
763 // memchr(x, y, 0) -> null
764 if (LenC && LenC->isNullValue())
765 return Constant::getNullValue(CI->getType());
767 // From now on we need at least constant length and string.
769 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
772 // Truncate the string to LenC. If Str is smaller than LenC we will still only
773 // scan the string, as reading past the end of it is undefined and we can just
774 // return null if we don't find the char.
775 Str = Str.substr(0, LenC->getZExtValue());
777 // If the char is variable but the input str and length are not we can turn
778 // this memchr call into a simple bit field test. Of course this only works
779 // when the return value is only checked against null.
781 // It would be really nice to reuse switch lowering here but we can't change
782 // the CFG at this point.
784 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
785 // after bounds check.
786 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
788 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
789 reinterpret_cast<const unsigned char *>(Str.end()));
791 // Make sure the bit field we're about to create fits in a register on the
793 // FIXME: On a 64 bit architecture this prevents us from using the
794 // interesting range of alpha ascii chars. We could do better by emitting
795 // two bitfields or shifting the range by 64 if no lower chars are used.
796 if (!DL.fitsInLegalInteger(Max + 1))
799 // For the bit field use a power-of-2 type with at least 8 bits to avoid
800 // creating unnecessary illegal types.
801 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
803 // Now build the bit field.
804 APInt Bitfield(Width, 0);
806 Bitfield.setBit((unsigned char)C);
807 Value *BitfieldC = B.getInt(Bitfield);
809 // First check that the bit field access is within bounds.
810 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
811 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
814 // Create code that checks if the given bit is set in the field.
815 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
816 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
818 // Finally merge both checks and cast to pointer type. The inttoptr
819 // implicitly zexts the i1 to intptr type.
820 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
823 // Check if all arguments are constants. If so, we can constant fold.
827 // Compute the offset.
828 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
829 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
830 return Constant::getNullValue(CI->getType());
832 // memchr(s+n,c,l) -> gep(s+n+i,c)
833 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
836 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
837 Function *Callee = CI->getCalledFunction();
838 FunctionType *FT = Callee->getFunctionType();
839 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
840 !FT->getParamType(1)->isPointerTy() ||
841 !FT->getReturnType()->isIntegerTy(32))
844 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
846 if (LHS == RHS) // memcmp(s,s,x) -> 0
847 return Constant::getNullValue(CI->getType());
849 // Make sure we have a constant length.
850 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
853 uint64_t Len = LenC->getZExtValue();
855 if (Len == 0) // memcmp(s1,s2,0) -> 0
856 return Constant::getNullValue(CI->getType());
858 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
860 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
861 CI->getType(), "lhsv");
862 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
863 CI->getType(), "rhsv");
864 return B.CreateSub(LHSV, RHSV, "chardiff");
867 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
868 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
870 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
871 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
873 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
874 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
877 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
879 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
881 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
882 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
884 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
888 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
889 StringRef LHSStr, RHSStr;
890 if (getConstantStringInfo(LHS, LHSStr) &&
891 getConstantStringInfo(RHS, RHSStr)) {
892 // Make sure we're not reading out-of-bounds memory.
893 if (Len > LHSStr.size() || Len > RHSStr.size())
895 // Fold the memcmp and normalize the result. This way we get consistent
896 // results across multiple platforms.
898 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
903 return ConstantInt::get(CI->getType(), Ret);
909 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
910 Function *Callee = CI->getCalledFunction();
912 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
915 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
916 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
917 CI->getArgOperand(2), 1);
918 return CI->getArgOperand(0);
921 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
922 Function *Callee = CI->getCalledFunction();
924 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
927 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
928 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
929 CI->getArgOperand(2), 1);
930 return CI->getArgOperand(0);
933 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
934 Function *Callee = CI->getCalledFunction();
936 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
939 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
940 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
941 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
942 return CI->getArgOperand(0);
945 //===----------------------------------------------------------------------===//
946 // Math Library Optimizations
947 //===----------------------------------------------------------------------===//
949 /// Return a variant of Val with float type.
950 /// Currently this works in two cases: If Val is an FPExtension of a float
951 /// value to something bigger, simply return the operand.
952 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
953 /// loss of precision do so.
954 static Value *valueHasFloatPrecision(Value *Val) {
955 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
956 Value *Op = Cast->getOperand(0);
957 if (Op->getType()->isFloatTy())
960 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
961 APFloat F = Const->getValueAPF();
963 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
966 return ConstantFP::get(Const->getContext(), F);
971 //===----------------------------------------------------------------------===//
972 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
974 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
976 Function *Callee = CI->getCalledFunction();
977 FunctionType *FT = Callee->getFunctionType();
978 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
979 !FT->getParamType(0)->isDoubleTy())
983 // Check if all the uses for function like 'sin' are converted to float.
984 for (User *U : CI->users()) {
985 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
986 if (!Cast || !Cast->getType()->isFloatTy())
991 // If this is something like 'floor((double)floatval)', convert to floorf.
992 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
996 // floor((double)floatval) -> (double)floorf(floatval)
997 if (Callee->isIntrinsic()) {
998 Module *M = CI->getParent()->getParent()->getParent();
999 Intrinsic::ID IID = Callee->getIntrinsicID();
1000 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1001 V = B.CreateCall(F, V);
1003 // The call is a library call rather than an intrinsic.
1004 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1007 return B.CreateFPExt(V, B.getDoubleTy());
1010 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1011 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1012 Function *Callee = CI->getCalledFunction();
1013 FunctionType *FT = Callee->getFunctionType();
1014 // Just make sure this has 2 arguments of the same FP type, which match the
1016 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1017 FT->getParamType(0) != FT->getParamType(1) ||
1018 !FT->getParamType(0)->isFloatingPointTy())
1021 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1022 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1023 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1026 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1030 // fmin((double)floatval1, (double)floatval2)
1031 // -> (double)fminf(floatval1, floatval2)
1032 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1033 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1034 Callee->getAttributes());
1035 return B.CreateFPExt(V, B.getDoubleTy());
1038 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1039 Function *Callee = CI->getCalledFunction();
1040 Value *Ret = nullptr;
1041 StringRef Name = Callee->getName();
1042 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1043 Ret = optimizeUnaryDoubleFP(CI, B, true);
1045 FunctionType *FT = Callee->getFunctionType();
1046 // Just make sure this has 1 argument of FP type, which matches the
1048 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1049 !FT->getParamType(0)->isFloatingPointTy())
1052 // cos(-x) -> cos(x)
1053 Value *Op1 = CI->getArgOperand(0);
1054 if (BinaryOperator::isFNeg(Op1)) {
1055 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1056 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1061 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1062 Function *Callee = CI->getCalledFunction();
1063 Value *Ret = nullptr;
1064 StringRef Name = Callee->getName();
1065 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1066 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, TLI->getName(LibFunc::exp2), B,
1086 Callee->getAttributes());
1087 // pow(10.0, x) -> exp10(x)
1088 if (Op1C->isExactlyValue(10.0) &&
1089 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1091 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1092 Callee->getAttributes());
1095 bool unsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1097 // pow(exp(x), y) -> exp(x*y)
1098 // pow(exp2(x), y) -> exp2(x * y)
1099 // We enable these only under fast-math. Besides rounding
1100 // differences the transformation changes overflow and
1101 // underflow behavior quite dramatically.
1102 // Example: x = 1000, y = 0.001.
1103 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1105 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1106 IRBuilder<>::FastMathFlagGuard Guard(B);
1108 FMF.setUnsafeAlgebra();
1109 B.SetFastMathFlags(FMF);
1112 Function *OpCCallee = OpC->getCalledFunction();
1113 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1114 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2))
1115 return EmitUnaryFloatFnCall(
1116 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"),
1117 OpCCallee->getName(), B, OpCCallee->getAttributes());
1121 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1125 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1126 return ConstantFP::get(CI->getType(), 1.0);
1128 if (Op2C->isExactlyValue(0.5) &&
1129 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1131 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1134 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1136 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1137 Callee->getAttributes());
1139 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1140 // This is faster than calling pow, and still handles negative zero
1141 // and negative infinity correctly.
1142 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1143 Value *Inf = ConstantFP::getInfinity(CI->getType());
1144 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1145 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1147 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1148 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1149 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1153 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1155 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1156 return B.CreateFMul(Op1, Op1, "pow2");
1157 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1158 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1162 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1163 Function *Callee = CI->getCalledFunction();
1164 Function *Caller = CI->getParent()->getParent();
1165 Value *Ret = nullptr;
1166 StringRef Name = Callee->getName();
1167 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1168 Ret = optimizeUnaryDoubleFP(CI, B, true);
1170 FunctionType *FT = Callee->getFunctionType();
1171 // Just make sure this has 1 argument of FP type, which matches the
1173 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1174 !FT->getParamType(0)->isFloatingPointTy())
1177 Value *Op = CI->getArgOperand(0);
1178 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1179 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1180 LibFunc::Func LdExp = LibFunc::ldexpl;
1181 if (Op->getType()->isFloatTy())
1182 LdExp = LibFunc::ldexpf;
1183 else if (Op->getType()->isDoubleTy())
1184 LdExp = LibFunc::ldexp;
1186 if (TLI->has(LdExp)) {
1187 Value *LdExpArg = nullptr;
1188 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1189 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1190 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1191 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1192 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1193 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1197 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1198 if (!Op->getType()->isFloatTy())
1199 One = ConstantExpr::getFPExtend(One, Op->getType());
1201 Module *M = Caller->getParent();
1203 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1204 Op->getType(), B.getInt32Ty(), nullptr);
1205 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
1206 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1207 CI->setCallingConv(F->getCallingConv());
1215 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1216 Function *Callee = CI->getCalledFunction();
1217 Value *Ret = nullptr;
1218 StringRef Name = Callee->getName();
1219 if (Name == "fabs" && hasFloatVersion(Name))
1220 Ret = optimizeUnaryDoubleFP(CI, B, false);
1222 FunctionType *FT = Callee->getFunctionType();
1223 // Make sure this has 1 argument of FP type which matches the result type.
1224 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1225 !FT->getParamType(0)->isFloatingPointTy())
1228 Value *Op = CI->getArgOperand(0);
1229 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1230 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1231 if (I->getOpcode() == Instruction::FMul)
1232 if (I->getOperand(0) == I->getOperand(1))
1238 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1239 // If we can shrink the call to a float function rather than a double
1240 // function, do that first.
1241 Function *Callee = CI->getCalledFunction();
1242 StringRef Name = Callee->getName();
1243 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1244 (Name == "fmax" && hasFloatVersion(Name))) {
1245 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1250 // Make sure this has 2 arguments of FP type which match the result type.
1251 FunctionType *FT = Callee->getFunctionType();
1252 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1253 FT->getParamType(0) != FT->getParamType(1) ||
1254 !FT->getParamType(0)->isFloatingPointTy())
1257 IRBuilder<>::FastMathFlagGuard Guard(B);
1259 Function *F = CI->getParent()->getParent();
1260 if (canUseUnsafeFPMath(F)) {
1261 // Unsafe algebra sets all fast-math-flags to true.
1262 FMF.setUnsafeAlgebra();
1264 // At a minimum, no-nans-fp-math must be true.
1265 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
1266 if (Attr.getValueAsString() != "true")
1268 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1269 // "Ideally, fmax would be sensitive to the sign of zero, for example
1270 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1271 // might be impractical."
1272 FMF.setNoSignedZeros();
1275 B.SetFastMathFlags(FMF);
1277 // We have a relaxed floating-point environment. We can ignore NaN-handling
1278 // and transform to a compare and select. We do not have to consider errno or
1279 // exceptions, because fmin/fmax do not have those.
1280 Value *Op0 = CI->getArgOperand(0);
1281 Value *Op1 = CI->getArgOperand(1);
1282 Value *Cmp = Callee->getName().startswith("fmin") ?
1283 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1284 return B.CreateSelect(Cmp, Op0, Op1);
1287 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1288 Function *Callee = CI->getCalledFunction();
1289 Value *Ret = nullptr;
1290 StringRef Name = Callee->getName();
1291 if (UnsafeFPShrink && hasFloatVersion(Name))
1292 Ret = optimizeUnaryDoubleFP(CI, B, true);
1293 FunctionType *FT = Callee->getFunctionType();
1295 // Just make sure this has 1 argument of FP type, which matches the
1297 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1298 !FT->getParamType(0)->isFloatingPointTy())
1301 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1303 Value *Op1 = CI->getArgOperand(0);
1304 auto *OpC = dyn_cast<CallInst>(Op1);
1308 // log(pow(x,y)) -> y*log(x)
1309 // This is only applicable to log, log2, log10.
1310 if (Name != "log" && Name != "log2" && Name != "log10")
1313 IRBuilder<>::FastMathFlagGuard Guard(B);
1315 FMF.setUnsafeAlgebra();
1316 B.SetFastMathFlags(FMF);
1319 Function *F = OpC->getCalledFunction();
1320 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1321 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
1322 return B.CreateFMul(OpC->getArgOperand(1),
1323 EmitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1324 Callee->getAttributes()), "mul");
1328 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1329 Function *Callee = CI->getCalledFunction();
1331 Value *Ret = nullptr;
1332 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1333 Callee->getIntrinsicID() == Intrinsic::sqrt))
1334 Ret = optimizeUnaryDoubleFP(CI, B, true);
1335 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1338 Value *Op = CI->getArgOperand(0);
1339 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1340 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1341 // We're looking for a repeated factor in a multiplication tree,
1342 // so we can do this fold: sqrt(x * x) -> fabs(x);
1343 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1344 Value *Op0 = I->getOperand(0);
1345 Value *Op1 = I->getOperand(1);
1346 Value *RepeatOp = nullptr;
1347 Value *OtherOp = nullptr;
1349 // Simple match: the operands of the multiply are identical.
1352 // Look for a more complicated pattern: one of the operands is itself
1353 // a multiply, so search for a common factor in that multiply.
1354 // Note: We don't bother looking any deeper than this first level or for
1355 // variations of this pattern because instcombine's visitFMUL and/or the
1356 // reassociation pass should give us this form.
1357 Value *OtherMul0, *OtherMul1;
1358 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1359 // Pattern: sqrt((x * y) * z)
1360 if (OtherMul0 == OtherMul1) {
1361 // Matched: sqrt((x * x) * z)
1362 RepeatOp = OtherMul0;
1368 // Fast math flags for any created instructions should match the sqrt
1370 // FIXME: We're not checking the sqrt because it doesn't have
1371 // fast-math-flags (see earlier comment).
1372 IRBuilder<>::FastMathFlagGuard Guard(B);
1373 B.SetFastMathFlags(I->getFastMathFlags());
1374 // If we found a repeated factor, hoist it out of the square root and
1375 // replace it with the fabs of that factor.
1376 Module *M = Callee->getParent();
1377 Type *ArgType = Op->getType();
1378 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1379 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1381 // If we found a non-repeated factor, we still need to get its square
1382 // root. We then multiply that by the value that was simplified out
1383 // of the square root calculation.
1384 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1385 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1386 return B.CreateFMul(FabsCall, SqrtCall);
1395 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1396 Function *Callee = CI->getCalledFunction();
1397 Value *Ret = nullptr;
1398 StringRef Name = Callee->getName();
1399 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1400 Ret = optimizeUnaryDoubleFP(CI, B, true);
1401 FunctionType *FT = Callee->getFunctionType();
1403 // Just make sure this has 1 argument of FP type, which matches the
1405 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1406 !FT->getParamType(0)->isFloatingPointTy())
1409 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1411 Value *Op1 = CI->getArgOperand(0);
1412 auto *OpC = dyn_cast<CallInst>(Op1);
1416 // tan(atan(x)) -> x
1417 // tanf(atanf(x)) -> x
1418 // tanl(atanl(x)) -> x
1420 Function *F = OpC->getCalledFunction();
1421 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1422 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1423 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1424 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1425 Ret = OpC->getArgOperand(0);
1429 static bool isTrigLibCall(CallInst *CI);
1430 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1431 bool UseFloat, Value *&Sin, Value *&Cos,
1434 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1436 // Make sure the prototype is as expected, otherwise the rest of the
1437 // function is probably invalid and likely to abort.
1438 if (!isTrigLibCall(CI))
1441 Value *Arg = CI->getArgOperand(0);
1442 SmallVector<CallInst *, 1> SinCalls;
1443 SmallVector<CallInst *, 1> CosCalls;
1444 SmallVector<CallInst *, 1> SinCosCalls;
1446 bool IsFloat = Arg->getType()->isFloatTy();
1448 // Look for all compatible sinpi, cospi and sincospi calls with the same
1449 // argument. If there are enough (in some sense) we can make the
1451 for (User *U : Arg->users())
1452 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1455 // It's only worthwhile if both sinpi and cospi are actually used.
1456 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1459 Value *Sin, *Cos, *SinCos;
1460 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1462 replaceTrigInsts(SinCalls, Sin);
1463 replaceTrigInsts(CosCalls, Cos);
1464 replaceTrigInsts(SinCosCalls, SinCos);
1469 static bool isTrigLibCall(CallInst *CI) {
1470 Function *Callee = CI->getCalledFunction();
1471 FunctionType *FT = Callee->getFunctionType();
1473 // We can only hope to do anything useful if we can ignore things like errno
1474 // and floating-point exceptions.
1475 bool AttributesSafe =
1476 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1478 // Other than that we need float(float) or double(double)
1479 return AttributesSafe && FT->getNumParams() == 1 &&
1480 FT->getReturnType() == FT->getParamType(0) &&
1481 (FT->getParamType(0)->isFloatTy() ||
1482 FT->getParamType(0)->isDoubleTy());
1486 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1487 SmallVectorImpl<CallInst *> &SinCalls,
1488 SmallVectorImpl<CallInst *> &CosCalls,
1489 SmallVectorImpl<CallInst *> &SinCosCalls) {
1490 CallInst *CI = dyn_cast<CallInst>(Val);
1495 Function *Callee = CI->getCalledFunction();
1497 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1502 if (Func == LibFunc::sinpif)
1503 SinCalls.push_back(CI);
1504 else if (Func == LibFunc::cospif)
1505 CosCalls.push_back(CI);
1506 else if (Func == LibFunc::sincospif_stret)
1507 SinCosCalls.push_back(CI);
1509 if (Func == LibFunc::sinpi)
1510 SinCalls.push_back(CI);
1511 else if (Func == LibFunc::cospi)
1512 CosCalls.push_back(CI);
1513 else if (Func == LibFunc::sincospi_stret)
1514 SinCosCalls.push_back(CI);
1518 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1520 for (CallInst *C : Calls)
1521 replaceAllUsesWith(C, Res);
1524 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1525 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1526 Type *ArgTy = Arg->getType();
1530 Triple T(OrigCallee->getParent()->getTargetTriple());
1532 Name = "__sincospif_stret";
1534 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1535 // x86_64 can't use {float, float} since that would be returned in both
1536 // xmm0 and xmm1, which isn't what a real struct would do.
1537 ResTy = T.getArch() == Triple::x86_64
1538 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1539 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1541 Name = "__sincospi_stret";
1542 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1545 Module *M = OrigCallee->getParent();
1546 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1547 ResTy, ArgTy, nullptr);
1549 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1550 // If the argument is an instruction, it must dominate all uses so put our
1551 // sincos call there.
1552 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1554 // Otherwise (e.g. for a constant) the beginning of the function is as
1555 // good a place as any.
1556 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1557 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1560 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1562 if (SinCos->getType()->isStructTy()) {
1563 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1564 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1566 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1568 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1573 //===----------------------------------------------------------------------===//
1574 // Integer Library Call Optimizations
1575 //===----------------------------------------------------------------------===//
1577 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1578 FunctionType *FT = Callee->getFunctionType();
1579 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1580 FT->getParamType(0)->isIntegerTy();
1583 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1584 Function *Callee = CI->getCalledFunction();
1585 if (!checkIntUnaryReturnAndParam(Callee))
1587 Value *Op = CI->getArgOperand(0);
1590 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1591 if (CI->isZero()) // ffs(0) -> 0.
1592 return B.getInt32(0);
1593 // ffs(c) -> cttz(c)+1
1594 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1597 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1598 Type *ArgType = Op->getType();
1600 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1601 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1602 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1603 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1605 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1606 return B.CreateSelect(Cond, V, B.getInt32(0));
1609 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1610 Function *Callee = CI->getCalledFunction();
1611 FunctionType *FT = Callee->getFunctionType();
1612 // We require integer(integer) where the types agree.
1613 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1614 FT->getParamType(0) != FT->getReturnType())
1617 // abs(x) -> x >s -1 ? x : -x
1618 Value *Op = CI->getArgOperand(0);
1620 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1621 Value *Neg = B.CreateNeg(Op, "neg");
1622 return B.CreateSelect(Pos, Op, Neg);
1625 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1626 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1629 // isdigit(c) -> (c-'0') <u 10
1630 Value *Op = CI->getArgOperand(0);
1631 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1632 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1633 return B.CreateZExt(Op, CI->getType());
1636 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1637 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1640 // isascii(c) -> c <u 128
1641 Value *Op = CI->getArgOperand(0);
1642 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1643 return B.CreateZExt(Op, CI->getType());
1646 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1647 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1650 // toascii(c) -> c & 0x7f
1651 return B.CreateAnd(CI->getArgOperand(0),
1652 ConstantInt::get(CI->getType(), 0x7F));
1655 //===----------------------------------------------------------------------===//
1656 // Formatting and IO Library Call Optimizations
1657 //===----------------------------------------------------------------------===//
1659 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1661 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1663 // Error reporting calls should be cold, mark them as such.
1664 // This applies even to non-builtin calls: it is only a hint and applies to
1665 // functions that the frontend might not understand as builtins.
1667 // This heuristic was suggested in:
1668 // Improving Static Branch Prediction in a Compiler
1669 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1670 // Proceedings of PACT'98, Oct. 1998, IEEE
1671 Function *Callee = CI->getCalledFunction();
1673 if (!CI->hasFnAttr(Attribute::Cold) &&
1674 isReportingError(Callee, CI, StreamArg)) {
1675 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1681 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1682 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1688 // These functions might be considered cold, but only if their stream
1689 // argument is stderr.
1691 if (StreamArg >= (int)CI->getNumArgOperands())
1693 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1696 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1697 if (!GV || !GV->isDeclaration())
1699 return GV->getName() == "stderr";
1702 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1703 // Check for a fixed format string.
1704 StringRef FormatStr;
1705 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1708 // Empty format string -> noop.
1709 if (FormatStr.empty()) // Tolerate printf's declared void.
1710 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1712 // Do not do any of the following transformations if the printf return value
1713 // is used, in general the printf return value is not compatible with either
1714 // putchar() or puts().
1715 if (!CI->use_empty())
1718 // printf("x") -> putchar('x'), even for '%'.
1719 if (FormatStr.size() == 1) {
1720 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1721 if (CI->use_empty() || !Res)
1723 return B.CreateIntCast(Res, CI->getType(), true);
1726 // printf("foo\n") --> puts("foo")
1727 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1728 FormatStr.find('%') == StringRef::npos) { // No format characters.
1729 // Create a string literal with no \n on it. We expect the constant merge
1730 // pass to be run after this pass, to merge duplicate strings.
1731 FormatStr = FormatStr.drop_back();
1732 Value *GV = B.CreateGlobalString(FormatStr, "str");
1733 Value *NewCI = EmitPutS(GV, B, TLI);
1734 return (CI->use_empty() || !NewCI)
1736 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1739 // Optimize specific format strings.
1740 // printf("%c", chr) --> putchar(chr)
1741 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1742 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1743 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
1745 if (CI->use_empty() || !Res)
1747 return B.CreateIntCast(Res, CI->getType(), true);
1750 // printf("%s\n", str) --> puts(str)
1751 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1752 CI->getArgOperand(1)->getType()->isPointerTy()) {
1753 return EmitPutS(CI->getArgOperand(1), B, TLI);
1758 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1760 Function *Callee = CI->getCalledFunction();
1761 // Require one fixed pointer argument and an integer/void result.
1762 FunctionType *FT = Callee->getFunctionType();
1763 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1764 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1767 if (Value *V = optimizePrintFString(CI, B)) {
1771 // printf(format, ...) -> iprintf(format, ...) if no floating point
1773 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1774 Module *M = B.GetInsertBlock()->getParent()->getParent();
1775 Constant *IPrintFFn =
1776 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1777 CallInst *New = cast<CallInst>(CI->clone());
1778 New->setCalledFunction(IPrintFFn);
1785 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1786 // Check for a fixed format string.
1787 StringRef FormatStr;
1788 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1791 // If we just have a format string (nothing else crazy) transform it.
1792 if (CI->getNumArgOperands() == 2) {
1793 // Make sure there's no % in the constant array. We could try to handle
1794 // %% -> % in the future if we cared.
1795 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1796 if (FormatStr[i] == '%')
1797 return nullptr; // we found a format specifier, bail out.
1799 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1800 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1801 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1802 FormatStr.size() + 1),
1803 1); // Copy the null byte.
1804 return ConstantInt::get(CI->getType(), FormatStr.size());
1807 // The remaining optimizations require the format string to be "%s" or "%c"
1808 // and have an extra operand.
1809 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1810 CI->getNumArgOperands() < 3)
1813 // Decode the second character of the format string.
1814 if (FormatStr[1] == 'c') {
1815 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1816 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1818 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1819 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1820 B.CreateStore(V, Ptr);
1821 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1822 B.CreateStore(B.getInt8(0), Ptr);
1824 return ConstantInt::get(CI->getType(), 1);
1827 if (FormatStr[1] == 's') {
1828 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1829 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1832 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1836 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1837 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1839 // The sprintf result is the unincremented number of bytes in the string.
1840 return B.CreateIntCast(Len, CI->getType(), false);
1845 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1846 Function *Callee = CI->getCalledFunction();
1847 // Require two fixed pointer arguments and an integer result.
1848 FunctionType *FT = Callee->getFunctionType();
1849 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1850 !FT->getParamType(1)->isPointerTy() ||
1851 !FT->getReturnType()->isIntegerTy())
1854 if (Value *V = optimizeSPrintFString(CI, B)) {
1858 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1860 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1861 Module *M = B.GetInsertBlock()->getParent()->getParent();
1862 Constant *SIPrintFFn =
1863 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1864 CallInst *New = cast<CallInst>(CI->clone());
1865 New->setCalledFunction(SIPrintFFn);
1872 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1873 optimizeErrorReporting(CI, B, 0);
1875 // All the optimizations depend on the format string.
1876 StringRef FormatStr;
1877 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1880 // Do not do any of the following transformations if the fprintf return
1881 // value is used, in general the fprintf return value is not compatible
1882 // with fwrite(), fputc() or fputs().
1883 if (!CI->use_empty())
1886 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1887 if (CI->getNumArgOperands() == 2) {
1888 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1889 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1890 return nullptr; // We found a format specifier.
1893 CI->getArgOperand(1),
1894 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
1895 CI->getArgOperand(0), B, DL, TLI);
1898 // The remaining optimizations require the format string to be "%s" or "%c"
1899 // and have an extra operand.
1900 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1901 CI->getNumArgOperands() < 3)
1904 // Decode the second character of the format string.
1905 if (FormatStr[1] == 'c') {
1906 // fprintf(F, "%c", chr) --> fputc(chr, F)
1907 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1909 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1912 if (FormatStr[1] == 's') {
1913 // fprintf(F, "%s", str) --> fputs(str, F)
1914 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1916 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
1921 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1922 Function *Callee = CI->getCalledFunction();
1923 // Require two fixed paramters as pointers and integer result.
1924 FunctionType *FT = Callee->getFunctionType();
1925 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1926 !FT->getParamType(1)->isPointerTy() ||
1927 !FT->getReturnType()->isIntegerTy())
1930 if (Value *V = optimizeFPrintFString(CI, B)) {
1934 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1935 // floating point arguments.
1936 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1937 Module *M = B.GetInsertBlock()->getParent()->getParent();
1938 Constant *FIPrintFFn =
1939 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1940 CallInst *New = cast<CallInst>(CI->clone());
1941 New->setCalledFunction(FIPrintFFn);
1948 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1949 optimizeErrorReporting(CI, B, 3);
1951 Function *Callee = CI->getCalledFunction();
1952 // Require a pointer, an integer, an integer, a pointer, returning integer.
1953 FunctionType *FT = Callee->getFunctionType();
1954 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1955 !FT->getParamType(1)->isIntegerTy() ||
1956 !FT->getParamType(2)->isIntegerTy() ||
1957 !FT->getParamType(3)->isPointerTy() ||
1958 !FT->getReturnType()->isIntegerTy())
1961 // Get the element size and count.
1962 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1963 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1964 if (!SizeC || !CountC)
1966 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1968 // If this is writing zero records, remove the call (it's a noop).
1970 return ConstantInt::get(CI->getType(), 0);
1972 // If this is writing one byte, turn it into fputc.
1973 // This optimisation is only valid, if the return value is unused.
1974 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1975 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1976 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
1977 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1983 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1984 optimizeErrorReporting(CI, B, 1);
1986 Function *Callee = CI->getCalledFunction();
1988 // Require two pointers. Also, we can't optimize if return value is used.
1989 FunctionType *FT = Callee->getFunctionType();
1990 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1991 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1994 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1995 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1999 // Known to have no uses (see above).
2001 CI->getArgOperand(0),
2002 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2003 CI->getArgOperand(1), B, DL, TLI);
2006 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2007 Function *Callee = CI->getCalledFunction();
2008 // Require one fixed pointer argument and an integer/void result.
2009 FunctionType *FT = Callee->getFunctionType();
2010 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2011 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2014 // Check for a constant string.
2016 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2019 if (Str.empty() && CI->use_empty()) {
2020 // puts("") -> putchar('\n')
2021 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
2022 if (CI->use_empty() || !Res)
2024 return B.CreateIntCast(Res, CI->getType(), true);
2030 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2032 SmallString<20> FloatFuncName = FuncName;
2033 FloatFuncName += 'f';
2034 if (TLI->getLibFunc(FloatFuncName, Func))
2035 return TLI->has(Func);
2039 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2040 IRBuilder<> &Builder) {
2042 Function *Callee = CI->getCalledFunction();
2043 StringRef FuncName = Callee->getName();
2045 // Check for string/memory library functions.
2046 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2047 // Make sure we never change the calling convention.
2048 assert((ignoreCallingConv(Func) ||
2049 CI->getCallingConv() == llvm::CallingConv::C) &&
2050 "Optimizing string/memory libcall would change the calling convention");
2052 case LibFunc::strcat:
2053 return optimizeStrCat(CI, Builder);
2054 case LibFunc::strncat:
2055 return optimizeStrNCat(CI, Builder);
2056 case LibFunc::strchr:
2057 return optimizeStrChr(CI, Builder);
2058 case LibFunc::strrchr:
2059 return optimizeStrRChr(CI, Builder);
2060 case LibFunc::strcmp:
2061 return optimizeStrCmp(CI, Builder);
2062 case LibFunc::strncmp:
2063 return optimizeStrNCmp(CI, Builder);
2064 case LibFunc::strcpy:
2065 return optimizeStrCpy(CI, Builder);
2066 case LibFunc::stpcpy:
2067 return optimizeStpCpy(CI, Builder);
2068 case LibFunc::strncpy:
2069 return optimizeStrNCpy(CI, Builder);
2070 case LibFunc::strlen:
2071 return optimizeStrLen(CI, Builder);
2072 case LibFunc::strpbrk:
2073 return optimizeStrPBrk(CI, Builder);
2074 case LibFunc::strtol:
2075 case LibFunc::strtod:
2076 case LibFunc::strtof:
2077 case LibFunc::strtoul:
2078 case LibFunc::strtoll:
2079 case LibFunc::strtold:
2080 case LibFunc::strtoull:
2081 return optimizeStrTo(CI, Builder);
2082 case LibFunc::strspn:
2083 return optimizeStrSpn(CI, Builder);
2084 case LibFunc::strcspn:
2085 return optimizeStrCSpn(CI, Builder);
2086 case LibFunc::strstr:
2087 return optimizeStrStr(CI, Builder);
2088 case LibFunc::memchr:
2089 return optimizeMemChr(CI, Builder);
2090 case LibFunc::memcmp:
2091 return optimizeMemCmp(CI, Builder);
2092 case LibFunc::memcpy:
2093 return optimizeMemCpy(CI, Builder);
2094 case LibFunc::memmove:
2095 return optimizeMemMove(CI, Builder);
2096 case LibFunc::memset:
2097 return optimizeMemSet(CI, Builder);
2105 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2106 if (CI->isNoBuiltin())
2110 Function *Callee = CI->getCalledFunction();
2111 StringRef FuncName = Callee->getName();
2112 IRBuilder<> Builder(CI);
2113 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2115 // Command-line parameter overrides function attribute.
2116 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2117 UnsafeFPShrink = EnableUnsafeFPShrink;
2118 else if (canUseUnsafeFPMath(Callee))
2119 UnsafeFPShrink = true;
2121 // First, check for intrinsics.
2122 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2123 if (!isCallingConvC)
2125 switch (II->getIntrinsicID()) {
2126 case Intrinsic::pow:
2127 return optimizePow(CI, Builder);
2128 case Intrinsic::exp2:
2129 return optimizeExp2(CI, Builder);
2130 case Intrinsic::fabs:
2131 return optimizeFabs(CI, Builder);
2132 case Intrinsic::log:
2133 return optimizeLog(CI, Builder);
2134 case Intrinsic::sqrt:
2135 return optimizeSqrt(CI, Builder);
2141 // Also try to simplify calls to fortified library functions.
2142 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2143 // Try to further simplify the result.
2144 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2145 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2146 // Use an IR Builder from SimplifiedCI if available instead of CI
2147 // to guarantee we reach all uses we might replace later on.
2148 IRBuilder<> TmpBuilder(SimplifiedCI);
2149 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2150 // If we were able to further simplify, remove the now redundant call.
2151 SimplifiedCI->replaceAllUsesWith(V);
2152 SimplifiedCI->eraseFromParent();
2156 return SimplifiedFortifiedCI;
2159 // Then check for known library functions.
2160 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2161 // We never change the calling convention.
2162 if (!ignoreCallingConv(Func) && !isCallingConvC)
2164 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2170 return optimizeCos(CI, Builder);
2171 case LibFunc::sinpif:
2172 case LibFunc::sinpi:
2173 case LibFunc::cospif:
2174 case LibFunc::cospi:
2175 return optimizeSinCosPi(CI, Builder);
2179 return optimizePow(CI, Builder);
2180 case LibFunc::exp2l:
2182 case LibFunc::exp2f:
2183 return optimizeExp2(CI, Builder);
2184 case LibFunc::fabsf:
2186 case LibFunc::fabsl:
2187 return optimizeFabs(CI, Builder);
2188 case LibFunc::sqrtf:
2190 case LibFunc::sqrtl:
2191 return optimizeSqrt(CI, Builder);
2194 case LibFunc::ffsll:
2195 return optimizeFFS(CI, Builder);
2198 case LibFunc::llabs:
2199 return optimizeAbs(CI, Builder);
2200 case LibFunc::isdigit:
2201 return optimizeIsDigit(CI, Builder);
2202 case LibFunc::isascii:
2203 return optimizeIsAscii(CI, Builder);
2204 case LibFunc::toascii:
2205 return optimizeToAscii(CI, Builder);
2206 case LibFunc::printf:
2207 return optimizePrintF(CI, Builder);
2208 case LibFunc::sprintf:
2209 return optimizeSPrintF(CI, Builder);
2210 case LibFunc::fprintf:
2211 return optimizeFPrintF(CI, Builder);
2212 case LibFunc::fwrite:
2213 return optimizeFWrite(CI, Builder);
2214 case LibFunc::fputs:
2215 return optimizeFPuts(CI, Builder);
2217 case LibFunc::log10:
2218 case LibFunc::log1p:
2221 return optimizeLog(CI, Builder);
2223 return optimizePuts(CI, Builder);
2227 return optimizeTan(CI, Builder);
2228 case LibFunc::perror:
2229 return optimizeErrorReporting(CI, Builder);
2230 case LibFunc::vfprintf:
2231 case LibFunc::fiprintf:
2232 return optimizeErrorReporting(CI, Builder, 0);
2233 case LibFunc::fputc:
2234 return optimizeErrorReporting(CI, Builder, 1);
2236 case LibFunc::floor:
2238 case LibFunc::round:
2239 case LibFunc::nearbyint:
2240 case LibFunc::trunc:
2241 if (hasFloatVersion(FuncName))
2242 return optimizeUnaryDoubleFP(CI, Builder, false);
2245 case LibFunc::acosh:
2247 case LibFunc::asinh:
2249 case LibFunc::atanh:
2253 case LibFunc::exp10:
2254 case LibFunc::expm1:
2258 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2259 return optimizeUnaryDoubleFP(CI, Builder, true);
2261 case LibFunc::copysign:
2262 if (hasFloatVersion(FuncName))
2263 return optimizeBinaryDoubleFP(CI, Builder);
2265 case LibFunc::fminf:
2267 case LibFunc::fminl:
2268 case LibFunc::fmaxf:
2270 case LibFunc::fmaxl:
2271 return optimizeFMinFMax(CI, Builder);
2279 LibCallSimplifier::LibCallSimplifier(
2280 const DataLayout &DL, const TargetLibraryInfo *TLI,
2281 function_ref<void(Instruction *, Value *)> Replacer)
2282 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2283 Replacer(Replacer) {}
2285 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2286 // Indirect through the replacer used in this instance.
2291 // Additional cases that we need to add to this file:
2294 // * cbrt(expN(X)) -> expN(x/3)
2295 // * cbrt(sqrt(x)) -> pow(x,1/6)
2296 // * cbrt(cbrt(x)) -> pow(x,1/9)
2299 // * exp(log(x)) -> x
2302 // * log(exp(x)) -> x
2303 // * log(exp(y)) -> y*log(e)
2304 // * log(exp2(y)) -> y*log(2)
2305 // * log(exp10(y)) -> y*log(10)
2306 // * log(sqrt(x)) -> 0.5*log(x)
2308 // lround, lroundf, lroundl:
2309 // * lround(cnst) -> cnst'
2312 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2313 // * pow(pow(x,y),z)-> pow(x,y*z)
2315 // round, roundf, roundl:
2316 // * round(cnst) -> cnst'
2319 // * signbit(cnst) -> cnst'
2320 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2322 // sqrt, sqrtf, sqrtl:
2323 // * sqrt(expN(x)) -> expN(x*0.5)
2324 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2325 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2327 // trunc, truncf, truncl:
2328 // * trunc(cnst) -> cnst'
2332 //===----------------------------------------------------------------------===//
2333 // Fortified Library Call Optimizations
2334 //===----------------------------------------------------------------------===//
2336 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2340 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2342 if (ConstantInt *ObjSizeCI =
2343 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2344 if (ObjSizeCI->isAllOnesValue())
2346 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2347 if (OnlyLowerUnknownSize)
2350 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2351 // If the length is 0 we don't know how long it is and so we can't
2352 // remove the check.
2355 return ObjSizeCI->getZExtValue() >= Len;
2357 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2358 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2363 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2364 Function *Callee = CI->getCalledFunction();
2366 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2369 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2370 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2371 CI->getArgOperand(2), 1);
2372 return CI->getArgOperand(0);
2377 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2378 Function *Callee = CI->getCalledFunction();
2380 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2383 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2384 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2385 CI->getArgOperand(2), 1);
2386 return CI->getArgOperand(0);
2391 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2392 Function *Callee = CI->getCalledFunction();
2394 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2397 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2398 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2399 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2400 return CI->getArgOperand(0);
2405 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2407 LibFunc::Func Func) {
2408 Function *Callee = CI->getCalledFunction();
2409 StringRef Name = Callee->getName();
2410 const DataLayout &DL = CI->getModule()->getDataLayout();
2412 if (!checkStringCopyLibFuncSignature(Callee, Func))
2415 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2416 *ObjSize = CI->getArgOperand(2);
2418 // __stpcpy_chk(x,x,...) -> x+strlen(x)
2419 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2420 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2421 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2424 // If a) we don't have any length information, or b) we know this will
2425 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2426 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2427 // TODO: It might be nice to get a maximum length out of the possible
2428 // string lengths for varying.
2429 if (isFortifiedCallFoldable(CI, 2, 1, true))
2430 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2432 if (OnlyLowerUnknownSize)
2435 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2436 uint64_t Len = GetStringLength(Src);
2440 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2441 Value *LenV = ConstantInt::get(SizeTTy, Len);
2442 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2443 // If the function was an __stpcpy_chk, and we were able to fold it into
2444 // a __memcpy_chk, we still need to return the correct end pointer.
2445 if (Ret && Func == LibFunc::stpcpy_chk)
2446 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2450 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2452 LibFunc::Func Func) {
2453 Function *Callee = CI->getCalledFunction();
2454 StringRef Name = Callee->getName();
2456 if (!checkStringCopyLibFuncSignature(Callee, Func))
2458 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2459 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2460 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2466 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2467 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2468 // Some clang users checked for _chk libcall availability using:
2469 // __has_builtin(__builtin___memcpy_chk)
2470 // When compiling with -fno-builtin, this is always true.
2471 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2472 // end up with fortified libcalls, which isn't acceptable in a freestanding
2473 // environment which only provides their non-fortified counterparts.
2475 // Until we change clang and/or teach external users to check for availability
2476 // differently, disregard the "nobuiltin" attribute and TLI::has.
2481 Function *Callee = CI->getCalledFunction();
2482 StringRef FuncName = Callee->getName();
2483 IRBuilder<> Builder(CI);
2484 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2486 // First, check that this is a known library functions.
2487 if (!TLI->getLibFunc(FuncName, Func))
2490 // We never change the calling convention.
2491 if (!ignoreCallingConv(Func) && !isCallingConvC)
2495 case LibFunc::memcpy_chk:
2496 return optimizeMemCpyChk(CI, Builder);
2497 case LibFunc::memmove_chk:
2498 return optimizeMemMoveChk(CI, Builder);
2499 case LibFunc::memset_chk:
2500 return optimizeMemSetChk(CI, Builder);
2501 case LibFunc::stpcpy_chk:
2502 case LibFunc::strcpy_chk:
2503 return optimizeStrpCpyChk(CI, Builder, Func);
2504 case LibFunc::stpncpy_chk:
2505 case LibFunc::strncpy_chk:
2506 return optimizeStrpNCpyChk(CI, Builder, Func);
2513 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2514 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2515 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}