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/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Transforms/Utils/BuildLibCalls.h"
37 ColdErrorCalls("error-reporting-is-cold", cl::init(true),
38 cl::Hidden, cl::desc("Treat error-reporting calls as cold"));
40 /// This class is the abstract base class for the set of optimizations that
41 /// corresponds to one library call.
43 class LibCallOptimization {
47 const TargetLibraryInfo *TLI;
48 const LibCallSimplifier *LCS;
51 LibCallOptimization() { }
52 virtual ~LibCallOptimization() {}
54 /// callOptimizer - This pure virtual method is implemented by base classes to
55 /// do various optimizations. If this returns null then no transformation was
56 /// performed. If it returns CI, then it transformed the call and CI is to be
57 /// deleted. If it returns something else, replace CI with the new value and
59 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
62 /// ignoreCallingConv - Returns false if this transformation could possibly
63 /// change the calling convention.
64 virtual bool ignoreCallingConv() { return false; }
66 Value *optimizeCall(CallInst *CI, const DataLayout *DL,
67 const TargetLibraryInfo *TLI,
68 const LibCallSimplifier *LCS, IRBuilder<> &B) {
69 Caller = CI->getParent()->getParent();
73 if (CI->getCalledFunction())
74 Context = &CI->getCalledFunction()->getContext();
76 // We never change the calling convention.
77 if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
80 return callOptimizer(CI->getCalledFunction(), CI, B);
84 //===----------------------------------------------------------------------===//
86 //===----------------------------------------------------------------------===//
88 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
89 /// value is equal or not-equal to zero.
90 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
94 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
97 // Unknown instruction.
103 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
104 /// comparisons with With.
105 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
106 for (User *U : V->users()) {
107 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
108 if (IC->isEquality() && IC->getOperand(1) == With)
110 // Unknown instruction.
116 static bool callHasFloatingPointArgument(const CallInst *CI) {
117 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
119 if ((*it)->getType()->isFloatingPointTy())
125 /// \brief Check whether the overloaded unary floating point function
126 /// corresponing to \a Ty is available.
127 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
128 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
129 LibFunc::Func LongDoubleFn) {
130 switch (Ty->getTypeID()) {
131 case Type::FloatTyID:
132 return TLI->has(FloatFn);
133 case Type::DoubleTyID:
134 return TLI->has(DoubleFn);
136 return TLI->has(LongDoubleFn);
140 //===----------------------------------------------------------------------===//
141 // Fortified Library Call Optimizations
142 //===----------------------------------------------------------------------===//
144 struct FortifiedLibCallOptimization : public LibCallOptimization {
146 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
147 bool isString) const = 0;
150 struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
153 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
154 bool isString) const override {
155 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
157 if (ConstantInt *SizeCI =
158 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
159 if (SizeCI->isAllOnesValue())
162 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
163 // If the length is 0 we don't know how long it is and so we can't
165 if (Len == 0) return false;
166 return SizeCI->getZExtValue() >= Len;
168 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
169 CI->getArgOperand(SizeArgOp)))
170 return SizeCI->getZExtValue() >= Arg->getZExtValue();
176 struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
177 Value *callOptimizer(Function *Callee, CallInst *CI,
178 IRBuilder<> &B) override {
180 FunctionType *FT = Callee->getFunctionType();
181 LLVMContext &Context = CI->getParent()->getContext();
183 // Check if this has the right signature.
184 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
185 !FT->getParamType(0)->isPointerTy() ||
186 !FT->getParamType(1)->isPointerTy() ||
187 FT->getParamType(2) != DL->getIntPtrType(Context) ||
188 FT->getParamType(3) != DL->getIntPtrType(Context))
191 if (isFoldable(3, 2, false)) {
192 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
193 CI->getArgOperand(2), 1);
194 return CI->getArgOperand(0);
200 struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
201 Value *callOptimizer(Function *Callee, CallInst *CI,
202 IRBuilder<> &B) override {
204 FunctionType *FT = Callee->getFunctionType();
205 LLVMContext &Context = CI->getParent()->getContext();
207 // Check if this has the right signature.
208 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
209 !FT->getParamType(0)->isPointerTy() ||
210 !FT->getParamType(1)->isPointerTy() ||
211 FT->getParamType(2) != DL->getIntPtrType(Context) ||
212 FT->getParamType(3) != DL->getIntPtrType(Context))
215 if (isFoldable(3, 2, false)) {
216 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
217 CI->getArgOperand(2), 1);
218 return CI->getArgOperand(0);
224 struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
225 Value *callOptimizer(Function *Callee, CallInst *CI,
226 IRBuilder<> &B) override {
228 FunctionType *FT = Callee->getFunctionType();
229 LLVMContext &Context = CI->getParent()->getContext();
231 // Check if this has the right signature.
232 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
233 !FT->getParamType(0)->isPointerTy() ||
234 !FT->getParamType(1)->isIntegerTy() ||
235 FT->getParamType(2) != DL->getIntPtrType(Context) ||
236 FT->getParamType(3) != DL->getIntPtrType(Context))
239 if (isFoldable(3, 2, false)) {
240 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
242 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
243 return CI->getArgOperand(0);
249 struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
250 Value *callOptimizer(Function *Callee, CallInst *CI,
251 IRBuilder<> &B) override {
253 StringRef Name = Callee->getName();
254 FunctionType *FT = Callee->getFunctionType();
255 LLVMContext &Context = CI->getParent()->getContext();
257 // Check if this has the right signature.
258 if (FT->getNumParams() != 3 ||
259 FT->getReturnType() != FT->getParamType(0) ||
260 FT->getParamType(0) != FT->getParamType(1) ||
261 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
262 FT->getParamType(2) != DL->getIntPtrType(Context))
265 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
266 if (Dst == Src) // __strcpy_chk(x,x) -> x
269 // If a) we don't have any length information, or b) we know this will
270 // fit then just lower to a plain strcpy. Otherwise we'll keep our
271 // strcpy_chk call which may fail at runtime if the size is too long.
272 // TODO: It might be nice to get a maximum length out of the possible
273 // string lengths for varying.
274 if (isFoldable(2, 1, true)) {
275 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
278 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
279 uint64_t Len = GetStringLength(Src);
280 if (Len == 0) return nullptr;
282 // This optimization require DataLayout.
283 if (!DL) return nullptr;
286 EmitMemCpyChk(Dst, Src,
287 ConstantInt::get(DL->getIntPtrType(Context), Len),
288 CI->getArgOperand(2), B, DL, TLI);
295 struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
296 Value *callOptimizer(Function *Callee, CallInst *CI,
297 IRBuilder<> &B) override {
299 StringRef Name = Callee->getName();
300 FunctionType *FT = Callee->getFunctionType();
301 LLVMContext &Context = CI->getParent()->getContext();
303 // Check if this has the right signature.
304 if (FT->getNumParams() != 3 ||
305 FT->getReturnType() != FT->getParamType(0) ||
306 FT->getParamType(0) != FT->getParamType(1) ||
307 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
308 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
311 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
312 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
313 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
314 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
317 // If a) we don't have any length information, or b) we know this will
318 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
319 // stpcpy_chk call which may fail at runtime if the size is too long.
320 // TODO: It might be nice to get a maximum length out of the possible
321 // string lengths for varying.
322 if (isFoldable(2, 1, true)) {
323 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
326 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
327 uint64_t Len = GetStringLength(Src);
328 if (Len == 0) return nullptr;
330 // This optimization require DataLayout.
331 if (!DL) return nullptr;
333 Type *PT = FT->getParamType(0);
334 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
335 Value *DstEnd = B.CreateGEP(Dst,
336 ConstantInt::get(DL->getIntPtrType(PT),
338 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
346 struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
347 Value *callOptimizer(Function *Callee, CallInst *CI,
348 IRBuilder<> &B) override {
350 StringRef Name = Callee->getName();
351 FunctionType *FT = Callee->getFunctionType();
352 LLVMContext &Context = CI->getParent()->getContext();
354 // Check if this has the right signature.
355 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
356 FT->getParamType(0) != FT->getParamType(1) ||
357 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
358 !FT->getParamType(2)->isIntegerTy() ||
359 FT->getParamType(3) != DL->getIntPtrType(Context))
362 if (isFoldable(3, 2, false)) {
363 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
364 CI->getArgOperand(2), B, DL, TLI,
372 //===----------------------------------------------------------------------===//
373 // String and Memory Library Call Optimizations
374 //===----------------------------------------------------------------------===//
376 struct StrCatOpt : public LibCallOptimization {
377 Value *callOptimizer(Function *Callee, CallInst *CI,
378 IRBuilder<> &B) override {
379 // Verify the "strcat" function prototype.
380 FunctionType *FT = Callee->getFunctionType();
381 if (FT->getNumParams() != 2 ||
382 FT->getReturnType() != B.getInt8PtrTy() ||
383 FT->getParamType(0) != FT->getReturnType() ||
384 FT->getParamType(1) != FT->getReturnType())
387 // Extract some information from the instruction
388 Value *Dst = CI->getArgOperand(0);
389 Value *Src = CI->getArgOperand(1);
391 // See if we can get the length of the input string.
392 uint64_t Len = GetStringLength(Src);
393 if (Len == 0) return nullptr;
394 --Len; // Unbias length.
396 // Handle the simple, do-nothing case: strcat(x, "") -> x
400 // These optimizations require DataLayout.
401 if (!DL) return nullptr;
403 return emitStrLenMemCpy(Src, Dst, Len, B);
406 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
408 // We need to find the end of the destination string. That's where the
409 // memory is to be moved to. We just generate a call to strlen.
410 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
414 // Now that we have the destination's length, we must index into the
415 // destination's pointer to get the actual memcpy destination (end of
416 // the string .. we're concatenating).
417 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
419 // We have enough information to now generate the memcpy call to do the
420 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
421 B.CreateMemCpy(CpyDst, Src,
422 ConstantInt::get(DL->getIntPtrType(*Context), Len + 1), 1);
427 struct StrNCatOpt : public StrCatOpt {
428 Value *callOptimizer(Function *Callee, CallInst *CI,
429 IRBuilder<> &B) override {
430 // Verify the "strncat" function prototype.
431 FunctionType *FT = Callee->getFunctionType();
432 if (FT->getNumParams() != 3 ||
433 FT->getReturnType() != B.getInt8PtrTy() ||
434 FT->getParamType(0) != FT->getReturnType() ||
435 FT->getParamType(1) != FT->getReturnType() ||
436 !FT->getParamType(2)->isIntegerTy())
439 // Extract some information from the instruction
440 Value *Dst = CI->getArgOperand(0);
441 Value *Src = CI->getArgOperand(1);
444 // We don't do anything if length is not constant
445 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
446 Len = LengthArg->getZExtValue();
450 // See if we can get the length of the input string.
451 uint64_t SrcLen = GetStringLength(Src);
452 if (SrcLen == 0) return nullptr;
453 --SrcLen; // Unbias length.
455 // Handle the simple, do-nothing cases:
456 // strncat(x, "", c) -> x
457 // strncat(x, c, 0) -> x
458 if (SrcLen == 0 || Len == 0) return Dst;
460 // These optimizations require DataLayout.
461 if (!DL) return nullptr;
463 // We don't optimize this case
464 if (Len < SrcLen) return nullptr;
466 // strncat(x, s, c) -> strcat(x, s)
467 // s is constant so the strcat can be optimized further
468 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
472 struct StrChrOpt : public LibCallOptimization {
473 Value *callOptimizer(Function *Callee, CallInst *CI,
474 IRBuilder<> &B) override {
475 // Verify the "strchr" function prototype.
476 FunctionType *FT = Callee->getFunctionType();
477 if (FT->getNumParams() != 2 ||
478 FT->getReturnType() != B.getInt8PtrTy() ||
479 FT->getParamType(0) != FT->getReturnType() ||
480 !FT->getParamType(1)->isIntegerTy(32))
483 Value *SrcStr = CI->getArgOperand(0);
485 // If the second operand is non-constant, see if we can compute the length
486 // of the input string and turn this into memchr.
487 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
489 // These optimizations require DataLayout.
490 if (!DL) return nullptr;
492 uint64_t Len = GetStringLength(SrcStr);
493 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
496 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
497 ConstantInt::get(DL->getIntPtrType(*Context), Len),
501 // Otherwise, the character is a constant, see if the first argument is
502 // a string literal. If so, we can constant fold.
504 if (!getConstantStringInfo(SrcStr, Str)) {
505 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
506 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
510 // Compute the offset, make sure to handle the case when we're searching for
511 // zero (a weird way to spell strlen).
512 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
513 Str.size() : Str.find(CharC->getSExtValue());
514 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
515 return Constant::getNullValue(CI->getType());
517 // strchr(s+n,c) -> gep(s+n+i,c)
518 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
522 struct StrRChrOpt : public LibCallOptimization {
523 Value *callOptimizer(Function *Callee, CallInst *CI,
524 IRBuilder<> &B) override {
525 // Verify the "strrchr" function prototype.
526 FunctionType *FT = Callee->getFunctionType();
527 if (FT->getNumParams() != 2 ||
528 FT->getReturnType() != B.getInt8PtrTy() ||
529 FT->getParamType(0) != FT->getReturnType() ||
530 !FT->getParamType(1)->isIntegerTy(32))
533 Value *SrcStr = CI->getArgOperand(0);
534 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
536 // Cannot fold anything if we're not looking for a constant.
541 if (!getConstantStringInfo(SrcStr, Str)) {
542 // strrchr(s, 0) -> strchr(s, 0)
543 if (DL && CharC->isZero())
544 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
548 // Compute the offset.
549 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
550 Str.size() : Str.rfind(CharC->getSExtValue());
551 if (I == StringRef::npos) // Didn't find the char. Return null.
552 return Constant::getNullValue(CI->getType());
554 // strrchr(s+n,c) -> gep(s+n+i,c)
555 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
559 struct StrCmpOpt : public LibCallOptimization {
560 Value *callOptimizer(Function *Callee, CallInst *CI,
561 IRBuilder<> &B) override {
562 // Verify the "strcmp" function prototype.
563 FunctionType *FT = Callee->getFunctionType();
564 if (FT->getNumParams() != 2 ||
565 !FT->getReturnType()->isIntegerTy(32) ||
566 FT->getParamType(0) != FT->getParamType(1) ||
567 FT->getParamType(0) != B.getInt8PtrTy())
570 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
571 if (Str1P == Str2P) // strcmp(x,x) -> 0
572 return ConstantInt::get(CI->getType(), 0);
574 StringRef Str1, Str2;
575 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
576 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
578 // strcmp(x, y) -> cnst (if both x and y are constant strings)
579 if (HasStr1 && HasStr2)
580 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
582 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
583 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
586 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
587 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
589 // strcmp(P, "x") -> memcmp(P, "x", 2)
590 uint64_t Len1 = GetStringLength(Str1P);
591 uint64_t Len2 = GetStringLength(Str2P);
593 // These optimizations require DataLayout.
594 if (!DL) return nullptr;
596 return EmitMemCmp(Str1P, Str2P,
597 ConstantInt::get(DL->getIntPtrType(*Context),
598 std::min(Len1, Len2)), B, DL, TLI);
605 struct StrNCmpOpt : public LibCallOptimization {
606 Value *callOptimizer(Function *Callee, CallInst *CI,
607 IRBuilder<> &B) override {
608 // Verify the "strncmp" function prototype.
609 FunctionType *FT = Callee->getFunctionType();
610 if (FT->getNumParams() != 3 ||
611 !FT->getReturnType()->isIntegerTy(32) ||
612 FT->getParamType(0) != FT->getParamType(1) ||
613 FT->getParamType(0) != B.getInt8PtrTy() ||
614 !FT->getParamType(2)->isIntegerTy())
617 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
618 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
619 return ConstantInt::get(CI->getType(), 0);
621 // Get the length argument if it is constant.
623 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
624 Length = LengthArg->getZExtValue();
628 if (Length == 0) // strncmp(x,y,0) -> 0
629 return ConstantInt::get(CI->getType(), 0);
631 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
632 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
634 StringRef Str1, Str2;
635 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
636 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
638 // strncmp(x, y) -> cnst (if both x and y are constant strings)
639 if (HasStr1 && HasStr2) {
640 StringRef SubStr1 = Str1.substr(0, Length);
641 StringRef SubStr2 = Str2.substr(0, Length);
642 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
645 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
646 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
649 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
650 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
656 struct StrCpyOpt : public LibCallOptimization {
657 Value *callOptimizer(Function *Callee, CallInst *CI,
658 IRBuilder<> &B) override {
659 // Verify the "strcpy" function prototype.
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 2 ||
662 FT->getReturnType() != FT->getParamType(0) ||
663 FT->getParamType(0) != FT->getParamType(1) ||
664 FT->getParamType(0) != B.getInt8PtrTy())
667 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
668 if (Dst == Src) // strcpy(x,x) -> x
671 // These optimizations require DataLayout.
672 if (!DL) return nullptr;
674 // See if we can get the length of the input string.
675 uint64_t Len = GetStringLength(Src);
676 if (Len == 0) return nullptr;
678 // We have enough information to now generate the memcpy call to do the
679 // copy for us. Make a memcpy to copy the nul byte with align = 1.
680 B.CreateMemCpy(Dst, Src,
681 ConstantInt::get(DL->getIntPtrType(*Context), Len), 1);
686 struct StpCpyOpt: public LibCallOptimization {
687 Value *callOptimizer(Function *Callee, CallInst *CI,
688 IRBuilder<> &B) override {
689 // Verify the "stpcpy" function prototype.
690 FunctionType *FT = Callee->getFunctionType();
691 if (FT->getNumParams() != 2 ||
692 FT->getReturnType() != FT->getParamType(0) ||
693 FT->getParamType(0) != FT->getParamType(1) ||
694 FT->getParamType(0) != B.getInt8PtrTy())
697 // These optimizations require DataLayout.
698 if (!DL) return nullptr;
700 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
701 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
702 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
703 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
706 // See if we can get the length of the input string.
707 uint64_t Len = GetStringLength(Src);
708 if (Len == 0) return nullptr;
710 Type *PT = FT->getParamType(0);
711 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
712 Value *DstEnd = B.CreateGEP(Dst,
713 ConstantInt::get(DL->getIntPtrType(PT),
716 // We have enough information to now generate the memcpy call to do the
717 // copy for us. Make a memcpy to copy the nul byte with align = 1.
718 B.CreateMemCpy(Dst, Src, LenV, 1);
723 struct StrNCpyOpt : public LibCallOptimization {
724 Value *callOptimizer(Function *Callee, CallInst *CI,
725 IRBuilder<> &B) override {
726 FunctionType *FT = Callee->getFunctionType();
727 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
728 FT->getParamType(0) != FT->getParamType(1) ||
729 FT->getParamType(0) != B.getInt8PtrTy() ||
730 !FT->getParamType(2)->isIntegerTy())
733 Value *Dst = CI->getArgOperand(0);
734 Value *Src = CI->getArgOperand(1);
735 Value *LenOp = CI->getArgOperand(2);
737 // See if we can get the length of the input string.
738 uint64_t SrcLen = GetStringLength(Src);
739 if (SrcLen == 0) return nullptr;
743 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
744 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
749 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
750 Len = LengthArg->getZExtValue();
754 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
756 // These optimizations require DataLayout.
757 if (!DL) return nullptr;
759 // Let strncpy handle the zero padding
760 if (Len > SrcLen+1) return nullptr;
762 Type *PT = FT->getParamType(0);
763 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
764 B.CreateMemCpy(Dst, Src,
765 ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
771 struct StrLenOpt : public LibCallOptimization {
772 bool ignoreCallingConv() override { return true; }
773 Value *callOptimizer(Function *Callee, CallInst *CI,
774 IRBuilder<> &B) override {
775 FunctionType *FT = Callee->getFunctionType();
776 if (FT->getNumParams() != 1 ||
777 FT->getParamType(0) != B.getInt8PtrTy() ||
778 !FT->getReturnType()->isIntegerTy())
781 Value *Src = CI->getArgOperand(0);
783 // Constant folding: strlen("xyz") -> 3
784 if (uint64_t Len = GetStringLength(Src))
785 return ConstantInt::get(CI->getType(), Len-1);
787 // strlen(x?"foo":"bars") --> x ? 3 : 4
788 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
789 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
790 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
791 if (LenTrue && LenFalse) {
792 Context->emitOptimizationRemark(
793 "simplify-libcalls", *Caller, SI->getDebugLoc(),
794 "folded strlen(select) to select of constants");
795 return B.CreateSelect(SI->getCondition(),
796 ConstantInt::get(CI->getType(), LenTrue-1),
797 ConstantInt::get(CI->getType(), LenFalse-1));
801 // strlen(x) != 0 --> *x != 0
802 // strlen(x) == 0 --> *x == 0
803 if (isOnlyUsedInZeroEqualityComparison(CI))
804 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
810 struct StrPBrkOpt : public LibCallOptimization {
811 Value *callOptimizer(Function *Callee, CallInst *CI,
812 IRBuilder<> &B) override {
813 FunctionType *FT = Callee->getFunctionType();
814 if (FT->getNumParams() != 2 ||
815 FT->getParamType(0) != B.getInt8PtrTy() ||
816 FT->getParamType(1) != FT->getParamType(0) ||
817 FT->getReturnType() != FT->getParamType(0))
821 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
822 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
824 // strpbrk(s, "") -> NULL
825 // strpbrk("", s) -> NULL
826 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
827 return Constant::getNullValue(CI->getType());
830 if (HasS1 && HasS2) {
831 size_t I = S1.find_first_of(S2);
832 if (I == StringRef::npos) // No match.
833 return Constant::getNullValue(CI->getType());
835 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
838 // strpbrk(s, "a") -> strchr(s, 'a')
839 if (DL && HasS2 && S2.size() == 1)
840 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
846 struct StrToOpt : public LibCallOptimization {
847 Value *callOptimizer(Function *Callee, CallInst *CI,
848 IRBuilder<> &B) override {
849 FunctionType *FT = Callee->getFunctionType();
850 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
851 !FT->getParamType(0)->isPointerTy() ||
852 !FT->getParamType(1)->isPointerTy())
855 Value *EndPtr = CI->getArgOperand(1);
856 if (isa<ConstantPointerNull>(EndPtr)) {
857 // With a null EndPtr, this function won't capture the main argument.
858 // It would be readonly too, except that it still may write to errno.
859 CI->addAttribute(1, Attribute::NoCapture);
866 struct StrSpnOpt : public LibCallOptimization {
867 Value *callOptimizer(Function *Callee, CallInst *CI,
868 IRBuilder<> &B) override {
869 FunctionType *FT = Callee->getFunctionType();
870 if (FT->getNumParams() != 2 ||
871 FT->getParamType(0) != B.getInt8PtrTy() ||
872 FT->getParamType(1) != FT->getParamType(0) ||
873 !FT->getReturnType()->isIntegerTy())
877 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
878 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
880 // strspn(s, "") -> 0
881 // strspn("", s) -> 0
882 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
883 return Constant::getNullValue(CI->getType());
886 if (HasS1 && HasS2) {
887 size_t Pos = S1.find_first_not_of(S2);
888 if (Pos == StringRef::npos) Pos = S1.size();
889 return ConstantInt::get(CI->getType(), Pos);
896 struct StrCSpnOpt : public LibCallOptimization {
897 Value *callOptimizer(Function *Callee, CallInst *CI,
898 IRBuilder<> &B) override {
899 FunctionType *FT = Callee->getFunctionType();
900 if (FT->getNumParams() != 2 ||
901 FT->getParamType(0) != B.getInt8PtrTy() ||
902 FT->getParamType(1) != FT->getParamType(0) ||
903 !FT->getReturnType()->isIntegerTy())
907 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
908 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
910 // strcspn("", s) -> 0
911 if (HasS1 && S1.empty())
912 return Constant::getNullValue(CI->getType());
915 if (HasS1 && HasS2) {
916 size_t Pos = S1.find_first_of(S2);
917 if (Pos == StringRef::npos) Pos = S1.size();
918 return ConstantInt::get(CI->getType(), Pos);
921 // strcspn(s, "") -> strlen(s)
922 if (DL && HasS2 && S2.empty())
923 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
929 struct StrStrOpt : public LibCallOptimization {
930 Value *callOptimizer(Function *Callee, CallInst *CI,
931 IRBuilder<> &B) override {
932 FunctionType *FT = Callee->getFunctionType();
933 if (FT->getNumParams() != 2 ||
934 !FT->getParamType(0)->isPointerTy() ||
935 !FT->getParamType(1)->isPointerTy() ||
936 !FT->getReturnType()->isPointerTy())
939 // fold strstr(x, x) -> x.
940 if (CI->getArgOperand(0) == CI->getArgOperand(1))
941 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
943 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
944 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
945 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
948 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
952 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
953 ICmpInst *Old = cast<ICmpInst>(*UI++);
954 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
955 ConstantInt::getNullValue(StrNCmp->getType()),
957 LCS->replaceAllUsesWith(Old, Cmp);
962 // See if either input string is a constant string.
963 StringRef SearchStr, ToFindStr;
964 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
965 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
967 // fold strstr(x, "") -> x.
968 if (HasStr2 && ToFindStr.empty())
969 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
971 // If both strings are known, constant fold it.
972 if (HasStr1 && HasStr2) {
973 size_t Offset = SearchStr.find(ToFindStr);
975 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
976 return Constant::getNullValue(CI->getType());
978 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
979 Value *Result = CastToCStr(CI->getArgOperand(0), B);
980 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
981 return B.CreateBitCast(Result, CI->getType());
984 // fold strstr(x, "y") -> strchr(x, 'y').
985 if (HasStr2 && ToFindStr.size() == 1) {
986 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
987 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
993 struct MemCmpOpt : public LibCallOptimization {
994 Value *callOptimizer(Function *Callee, CallInst *CI,
995 IRBuilder<> &B) override {
996 FunctionType *FT = Callee->getFunctionType();
997 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
998 !FT->getParamType(1)->isPointerTy() ||
999 !FT->getReturnType()->isIntegerTy(32))
1002 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1004 if (LHS == RHS) // memcmp(s,s,x) -> 0
1005 return Constant::getNullValue(CI->getType());
1007 // Make sure we have a constant length.
1008 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1009 if (!LenC) return nullptr;
1010 uint64_t Len = LenC->getZExtValue();
1012 if (Len == 0) // memcmp(s1,s2,0) -> 0
1013 return Constant::getNullValue(CI->getType());
1015 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1017 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
1018 CI->getType(), "lhsv");
1019 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
1020 CI->getType(), "rhsv");
1021 return B.CreateSub(LHSV, RHSV, "chardiff");
1024 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1025 StringRef LHSStr, RHSStr;
1026 if (getConstantStringInfo(LHS, LHSStr) &&
1027 getConstantStringInfo(RHS, RHSStr)) {
1028 // Make sure we're not reading out-of-bounds memory.
1029 if (Len > LHSStr.size() || Len > RHSStr.size())
1031 // Fold the memcmp and normalize the result. This way we get consistent
1032 // results across multiple platforms.
1034 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1039 return ConstantInt::get(CI->getType(), Ret);
1046 struct MemCpyOpt : public LibCallOptimization {
1047 Value *callOptimizer(Function *Callee, CallInst *CI,
1048 IRBuilder<> &B) override {
1049 // These optimizations require DataLayout.
1050 if (!DL) return nullptr;
1052 FunctionType *FT = Callee->getFunctionType();
1053 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1054 !FT->getParamType(0)->isPointerTy() ||
1055 !FT->getParamType(1)->isPointerTy() ||
1056 FT->getParamType(2) != DL->getIntPtrType(*Context))
1059 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1060 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1061 CI->getArgOperand(2), 1);
1062 return CI->getArgOperand(0);
1066 struct MemMoveOpt : public LibCallOptimization {
1067 Value *callOptimizer(Function *Callee, CallInst *CI,
1068 IRBuilder<> &B) override {
1069 // These optimizations require DataLayout.
1070 if (!DL) return nullptr;
1072 FunctionType *FT = Callee->getFunctionType();
1073 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1074 !FT->getParamType(0)->isPointerTy() ||
1075 !FT->getParamType(1)->isPointerTy() ||
1076 FT->getParamType(2) != DL->getIntPtrType(*Context))
1079 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1080 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1081 CI->getArgOperand(2), 1);
1082 return CI->getArgOperand(0);
1086 struct MemSetOpt : public LibCallOptimization {
1087 Value *callOptimizer(Function *Callee, CallInst *CI,
1088 IRBuilder<> &B) override {
1089 // These optimizations require DataLayout.
1090 if (!DL) return nullptr;
1092 FunctionType *FT = Callee->getFunctionType();
1093 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1094 !FT->getParamType(0)->isPointerTy() ||
1095 !FT->getParamType(1)->isIntegerTy() ||
1096 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
1099 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1100 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1101 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1102 return CI->getArgOperand(0);
1106 //===----------------------------------------------------------------------===//
1107 // Math Library Optimizations
1108 //===----------------------------------------------------------------------===//
1110 //===----------------------------------------------------------------------===//
1111 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1113 struct UnaryDoubleFPOpt : public LibCallOptimization {
1115 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1116 Value *callOptimizer(Function *Callee, CallInst *CI,
1117 IRBuilder<> &B) override {
1118 FunctionType *FT = Callee->getFunctionType();
1119 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1120 !FT->getParamType(0)->isDoubleTy())
1124 // Check if all the uses for function like 'sin' are converted to float.
1125 for (User *U : CI->users()) {
1126 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1127 if (!Cast || !Cast->getType()->isFloatTy())
1132 // If this is something like 'floor((double)floatval)', convert to floorf.
1133 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1134 if (!Cast || !Cast->getOperand(0)->getType()->isFloatTy())
1137 // floor((double)floatval) -> (double)floorf(floatval)
1138 Value *V = Cast->getOperand(0);
1139 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1140 return B.CreateFPExt(V, B.getDoubleTy());
1144 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1145 struct BinaryDoubleFPOpt : public LibCallOptimization {
1147 BinaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
1148 Value *callOptimizer(Function *Callee, CallInst *CI,
1149 IRBuilder<> &B) override {
1150 FunctionType *FT = Callee->getFunctionType();
1151 // Just make sure this has 2 arguments of the same FP type, which match the
1153 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1154 FT->getParamType(0) != FT->getParamType(1) ||
1155 !FT->getParamType(0)->isFloatingPointTy())
1159 // Check if all the uses for function like 'fmin/fmax' are converted to
1161 for (User *U : CI->users()) {
1162 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1163 if (!Cast || !Cast->getType()->isFloatTy())
1168 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1169 // we convert it to fminf.
1170 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1171 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1172 if (!Cast1 || !Cast1->getOperand(0)->getType()->isFloatTy() ||
1173 !Cast2 || !Cast2->getOperand(0)->getType()->isFloatTy())
1176 // fmin((double)floatval1, (double)floatval2)
1177 // -> (double)fmin(floatval1, floatval2)
1179 Value *V1 = Cast1->getOperand(0);
1180 Value *V2 = Cast2->getOperand(0);
1181 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1182 Callee->getAttributes());
1183 return B.CreateFPExt(V, B.getDoubleTy());
1187 struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1188 bool UnsafeFPShrink;
1189 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1190 this->UnsafeFPShrink = UnsafeFPShrink;
1194 struct CosOpt : public UnsafeFPLibCallOptimization {
1195 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1196 Value *callOptimizer(Function *Callee, CallInst *CI,
1197 IRBuilder<> &B) override {
1198 Value *Ret = nullptr;
1199 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1200 TLI->has(LibFunc::cosf)) {
1201 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1202 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1205 FunctionType *FT = Callee->getFunctionType();
1206 // Just make sure this has 1 argument of FP type, which matches the
1208 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1209 !FT->getParamType(0)->isFloatingPointTy())
1212 // cos(-x) -> cos(x)
1213 Value *Op1 = CI->getArgOperand(0);
1214 if (BinaryOperator::isFNeg(Op1)) {
1215 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1216 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1222 struct PowOpt : public UnsafeFPLibCallOptimization {
1223 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1224 Value *callOptimizer(Function *Callee, CallInst *CI,
1225 IRBuilder<> &B) override {
1226 Value *Ret = nullptr;
1227 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1228 TLI->has(LibFunc::powf)) {
1229 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1230 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1233 FunctionType *FT = Callee->getFunctionType();
1234 // Just make sure this has 2 arguments of the same FP type, which match the
1236 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1237 FT->getParamType(0) != FT->getParamType(1) ||
1238 !FT->getParamType(0)->isFloatingPointTy())
1241 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1242 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1243 // pow(1.0, x) -> 1.0
1244 if (Op1C->isExactlyValue(1.0))
1246 // pow(2.0, x) -> exp2(x)
1247 if (Op1C->isExactlyValue(2.0) &&
1248 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1250 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1251 // pow(10.0, x) -> exp10(x)
1252 if (Op1C->isExactlyValue(10.0) &&
1253 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1255 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1256 Callee->getAttributes());
1259 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1260 if (!Op2C) return Ret;
1262 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1263 return ConstantFP::get(CI->getType(), 1.0);
1265 if (Op2C->isExactlyValue(0.5) &&
1266 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1268 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1270 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1271 // This is faster than calling pow, and still handles negative zero
1272 // and negative infinity correctly.
1273 // TODO: In fast-math mode, this could be just sqrt(x).
1274 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1275 Value *Inf = ConstantFP::getInfinity(CI->getType());
1276 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1277 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1278 Callee->getAttributes());
1279 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1280 Callee->getAttributes());
1281 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1282 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1286 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1288 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1289 return B.CreateFMul(Op1, Op1, "pow2");
1290 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1291 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1297 struct Exp2Opt : public UnsafeFPLibCallOptimization {
1298 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
1299 Value *callOptimizer(Function *Callee, CallInst *CI,
1300 IRBuilder<> &B) override {
1301 Value *Ret = nullptr;
1302 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1303 TLI->has(LibFunc::exp2f)) {
1304 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1305 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1308 FunctionType *FT = Callee->getFunctionType();
1309 // Just make sure this has 1 argument of FP type, which matches the
1311 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1312 !FT->getParamType(0)->isFloatingPointTy())
1315 Value *Op = CI->getArgOperand(0);
1316 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1317 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1318 LibFunc::Func LdExp = LibFunc::ldexpl;
1319 if (Op->getType()->isFloatTy())
1320 LdExp = LibFunc::ldexpf;
1321 else if (Op->getType()->isDoubleTy())
1322 LdExp = LibFunc::ldexp;
1324 if (TLI->has(LdExp)) {
1325 Value *LdExpArg = nullptr;
1326 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1327 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1328 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1329 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1330 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1331 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1335 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1336 if (!Op->getType()->isFloatTy())
1337 One = ConstantExpr::getFPExtend(One, Op->getType());
1339 Module *M = Caller->getParent();
1341 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1342 Op->getType(), B.getInt32Ty(), NULL);
1343 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1344 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1345 CI->setCallingConv(F->getCallingConv());
1354 struct SinCosPiOpt : public LibCallOptimization {
1357 Value *callOptimizer(Function *Callee, CallInst *CI,
1358 IRBuilder<> &B) override {
1359 // Make sure the prototype is as expected, otherwise the rest of the
1360 // function is probably invalid and likely to abort.
1361 if (!isTrigLibCall(CI))
1364 Value *Arg = CI->getArgOperand(0);
1365 SmallVector<CallInst *, 1> SinCalls;
1366 SmallVector<CallInst *, 1> CosCalls;
1367 SmallVector<CallInst *, 1> SinCosCalls;
1369 bool IsFloat = Arg->getType()->isFloatTy();
1371 // Look for all compatible sinpi, cospi and sincospi calls with the same
1372 // argument. If there are enough (in some sense) we can make the
1374 for (User *U : Arg->users())
1375 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1378 // It's only worthwhile if both sinpi and cospi are actually used.
1379 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1382 Value *Sin, *Cos, *SinCos;
1383 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1386 replaceTrigInsts(SinCalls, Sin);
1387 replaceTrigInsts(CosCalls, Cos);
1388 replaceTrigInsts(SinCosCalls, SinCos);
1393 bool isTrigLibCall(CallInst *CI) {
1394 Function *Callee = CI->getCalledFunction();
1395 FunctionType *FT = Callee->getFunctionType();
1397 // We can only hope to do anything useful if we can ignore things like errno
1398 // and floating-point exceptions.
1399 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1400 CI->hasFnAttr(Attribute::ReadNone);
1402 // Other than that we need float(float) or double(double)
1403 return AttributesSafe && FT->getNumParams() == 1 &&
1404 FT->getReturnType() == FT->getParamType(0) &&
1405 (FT->getParamType(0)->isFloatTy() ||
1406 FT->getParamType(0)->isDoubleTy());
1409 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1410 SmallVectorImpl<CallInst *> &SinCalls,
1411 SmallVectorImpl<CallInst *> &CosCalls,
1412 SmallVectorImpl<CallInst *> &SinCosCalls) {
1413 CallInst *CI = dyn_cast<CallInst>(Val);
1418 Function *Callee = CI->getCalledFunction();
1419 StringRef FuncName = Callee->getName();
1421 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1426 if (Func == LibFunc::sinpif)
1427 SinCalls.push_back(CI);
1428 else if (Func == LibFunc::cospif)
1429 CosCalls.push_back(CI);
1430 else if (Func == LibFunc::sincospif_stret)
1431 SinCosCalls.push_back(CI);
1433 if (Func == LibFunc::sinpi)
1434 SinCalls.push_back(CI);
1435 else if (Func == LibFunc::cospi)
1436 CosCalls.push_back(CI);
1437 else if (Func == LibFunc::sincospi_stret)
1438 SinCosCalls.push_back(CI);
1442 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1443 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1446 LCS->replaceAllUsesWith(*I, Res);
1450 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1451 bool UseFloat, Value *&Sin, Value *&Cos,
1453 Type *ArgTy = Arg->getType();
1457 Triple T(OrigCallee->getParent()->getTargetTriple());
1459 Name = "__sincospif_stret";
1461 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1462 // x86_64 can't use {float, float} since that would be returned in both
1463 // xmm0 and xmm1, which isn't what a real struct would do.
1464 ResTy = T.getArch() == Triple::x86_64
1465 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1466 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1468 Name = "__sincospi_stret";
1469 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1472 Module *M = OrigCallee->getParent();
1473 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1474 ResTy, ArgTy, NULL);
1476 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1477 // If the argument is an instruction, it must dominate all uses so put our
1478 // sincos call there.
1479 BasicBlock::iterator Loc = ArgInst;
1480 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1482 // Otherwise (e.g. for a constant) the beginning of the function is as
1483 // good a place as any.
1484 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1485 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1488 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1490 if (SinCos->getType()->isStructTy()) {
1491 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1492 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1494 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1496 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1503 //===----------------------------------------------------------------------===//
1504 // Integer Library Call Optimizations
1505 //===----------------------------------------------------------------------===//
1507 struct FFSOpt : public LibCallOptimization {
1508 Value *callOptimizer(Function *Callee, CallInst *CI,
1509 IRBuilder<> &B) override {
1510 FunctionType *FT = Callee->getFunctionType();
1511 // Just make sure this has 2 arguments of the same FP type, which match the
1513 if (FT->getNumParams() != 1 ||
1514 !FT->getReturnType()->isIntegerTy(32) ||
1515 !FT->getParamType(0)->isIntegerTy())
1518 Value *Op = CI->getArgOperand(0);
1521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1522 if (CI->isZero()) // ffs(0) -> 0.
1523 return B.getInt32(0);
1524 // ffs(c) -> cttz(c)+1
1525 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1528 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1529 Type *ArgType = Op->getType();
1530 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1531 Intrinsic::cttz, ArgType);
1532 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1533 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1534 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1536 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1537 return B.CreateSelect(Cond, V, B.getInt32(0));
1541 struct AbsOpt : public LibCallOptimization {
1542 bool ignoreCallingConv() override { return true; }
1543 Value *callOptimizer(Function *Callee, CallInst *CI,
1544 IRBuilder<> &B) override {
1545 FunctionType *FT = Callee->getFunctionType();
1546 // We require integer(integer) where the types agree.
1547 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1548 FT->getParamType(0) != FT->getReturnType())
1551 // abs(x) -> x >s -1 ? x : -x
1552 Value *Op = CI->getArgOperand(0);
1553 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1555 Value *Neg = B.CreateNeg(Op, "neg");
1556 return B.CreateSelect(Pos, Op, Neg);
1560 struct IsDigitOpt : public LibCallOptimization {
1561 Value *callOptimizer(Function *Callee, CallInst *CI,
1562 IRBuilder<> &B) override {
1563 FunctionType *FT = Callee->getFunctionType();
1564 // We require integer(i32)
1565 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1566 !FT->getParamType(0)->isIntegerTy(32))
1569 // isdigit(c) -> (c-'0') <u 10
1570 Value *Op = CI->getArgOperand(0);
1571 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1572 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1573 return B.CreateZExt(Op, CI->getType());
1577 struct IsAsciiOpt : public LibCallOptimization {
1578 Value *callOptimizer(Function *Callee, CallInst *CI,
1579 IRBuilder<> &B) override {
1580 FunctionType *FT = Callee->getFunctionType();
1581 // We require integer(i32)
1582 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1583 !FT->getParamType(0)->isIntegerTy(32))
1586 // isascii(c) -> c <u 128
1587 Value *Op = CI->getArgOperand(0);
1588 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1589 return B.CreateZExt(Op, CI->getType());
1593 struct ToAsciiOpt : public LibCallOptimization {
1594 Value *callOptimizer(Function *Callee, CallInst *CI,
1595 IRBuilder<> &B) override {
1596 FunctionType *FT = Callee->getFunctionType();
1597 // We require i32(i32)
1598 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1599 !FT->getParamType(0)->isIntegerTy(32))
1602 // toascii(c) -> c & 0x7f
1603 return B.CreateAnd(CI->getArgOperand(0),
1604 ConstantInt::get(CI->getType(),0x7F));
1608 //===----------------------------------------------------------------------===//
1609 // Formatting and IO Library Call Optimizations
1610 //===----------------------------------------------------------------------===//
1612 struct ErrorReportingOpt : public LibCallOptimization {
1613 ErrorReportingOpt(int S = -1) : StreamArg(S) {}
1615 Value *callOptimizer(Function *Callee, CallInst *CI,
1616 IRBuilder<> &) override {
1617 // Error reporting calls should be cold, mark them as such.
1618 // This applies even to non-builtin calls: it is only a hint and applies to
1619 // functions that the frontend might not understand as builtins.
1621 // This heuristic was suggested in:
1622 // Improving Static Branch Prediction in a Compiler
1623 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1624 // Proceedings of PACT'98, Oct. 1998, IEEE
1626 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) {
1627 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1634 bool isReportingError(Function *Callee, CallInst *CI) {
1635 if (!ColdErrorCalls)
1638 if (!Callee || !Callee->isDeclaration())
1644 // These functions might be considered cold, but only if their stream
1645 // argument is stderr.
1647 if (StreamArg >= (int) CI->getNumArgOperands())
1649 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1652 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1653 if (!GV || !GV->isDeclaration())
1655 return GV->getName() == "stderr";
1661 struct PrintFOpt : public LibCallOptimization {
1662 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1664 // Check for a fixed format string.
1665 StringRef FormatStr;
1666 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1669 // Empty format string -> noop.
1670 if (FormatStr.empty()) // Tolerate printf's declared void.
1671 return CI->use_empty() ? (Value*)CI :
1672 ConstantInt::get(CI->getType(), 0);
1674 // Do not do any of the following transformations if the printf return value
1675 // is used, in general the printf return value is not compatible with either
1676 // putchar() or puts().
1677 if (!CI->use_empty())
1680 // printf("x") -> putchar('x'), even for '%'.
1681 if (FormatStr.size() == 1) {
1682 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1683 if (CI->use_empty() || !Res) return Res;
1684 return B.CreateIntCast(Res, CI->getType(), true);
1687 // printf("foo\n") --> puts("foo")
1688 if (FormatStr[FormatStr.size()-1] == '\n' &&
1689 FormatStr.find('%') == StringRef::npos) { // No format characters.
1690 // Create a string literal with no \n on it. We expect the constant merge
1691 // pass to be run after this pass, to merge duplicate strings.
1692 FormatStr = FormatStr.drop_back();
1693 Value *GV = B.CreateGlobalString(FormatStr, "str");
1694 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1695 return (CI->use_empty() || !NewCI) ?
1697 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1700 // Optimize specific format strings.
1701 // printf("%c", chr) --> putchar(chr)
1702 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1703 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1704 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1706 if (CI->use_empty() || !Res) return Res;
1707 return B.CreateIntCast(Res, CI->getType(), true);
1710 // printf("%s\n", str) --> puts(str)
1711 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1712 CI->getArgOperand(1)->getType()->isPointerTy()) {
1713 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1718 Value *callOptimizer(Function *Callee, CallInst *CI,
1719 IRBuilder<> &B) override {
1720 // Require one fixed pointer argument and an integer/void result.
1721 FunctionType *FT = Callee->getFunctionType();
1722 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1723 !(FT->getReturnType()->isIntegerTy() ||
1724 FT->getReturnType()->isVoidTy()))
1727 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1731 // printf(format, ...) -> iprintf(format, ...) if no floating point
1733 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1734 Module *M = B.GetInsertBlock()->getParent()->getParent();
1735 Constant *IPrintFFn =
1736 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1737 CallInst *New = cast<CallInst>(CI->clone());
1738 New->setCalledFunction(IPrintFFn);
1746 struct SPrintFOpt : public LibCallOptimization {
1747 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1749 // Check for a fixed format string.
1750 StringRef FormatStr;
1751 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1754 // If we just have a format string (nothing else crazy) transform it.
1755 if (CI->getNumArgOperands() == 2) {
1756 // Make sure there's no % in the constant array. We could try to handle
1757 // %% -> % in the future if we cared.
1758 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1759 if (FormatStr[i] == '%')
1760 return nullptr; // we found a format specifier, bail out.
1762 // These optimizations require DataLayout.
1763 if (!DL) return nullptr;
1765 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1766 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1767 ConstantInt::get(DL->getIntPtrType(*Context), // Copy the
1768 FormatStr.size() + 1), 1); // nul byte.
1769 return ConstantInt::get(CI->getType(), FormatStr.size());
1772 // The remaining optimizations require the format string to be "%s" or "%c"
1773 // and have an extra operand.
1774 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1775 CI->getNumArgOperands() < 3)
1778 // Decode the second character of the format string.
1779 if (FormatStr[1] == 'c') {
1780 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1781 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return nullptr;
1782 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1783 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1784 B.CreateStore(V, Ptr);
1785 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1786 B.CreateStore(B.getInt8(0), Ptr);
1788 return ConstantInt::get(CI->getType(), 1);
1791 if (FormatStr[1] == 's') {
1792 // These optimizations require DataLayout.
1793 if (!DL) return nullptr;
1795 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1796 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return nullptr;
1798 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1801 Value *IncLen = B.CreateAdd(Len,
1802 ConstantInt::get(Len->getType(), 1),
1804 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1806 // The sprintf result is the unincremented number of bytes in the string.
1807 return B.CreateIntCast(Len, CI->getType(), false);
1812 Value *callOptimizer(Function *Callee, CallInst *CI,
1813 IRBuilder<> &B) override {
1814 // Require two fixed pointer arguments and an integer result.
1815 FunctionType *FT = Callee->getFunctionType();
1816 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1817 !FT->getParamType(1)->isPointerTy() ||
1818 !FT->getReturnType()->isIntegerTy())
1821 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1825 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1827 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1828 Module *M = B.GetInsertBlock()->getParent()->getParent();
1829 Constant *SIPrintFFn =
1830 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1831 CallInst *New = cast<CallInst>(CI->clone());
1832 New->setCalledFunction(SIPrintFFn);
1840 struct FPrintFOpt : public LibCallOptimization {
1841 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1843 ErrorReportingOpt ER(/* StreamArg = */ 0);
1844 (void) ER.callOptimizer(Callee, CI, B);
1846 // All the optimizations depend on the format string.
1847 StringRef FormatStr;
1848 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1851 // Do not do any of the following transformations if the fprintf return
1852 // value is used, in general the fprintf return value is not compatible
1853 // with fwrite(), fputc() or fputs().
1854 if (!CI->use_empty())
1857 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1858 if (CI->getNumArgOperands() == 2) {
1859 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1860 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1861 return nullptr; // We found a format specifier.
1863 // These optimizations require DataLayout.
1864 if (!DL) return nullptr;
1866 return EmitFWrite(CI->getArgOperand(1),
1867 ConstantInt::get(DL->getIntPtrType(*Context),
1869 CI->getArgOperand(0), B, DL, TLI);
1872 // The remaining optimizations require the format string to be "%s" or "%c"
1873 // and have an extra operand.
1874 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1875 CI->getNumArgOperands() < 3)
1878 // Decode the second character of the format string.
1879 if (FormatStr[1] == 'c') {
1880 // fprintf(F, "%c", chr) --> fputc(chr, F)
1881 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return nullptr;
1882 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1885 if (FormatStr[1] == 's') {
1886 // fprintf(F, "%s", str) --> fputs(str, F)
1887 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1889 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1894 Value *callOptimizer(Function *Callee, CallInst *CI,
1895 IRBuilder<> &B) override {
1896 // Require two fixed paramters as pointers and integer result.
1897 FunctionType *FT = Callee->getFunctionType();
1898 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1899 !FT->getParamType(1)->isPointerTy() ||
1900 !FT->getReturnType()->isIntegerTy())
1903 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1907 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1908 // floating point arguments.
1909 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1910 Module *M = B.GetInsertBlock()->getParent()->getParent();
1911 Constant *FIPrintFFn =
1912 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1913 CallInst *New = cast<CallInst>(CI->clone());
1914 New->setCalledFunction(FIPrintFFn);
1922 struct FWriteOpt : public LibCallOptimization {
1923 Value *callOptimizer(Function *Callee, CallInst *CI,
1924 IRBuilder<> &B) override {
1925 ErrorReportingOpt ER(/* StreamArg = */ 3);
1926 (void) ER.callOptimizer(Callee, CI, B);
1928 // Require a pointer, an integer, an integer, a pointer, returning integer.
1929 FunctionType *FT = Callee->getFunctionType();
1930 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1931 !FT->getParamType(1)->isIntegerTy() ||
1932 !FT->getParamType(2)->isIntegerTy() ||
1933 !FT->getParamType(3)->isPointerTy() ||
1934 !FT->getReturnType()->isIntegerTy())
1937 // Get the element size and count.
1938 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1939 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1940 if (!SizeC || !CountC) return nullptr;
1941 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1943 // If this is writing zero records, remove the call (it's a noop).
1945 return ConstantInt::get(CI->getType(), 0);
1947 // If this is writing one byte, turn it into fputc.
1948 // This optimisation is only valid, if the return value is unused.
1949 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1950 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1951 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1952 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1959 struct FPutsOpt : public LibCallOptimization {
1960 Value *callOptimizer(Function *Callee, CallInst *CI,
1961 IRBuilder<> &B) override {
1962 ErrorReportingOpt ER(/* StreamArg = */ 1);
1963 (void) ER.callOptimizer(Callee, CI, B);
1965 // These optimizations require DataLayout.
1966 if (!DL) return nullptr;
1968 // Require two pointers. Also, we can't optimize if return value is used.
1969 FunctionType *FT = Callee->getFunctionType();
1970 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1971 !FT->getParamType(1)->isPointerTy() ||
1975 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1976 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1977 if (!Len) return nullptr;
1978 // Known to have no uses (see above).
1979 return EmitFWrite(CI->getArgOperand(0),
1980 ConstantInt::get(DL->getIntPtrType(*Context), Len-1),
1981 CI->getArgOperand(1), B, DL, TLI);
1985 struct PutsOpt : public LibCallOptimization {
1986 Value *callOptimizer(Function *Callee, CallInst *CI,
1987 IRBuilder<> &B) override {
1988 // Require one fixed pointer argument and an integer/void result.
1989 FunctionType *FT = Callee->getFunctionType();
1990 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1991 !(FT->getReturnType()->isIntegerTy() ||
1992 FT->getReturnType()->isVoidTy()))
1995 // Check for a constant string.
1997 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2000 if (Str.empty() && CI->use_empty()) {
2001 // puts("") -> putchar('\n')
2002 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
2003 if (CI->use_empty() || !Res) return Res;
2004 return B.CreateIntCast(Res, CI->getType(), true);
2011 } // End anonymous namespace.
2015 class LibCallSimplifierImpl {
2016 const DataLayout *DL;
2017 const TargetLibraryInfo *TLI;
2018 const LibCallSimplifier *LCS;
2019 bool UnsafeFPShrink;
2021 // Math library call optimizations.
2026 LibCallSimplifierImpl(const DataLayout *DL, const TargetLibraryInfo *TLI,
2027 const LibCallSimplifier *LCS,
2028 bool UnsafeFPShrink = false)
2029 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
2033 this->UnsafeFPShrink = UnsafeFPShrink;
2036 Value *optimizeCall(CallInst *CI);
2037 LibCallOptimization *lookupOptimization(CallInst *CI);
2038 bool hasFloatVersion(StringRef FuncName);
2041 bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
2043 SmallString<20> FloatFuncName = FuncName;
2044 FloatFuncName += 'f';
2045 if (TLI->getLibFunc(FloatFuncName, Func))
2046 return TLI->has(Func);
2050 // Fortified library call optimizations.
2051 static MemCpyChkOpt MemCpyChk;
2052 static MemMoveChkOpt MemMoveChk;
2053 static MemSetChkOpt MemSetChk;
2054 static StrCpyChkOpt StrCpyChk;
2055 static StpCpyChkOpt StpCpyChk;
2056 static StrNCpyChkOpt StrNCpyChk;
2058 // String library call optimizations.
2059 static StrCatOpt StrCat;
2060 static StrNCatOpt StrNCat;
2061 static StrChrOpt StrChr;
2062 static StrRChrOpt StrRChr;
2063 static StrCmpOpt StrCmp;
2064 static StrNCmpOpt StrNCmp;
2065 static StrCpyOpt StrCpy;
2066 static StpCpyOpt StpCpy;
2067 static StrNCpyOpt StrNCpy;
2068 static StrLenOpt StrLen;
2069 static StrPBrkOpt StrPBrk;
2070 static StrToOpt StrTo;
2071 static StrSpnOpt StrSpn;
2072 static StrCSpnOpt StrCSpn;
2073 static StrStrOpt StrStr;
2075 // Memory library call optimizations.
2076 static MemCmpOpt MemCmp;
2077 static MemCpyOpt MemCpy;
2078 static MemMoveOpt MemMove;
2079 static MemSetOpt MemSet;
2081 // Math library call optimizations.
2082 static UnaryDoubleFPOpt UnaryDoubleFP(false);
2083 static BinaryDoubleFPOpt BinaryDoubleFP(false);
2084 static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
2085 static SinCosPiOpt SinCosPi;
2087 // Integer library call optimizations.
2090 static IsDigitOpt IsDigit;
2091 static IsAsciiOpt IsAscii;
2092 static ToAsciiOpt ToAscii;
2094 // Formatting and IO library call optimizations.
2095 static ErrorReportingOpt ErrorReporting;
2096 static ErrorReportingOpt ErrorReporting0(0);
2097 static ErrorReportingOpt ErrorReporting1(1);
2098 static PrintFOpt PrintF;
2099 static SPrintFOpt SPrintF;
2100 static FPrintFOpt FPrintF;
2101 static FWriteOpt FWrite;
2102 static FPutsOpt FPuts;
2103 static PutsOpt Puts;
2105 LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
2107 Function *Callee = CI->getCalledFunction();
2108 StringRef FuncName = Callee->getName();
2110 // Next check for intrinsics.
2111 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2112 switch (II->getIntrinsicID()) {
2113 case Intrinsic::pow:
2115 case Intrinsic::exp2:
2122 // Then check for known library functions.
2123 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2125 case LibFunc::strcat:
2127 case LibFunc::strncat:
2129 case LibFunc::strchr:
2131 case LibFunc::strrchr:
2133 case LibFunc::strcmp:
2135 case LibFunc::strncmp:
2137 case LibFunc::strcpy:
2139 case LibFunc::stpcpy:
2141 case LibFunc::strncpy:
2143 case LibFunc::strlen:
2145 case LibFunc::strpbrk:
2147 case LibFunc::strtol:
2148 case LibFunc::strtod:
2149 case LibFunc::strtof:
2150 case LibFunc::strtoul:
2151 case LibFunc::strtoll:
2152 case LibFunc::strtold:
2153 case LibFunc::strtoull:
2155 case LibFunc::strspn:
2157 case LibFunc::strcspn:
2159 case LibFunc::strstr:
2161 case LibFunc::memcmp:
2163 case LibFunc::memcpy:
2165 case LibFunc::memmove:
2167 case LibFunc::memset:
2173 case LibFunc::sinpif:
2174 case LibFunc::sinpi:
2175 case LibFunc::cospif:
2176 case LibFunc::cospi:
2182 case LibFunc::exp2l:
2184 case LibFunc::exp2f:
2188 case LibFunc::ffsll:
2192 case LibFunc::llabs:
2194 case LibFunc::isdigit:
2196 case LibFunc::isascii:
2198 case LibFunc::toascii:
2200 case LibFunc::printf:
2202 case LibFunc::sprintf:
2204 case LibFunc::fprintf:
2206 case LibFunc::fwrite:
2208 case LibFunc::fputs:
2212 case LibFunc::perror:
2213 return &ErrorReporting;
2214 case LibFunc::vfprintf:
2215 case LibFunc::fiprintf:
2216 return &ErrorReporting0;
2217 case LibFunc::fputc:
2218 return &ErrorReporting1;
2221 case LibFunc::floor:
2223 case LibFunc::round:
2224 case LibFunc::nearbyint:
2225 case LibFunc::trunc:
2226 if (hasFloatVersion(FuncName))
2227 return &UnaryDoubleFP;
2230 case LibFunc::acosh:
2232 case LibFunc::asinh:
2234 case LibFunc::atanh:
2238 case LibFunc::exp10:
2239 case LibFunc::expm1:
2241 case LibFunc::log10:
2242 case LibFunc::log1p:
2250 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2251 return &UnsafeUnaryDoubleFP;
2255 if (hasFloatVersion(FuncName))
2256 return &BinaryDoubleFP;
2258 case LibFunc::memcpy_chk:
2265 // Finally check for fortified library calls.
2266 if (FuncName.endswith("_chk")) {
2267 if (FuncName == "__memmove_chk")
2269 else if (FuncName == "__memset_chk")
2271 else if (FuncName == "__strcpy_chk")
2273 else if (FuncName == "__stpcpy_chk")
2275 else if (FuncName == "__strncpy_chk")
2277 else if (FuncName == "__stpncpy_chk")
2285 Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
2286 LibCallOptimization *LCO = lookupOptimization(CI);
2288 IRBuilder<> Builder(CI);
2289 return LCO->optimizeCall(CI, DL, TLI, LCS, Builder);
2294 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2295 const TargetLibraryInfo *TLI,
2296 bool UnsafeFPShrink) {
2297 Impl = new LibCallSimplifierImpl(DL, TLI, this, UnsafeFPShrink);
2300 LibCallSimplifier::~LibCallSimplifier() {
2304 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2305 if (CI->isNoBuiltin()) return nullptr;
2306 return Impl->optimizeCall(CI);
2309 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2310 I->replaceAllUsesWith(With);
2311 I->eraseFromParent();
2317 // Additional cases that we need to add to this file:
2320 // * cbrt(expN(X)) -> expN(x/3)
2321 // * cbrt(sqrt(x)) -> pow(x,1/6)
2322 // * cbrt(sqrt(x)) -> pow(x,1/9)
2325 // * exp(log(x)) -> x
2328 // * log(exp(x)) -> x
2329 // * log(x**y) -> y*log(x)
2330 // * log(exp(y)) -> y*log(e)
2331 // * log(exp2(y)) -> y*log(2)
2332 // * log(exp10(y)) -> y*log(10)
2333 // * log(sqrt(x)) -> 0.5*log(x)
2334 // * log(pow(x,y)) -> y*log(x)
2336 // lround, lroundf, lroundl:
2337 // * lround(cnst) -> cnst'
2340 // * pow(exp(x),y) -> exp(x*y)
2341 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2342 // * pow(pow(x,y),z)-> pow(x,y*z)
2344 // round, roundf, roundl:
2345 // * round(cnst) -> cnst'
2348 // * signbit(cnst) -> cnst'
2349 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2351 // sqrt, sqrtf, sqrtl:
2352 // * sqrt(expN(x)) -> expN(x*0.5)
2353 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2354 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2357 // * tan(atan(x)) -> x
2359 // trunc, truncf, truncl:
2360 // * trunc(cnst) -> cnst'