1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification. If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Target/TargetLibraryInfo.h"
33 #include "llvm/Transforms/Utils/BuildLibCalls.h"
38 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
39 cl::desc("Treat error-reporting calls as cold"));
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 static bool ignoreCallingConv(LibFunc::Func Func) {
55 llvm_unreachable("All cases should be covered in the switch.");
58 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
59 /// value is equal or not-equal to zero.
60 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
61 for (User *U : V->users()) {
62 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
64 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
67 // Unknown instruction.
73 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
74 /// comparisons with With.
75 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
76 for (User *U : V->users()) {
77 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
78 if (IC->isEquality() && IC->getOperand(1) == With)
80 // Unknown instruction.
86 static bool callHasFloatingPointArgument(const CallInst *CI) {
87 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
89 if ((*it)->getType()->isFloatingPointTy())
95 /// \brief Check whether the overloaded unary floating point function
96 /// corresponing to \a Ty is available.
97 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
98 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
99 LibFunc::Func LongDoubleFn) {
100 switch (Ty->getTypeID()) {
101 case Type::FloatTyID:
102 return TLI->has(FloatFn);
103 case Type::DoubleTyID:
104 return TLI->has(DoubleFn);
106 return TLI->has(LongDoubleFn);
110 //===----------------------------------------------------------------------===//
111 // Fortified Library Call Optimizations
112 //===----------------------------------------------------------------------===//
114 static bool isFortifiedCallFoldable(CallInst *CI, unsigned SizeCIOp, unsigned SizeArgOp,
116 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
118 if (ConstantInt *SizeCI =
119 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
120 if (SizeCI->isAllOnesValue())
123 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
124 // If the length is 0 we don't know how long it is and so we can't
128 return SizeCI->getZExtValue() >= Len;
130 if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getArgOperand(SizeArgOp)))
131 return SizeCI->getZExtValue() >= Arg->getZExtValue();
136 Value *LibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
137 Function *Callee = CI->getCalledFunction();
138 FunctionType *FT = Callee->getFunctionType();
139 LLVMContext &Context = CI->getContext();
141 // Check if this has the right signature.
142 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
143 !FT->getParamType(0)->isPointerTy() ||
144 !FT->getParamType(1)->isPointerTy() ||
145 FT->getParamType(2) != DL->getIntPtrType(Context) ||
146 FT->getParamType(3) != DL->getIntPtrType(Context))
149 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
150 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
151 CI->getArgOperand(2), 1);
152 return CI->getArgOperand(0);
157 Value *LibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
158 Function *Callee = CI->getCalledFunction();
159 FunctionType *FT = Callee->getFunctionType();
160 LLVMContext &Context = CI->getContext();
162 // Check if this has the right signature.
163 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
164 !FT->getParamType(0)->isPointerTy() ||
165 !FT->getParamType(1)->isPointerTy() ||
166 FT->getParamType(2) != DL->getIntPtrType(Context) ||
167 FT->getParamType(3) != DL->getIntPtrType(Context))
170 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
171 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
172 CI->getArgOperand(2), 1);
173 return CI->getArgOperand(0);
178 Value *LibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
179 Function *Callee = CI->getCalledFunction();
180 FunctionType *FT = Callee->getFunctionType();
181 LLVMContext &Context = CI->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)->isIntegerTy() ||
187 FT->getParamType(2) != DL->getIntPtrType(Context) ||
188 FT->getParamType(3) != DL->getIntPtrType(Context))
191 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
192 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
193 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
194 return CI->getArgOperand(0);
199 Value *LibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
200 Function *Callee = CI->getCalledFunction();
201 StringRef Name = Callee->getName();
202 FunctionType *FT = Callee->getFunctionType();
203 LLVMContext &Context = CI->getContext();
205 // Check if this has the right signature.
206 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
207 FT->getParamType(0) != FT->getParamType(1) ||
208 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
209 FT->getParamType(2) != DL->getIntPtrType(Context))
212 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
213 if (Dst == Src) // __strcpy_chk(x,x) -> x
216 // If a) we don't have any length information, or b) we know this will
217 // fit then just lower to a plain strcpy. Otherwise we'll keep our
218 // strcpy_chk call which may fail at runtime if the size is too long.
219 // TODO: It might be nice to get a maximum length out of the possible
220 // string lengths for varying.
221 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
222 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
225 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
226 uint64_t Len = GetStringLength(Src);
230 // This optimization require DataLayout.
234 Value *Ret = EmitMemCpyChk(
235 Dst, Src, ConstantInt::get(DL->getIntPtrType(Context), Len),
236 CI->getArgOperand(2), B, DL, TLI);
242 Value *LibCallSimplifier::optimizeStpCpyChk(CallInst *CI, IRBuilder<> &B) {
243 Function *Callee = CI->getCalledFunction();
244 StringRef Name = Callee->getName();
245 FunctionType *FT = Callee->getFunctionType();
246 LLVMContext &Context = CI->getContext();
248 // Check if this has the right signature.
249 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
250 FT->getParamType(0) != FT->getParamType(1) ||
251 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
252 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
255 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
256 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
257 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
258 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
261 // If a) we don't have any length information, or b) we know this will
262 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
263 // stpcpy_chk call which may fail at runtime if the size is too long.
264 // TODO: It might be nice to get a maximum length out of the possible
265 // string lengths for varying.
266 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
267 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
270 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
271 uint64_t Len = GetStringLength(Src);
275 // This optimization require DataLayout.
279 Type *PT = FT->getParamType(0);
280 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
282 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
283 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
290 Value *LibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
291 Function *Callee = CI->getCalledFunction();
292 StringRef Name = Callee->getName();
293 FunctionType *FT = Callee->getFunctionType();
294 LLVMContext &Context = CI->getContext();
296 // Check if this has the right signature.
297 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
298 FT->getParamType(0) != FT->getParamType(1) ||
299 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
300 !FT->getParamType(2)->isIntegerTy() ||
301 FT->getParamType(3) != DL->getIntPtrType(Context))
304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
306 EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
307 CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
313 //===----------------------------------------------------------------------===//
314 // String and Memory Library Call Optimizations
315 //===----------------------------------------------------------------------===//
317 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
318 Function *Callee = CI->getCalledFunction();
319 // Verify the "strcat" function prototype.
320 FunctionType *FT = Callee->getFunctionType();
321 if (FT->getNumParams() != 2||
322 FT->getReturnType() != B.getInt8PtrTy() ||
323 FT->getParamType(0) != FT->getReturnType() ||
324 FT->getParamType(1) != FT->getReturnType())
327 // Extract some information from the instruction
328 Value *Dst = CI->getArgOperand(0);
329 Value *Src = CI->getArgOperand(1);
331 // See if we can get the length of the input string.
332 uint64_t Len = GetStringLength(Src);
335 --Len; // Unbias length.
337 // Handle the simple, do-nothing case: strcat(x, "") -> x
341 // These optimizations require DataLayout.
345 return emitStrLenMemCpy(Src, Dst, Len, B);
348 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
350 // We need to find the end of the destination string. That's where the
351 // memory is to be moved to. We just generate a call to strlen.
352 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
356 // Now that we have the destination's length, we must index into the
357 // destination's pointer to get the actual memcpy destination (end of
358 // the string .. we're concatenating).
359 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
361 // We have enough information to now generate the memcpy call to do the
362 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
365 ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
369 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
370 Function *Callee = CI->getCalledFunction();
371 // Verify the "strncat" function prototype.
372 FunctionType *FT = Callee->getFunctionType();
373 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
374 FT->getParamType(0) != FT->getReturnType() ||
375 FT->getParamType(1) != FT->getReturnType() ||
376 !FT->getParamType(2)->isIntegerTy())
379 // Extract some information from the instruction
380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
384 // We don't do anything if length is not constant
385 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
386 Len = LengthArg->getZExtValue();
390 // See if we can get the length of the input string.
391 uint64_t SrcLen = GetStringLength(Src);
394 --SrcLen; // Unbias length.
396 // Handle the simple, do-nothing cases:
397 // strncat(x, "", c) -> x
398 // strncat(x, c, 0) -> x
399 if (SrcLen == 0 || Len == 0)
402 // These optimizations require DataLayout.
406 // We don't optimize this case
410 // strncat(x, s, c) -> strcat(x, s)
411 // s is constant so the strcat can be optimized further
412 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
415 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
416 Function *Callee = CI->getCalledFunction();
417 // Verify the "strchr" function prototype.
418 FunctionType *FT = Callee->getFunctionType();
419 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
420 FT->getParamType(0) != FT->getReturnType() ||
421 !FT->getParamType(1)->isIntegerTy(32))
424 Value *SrcStr = CI->getArgOperand(0);
426 // If the second operand is non-constant, see if we can compute the length
427 // of the input string and turn this into memchr.
428 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
430 // These optimizations require DataLayout.
434 uint64_t Len = GetStringLength(SrcStr);
435 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
439 SrcStr, CI->getArgOperand(1), // include nul.
440 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
443 // Otherwise, the character is a constant, see if the first argument is
444 // a string literal. If so, we can constant fold.
446 if (!getConstantStringInfo(SrcStr, Str)) {
447 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
448 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
452 // Compute the offset, make sure to handle the case when we're searching for
453 // zero (a weird way to spell strlen).
454 size_t I = (0xFF & CharC->getSExtValue()) == 0
456 : Str.find(CharC->getSExtValue());
457 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
458 return Constant::getNullValue(CI->getType());
460 // strchr(s+n,c) -> gep(s+n+i,c)
461 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
464 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
465 Function *Callee = CI->getCalledFunction();
466 // Verify the "strrchr" function prototype.
467 FunctionType *FT = Callee->getFunctionType();
468 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
469 FT->getParamType(0) != FT->getReturnType() ||
470 !FT->getParamType(1)->isIntegerTy(32))
473 Value *SrcStr = CI->getArgOperand(0);
474 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
476 // Cannot fold anything if we're not looking for a constant.
481 if (!getConstantStringInfo(SrcStr, Str)) {
482 // strrchr(s, 0) -> strchr(s, 0)
483 if (DL && CharC->isZero())
484 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
488 // Compute the offset.
489 size_t I = (0xFF & CharC->getSExtValue()) == 0
491 : Str.rfind(CharC->getSExtValue());
492 if (I == StringRef::npos) // Didn't find the char. Return null.
493 return Constant::getNullValue(CI->getType());
495 // strrchr(s+n,c) -> gep(s+n+i,c)
496 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
499 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
500 Function *Callee = CI->getCalledFunction();
501 // Verify the "strcmp" function prototype.
502 FunctionType *FT = Callee->getFunctionType();
503 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
504 FT->getParamType(0) != FT->getParamType(1) ||
505 FT->getParamType(0) != B.getInt8PtrTy())
508 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
509 if (Str1P == Str2P) // strcmp(x,x) -> 0
510 return ConstantInt::get(CI->getType(), 0);
512 StringRef Str1, Str2;
513 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
514 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
516 // strcmp(x, y) -> cnst (if both x and y are constant strings)
517 if (HasStr1 && HasStr2)
518 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
520 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
522 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
524 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
525 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
527 // strcmp(P, "x") -> memcmp(P, "x", 2)
528 uint64_t Len1 = GetStringLength(Str1P);
529 uint64_t Len2 = GetStringLength(Str2P);
531 // These optimizations require DataLayout.
535 return EmitMemCmp(Str1P, Str2P,
536 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
537 std::min(Len1, Len2)),
544 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
545 Function *Callee = CI->getCalledFunction();
546 // Verify the "strncmp" function prototype.
547 FunctionType *FT = Callee->getFunctionType();
548 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
549 FT->getParamType(0) != FT->getParamType(1) ||
550 FT->getParamType(0) != B.getInt8PtrTy() ||
551 !FT->getParamType(2)->isIntegerTy())
554 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
555 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
556 return ConstantInt::get(CI->getType(), 0);
558 // Get the length argument if it is constant.
560 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
561 Length = LengthArg->getZExtValue();
565 if (Length == 0) // strncmp(x,y,0) -> 0
566 return ConstantInt::get(CI->getType(), 0);
568 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
569 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
571 StringRef Str1, Str2;
572 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
573 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
575 // strncmp(x, y) -> cnst (if both x and y are constant strings)
576 if (HasStr1 && HasStr2) {
577 StringRef SubStr1 = Str1.substr(0, Length);
578 StringRef SubStr2 = Str2.substr(0, Length);
579 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
582 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
584 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
586 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
587 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
592 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
593 Function *Callee = CI->getCalledFunction();
594 // Verify the "strcpy" function prototype.
595 FunctionType *FT = Callee->getFunctionType();
596 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
597 FT->getParamType(0) != FT->getParamType(1) ||
598 FT->getParamType(0) != B.getInt8PtrTy())
601 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
602 if (Dst == Src) // strcpy(x,x) -> x
605 // These optimizations require DataLayout.
609 // See if we can get the length of the input string.
610 uint64_t Len = GetStringLength(Src);
614 // We have enough information to now generate the memcpy call to do the
615 // copy for us. Make a memcpy to copy the nul byte with align = 1.
616 B.CreateMemCpy(Dst, Src,
617 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
621 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
622 Function *Callee = CI->getCalledFunction();
623 // Verify the "stpcpy" function prototype.
624 FunctionType *FT = Callee->getFunctionType();
625 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
626 FT->getParamType(0) != FT->getParamType(1) ||
627 FT->getParamType(0) != B.getInt8PtrTy())
630 // These optimizations require DataLayout.
634 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
635 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
636 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
637 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
640 // See if we can get the length of the input string.
641 uint64_t Len = GetStringLength(Src);
645 Type *PT = FT->getParamType(0);
646 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
648 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
650 // We have enough information to now generate the memcpy call to do the
651 // copy for us. Make a memcpy to copy the nul byte with align = 1.
652 B.CreateMemCpy(Dst, Src, LenV, 1);
656 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
657 Function *Callee = CI->getCalledFunction();
658 FunctionType *FT = Callee->getFunctionType();
659 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
660 FT->getParamType(0) != FT->getParamType(1) ||
661 FT->getParamType(0) != B.getInt8PtrTy() ||
662 !FT->getParamType(2)->isIntegerTy())
665 Value *Dst = CI->getArgOperand(0);
666 Value *Src = CI->getArgOperand(1);
667 Value *LenOp = CI->getArgOperand(2);
669 // See if we can get the length of the input string.
670 uint64_t SrcLen = GetStringLength(Src);
676 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
677 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
682 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
683 Len = LengthArg->getZExtValue();
688 return Dst; // strncpy(x, y, 0) -> x
690 // These optimizations require DataLayout.
694 // Let strncpy handle the zero padding
695 if (Len > SrcLen + 1)
698 Type *PT = FT->getParamType(0);
699 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
700 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
705 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
706 Function *Callee = CI->getCalledFunction();
707 FunctionType *FT = Callee->getFunctionType();
708 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
709 !FT->getReturnType()->isIntegerTy())
712 Value *Src = CI->getArgOperand(0);
714 // Constant folding: strlen("xyz") -> 3
715 if (uint64_t Len = GetStringLength(Src))
716 return ConstantInt::get(CI->getType(), Len - 1);
718 // strlen(x?"foo":"bars") --> x ? 3 : 4
719 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
720 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
721 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
722 if (LenTrue && LenFalse) {
723 Function *Caller = CI->getParent()->getParent();
724 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
726 "folded strlen(select) to select of constants");
727 return B.CreateSelect(SI->getCondition(),
728 ConstantInt::get(CI->getType(), LenTrue - 1),
729 ConstantInt::get(CI->getType(), LenFalse - 1));
733 // strlen(x) != 0 --> *x != 0
734 // strlen(x) == 0 --> *x == 0
735 if (isOnlyUsedInZeroEqualityComparison(CI))
736 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
741 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
742 Function *Callee = CI->getCalledFunction();
743 FunctionType *FT = Callee->getFunctionType();
744 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
745 FT->getParamType(1) != FT->getParamType(0) ||
746 FT->getReturnType() != FT->getParamType(0))
750 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
751 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
753 // strpbrk(s, "") -> NULL
754 // strpbrk("", s) -> NULL
755 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
756 return Constant::getNullValue(CI->getType());
759 if (HasS1 && HasS2) {
760 size_t I = S1.find_first_of(S2);
761 if (I == StringRef::npos) // No match.
762 return Constant::getNullValue(CI->getType());
764 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
767 // strpbrk(s, "a") -> strchr(s, 'a')
768 if (DL && HasS2 && S2.size() == 1)
769 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
774 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
775 Function *Callee = CI->getCalledFunction();
776 FunctionType *FT = Callee->getFunctionType();
777 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
778 !FT->getParamType(0)->isPointerTy() ||
779 !FT->getParamType(1)->isPointerTy())
782 Value *EndPtr = CI->getArgOperand(1);
783 if (isa<ConstantPointerNull>(EndPtr)) {
784 // With a null EndPtr, this function won't capture the main argument.
785 // It would be readonly too, except that it still may write to errno.
786 CI->addAttribute(1, Attribute::NoCapture);
792 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
793 Function *Callee = CI->getCalledFunction();
794 FunctionType *FT = Callee->getFunctionType();
795 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
796 FT->getParamType(1) != FT->getParamType(0) ||
797 !FT->getReturnType()->isIntegerTy())
801 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
802 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
804 // strspn(s, "") -> 0
805 // strspn("", s) -> 0
806 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
807 return Constant::getNullValue(CI->getType());
810 if (HasS1 && HasS2) {
811 size_t Pos = S1.find_first_not_of(S2);
812 if (Pos == StringRef::npos)
814 return ConstantInt::get(CI->getType(), Pos);
820 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
821 Function *Callee = CI->getCalledFunction();
822 FunctionType *FT = Callee->getFunctionType();
823 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
824 FT->getParamType(1) != FT->getParamType(0) ||
825 !FT->getReturnType()->isIntegerTy())
829 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
830 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
832 // strcspn("", s) -> 0
833 if (HasS1 && S1.empty())
834 return Constant::getNullValue(CI->getType());
837 if (HasS1 && HasS2) {
838 size_t Pos = S1.find_first_of(S2);
839 if (Pos == StringRef::npos)
841 return ConstantInt::get(CI->getType(), Pos);
844 // strcspn(s, "") -> strlen(s)
845 if (DL && HasS2 && S2.empty())
846 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
851 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
852 Function *Callee = CI->getCalledFunction();
853 FunctionType *FT = Callee->getFunctionType();
854 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
855 !FT->getParamType(1)->isPointerTy() ||
856 !FT->getReturnType()->isPointerTy())
859 // fold strstr(x, x) -> x.
860 if (CI->getArgOperand(0) == CI->getArgOperand(1))
861 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
863 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
864 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
865 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
868 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
872 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
873 ICmpInst *Old = cast<ICmpInst>(*UI++);
875 B.CreateICmp(Old->getPredicate(), StrNCmp,
876 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
877 replaceAllUsesWith(Old, Cmp);
882 // See if either input string is a constant string.
883 StringRef SearchStr, ToFindStr;
884 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
885 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
887 // fold strstr(x, "") -> x.
888 if (HasStr2 && ToFindStr.empty())
889 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
891 // If both strings are known, constant fold it.
892 if (HasStr1 && HasStr2) {
893 size_t Offset = SearchStr.find(ToFindStr);
895 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
896 return Constant::getNullValue(CI->getType());
898 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
899 Value *Result = CastToCStr(CI->getArgOperand(0), B);
900 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
901 return B.CreateBitCast(Result, CI->getType());
904 // fold strstr(x, "y") -> strchr(x, 'y').
905 if (HasStr2 && ToFindStr.size() == 1) {
906 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
907 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
912 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
913 Function *Callee = CI->getCalledFunction();
914 FunctionType *FT = Callee->getFunctionType();
915 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
916 !FT->getParamType(1)->isPointerTy() ||
917 !FT->getReturnType()->isIntegerTy(32))
920 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
922 if (LHS == RHS) // memcmp(s,s,x) -> 0
923 return Constant::getNullValue(CI->getType());
925 // Make sure we have a constant length.
926 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
929 uint64_t Len = LenC->getZExtValue();
931 if (Len == 0) // memcmp(s1,s2,0) -> 0
932 return Constant::getNullValue(CI->getType());
934 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
936 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
937 CI->getType(), "lhsv");
938 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
939 CI->getType(), "rhsv");
940 return B.CreateSub(LHSV, RHSV, "chardiff");
943 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
944 StringRef LHSStr, RHSStr;
945 if (getConstantStringInfo(LHS, LHSStr) &&
946 getConstantStringInfo(RHS, RHSStr)) {
947 // Make sure we're not reading out-of-bounds memory.
948 if (Len > LHSStr.size() || Len > RHSStr.size())
950 // Fold the memcmp and normalize the result. This way we get consistent
951 // results across multiple platforms.
953 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
958 return ConstantInt::get(CI->getType(), Ret);
964 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
965 Function *Callee = CI->getCalledFunction();
966 // These optimizations require DataLayout.
970 FunctionType *FT = Callee->getFunctionType();
971 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
972 !FT->getParamType(0)->isPointerTy() ||
973 !FT->getParamType(1)->isPointerTy() ||
974 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
977 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
978 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
979 CI->getArgOperand(2), 1);
980 return CI->getArgOperand(0);
983 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
984 Function *Callee = CI->getCalledFunction();
985 // These optimizations require DataLayout.
989 FunctionType *FT = Callee->getFunctionType();
990 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
991 !FT->getParamType(0)->isPointerTy() ||
992 !FT->getParamType(1)->isPointerTy() ||
993 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
996 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
997 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
998 CI->getArgOperand(2), 1);
999 return CI->getArgOperand(0);
1002 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1003 Function *Callee = CI->getCalledFunction();
1004 // These optimizations require DataLayout.
1008 FunctionType *FT = Callee->getFunctionType();
1009 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1010 !FT->getParamType(0)->isPointerTy() ||
1011 !FT->getParamType(1)->isIntegerTy() ||
1012 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
1015 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1016 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1017 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1018 return CI->getArgOperand(0);
1021 //===----------------------------------------------------------------------===//
1022 // Math Library Optimizations
1023 //===----------------------------------------------------------------------===//
1025 //===----------------------------------------------------------------------===//
1026 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1028 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1029 bool CheckRetType) {
1030 Function *Callee = CI->getCalledFunction();
1031 FunctionType *FT = Callee->getFunctionType();
1032 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1033 !FT->getParamType(0)->isDoubleTy())
1037 // Check if all the uses for function like 'sin' are converted to float.
1038 for (User *U : CI->users()) {
1039 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1040 if (!Cast || !Cast->getType()->isFloatTy())
1045 // If this is something like 'floor((double)floatval)', convert to floorf.
1046 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1047 if (!Cast || !Cast->getOperand(0)->getType()->isFloatTy())
1050 // floor((double)floatval) -> (double)floorf(floatval)
1051 Value *V = Cast->getOperand(0);
1052 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1053 return B.CreateFPExt(V, B.getDoubleTy());
1056 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1057 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1058 Function *Callee = CI->getCalledFunction();
1059 FunctionType *FT = Callee->getFunctionType();
1060 // Just make sure this has 2 arguments of the same FP type, which match the
1062 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1063 FT->getParamType(0) != FT->getParamType(1) ||
1064 !FT->getParamType(0)->isFloatingPointTy())
1067 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1068 // we convert it to fminf.
1069 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1070 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1071 if (!Cast1 || !Cast1->getOperand(0)->getType()->isFloatTy() || !Cast2 ||
1072 !Cast2->getOperand(0)->getType()->isFloatTy())
1075 // fmin((double)floatval1, (double)floatval2)
1076 // -> (double)fmin(floatval1, floatval2)
1078 Value *V1 = Cast1->getOperand(0);
1079 Value *V2 = Cast2->getOperand(0);
1080 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1081 Callee->getAttributes());
1082 return B.CreateFPExt(V, B.getDoubleTy());
1085 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1086 Function *Callee = CI->getCalledFunction();
1087 Value *Ret = nullptr;
1088 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1089 Ret = optimizeUnaryDoubleFP(CI, B, true);
1092 FunctionType *FT = Callee->getFunctionType();
1093 // Just make sure this has 1 argument of FP type, which matches the
1095 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1096 !FT->getParamType(0)->isFloatingPointTy())
1099 // cos(-x) -> cos(x)
1100 Value *Op1 = CI->getArgOperand(0);
1101 if (BinaryOperator::isFNeg(Op1)) {
1102 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1103 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1108 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1109 Function *Callee = CI->getCalledFunction();
1111 Value *Ret = nullptr;
1112 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1113 Ret = optimizeUnaryDoubleFP(CI, B, true);
1116 FunctionType *FT = Callee->getFunctionType();
1117 // Just make sure this has 2 arguments of the same FP type, which match the
1119 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1120 FT->getParamType(0) != FT->getParamType(1) ||
1121 !FT->getParamType(0)->isFloatingPointTy())
1124 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1125 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1126 // pow(1.0, x) -> 1.0
1127 if (Op1C->isExactlyValue(1.0))
1129 // pow(2.0, x) -> exp2(x)
1130 if (Op1C->isExactlyValue(2.0) &&
1131 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1133 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1134 // pow(10.0, x) -> exp10(x)
1135 if (Op1C->isExactlyValue(10.0) &&
1136 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1138 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1139 Callee->getAttributes());
1142 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1146 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1147 return ConstantFP::get(CI->getType(), 1.0);
1149 if (Op2C->isExactlyValue(0.5) &&
1150 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1152 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1154 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1155 // This is faster than calling pow, and still handles negative zero
1156 // and negative infinity correctly.
1157 // TODO: In fast-math mode, this could be just sqrt(x).
1158 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1159 Value *Inf = ConstantFP::getInfinity(CI->getType());
1160 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1161 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1163 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1164 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1165 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1169 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1171 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1172 return B.CreateFMul(Op1, Op1, "pow2");
1173 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1174 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1178 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1179 Function *Callee = CI->getCalledFunction();
1180 Function *Caller = CI->getParent()->getParent();
1182 Value *Ret = nullptr;
1183 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1184 TLI->has(LibFunc::exp2f)) {
1185 Ret = optimizeUnaryDoubleFP(CI, B, true);
1188 FunctionType *FT = Callee->getFunctionType();
1189 // Just make sure this has 1 argument of FP type, which matches the
1191 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1192 !FT->getParamType(0)->isFloatingPointTy())
1195 Value *Op = CI->getArgOperand(0);
1196 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1197 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1198 LibFunc::Func LdExp = LibFunc::ldexpl;
1199 if (Op->getType()->isFloatTy())
1200 LdExp = LibFunc::ldexpf;
1201 else if (Op->getType()->isDoubleTy())
1202 LdExp = LibFunc::ldexp;
1204 if (TLI->has(LdExp)) {
1205 Value *LdExpArg = nullptr;
1206 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1207 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1208 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1209 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1210 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1211 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1215 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1216 if (!Op->getType()->isFloatTy())
1217 One = ConstantExpr::getFPExtend(One, Op->getType());
1219 Module *M = Caller->getParent();
1221 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1222 Op->getType(), B.getInt32Ty(), NULL);
1223 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1224 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1225 CI->setCallingConv(F->getCallingConv());
1233 static bool isTrigLibCall(CallInst *CI);
1234 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1235 bool UseFloat, Value *&Sin, Value *&Cos,
1238 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1240 // Make sure the prototype is as expected, otherwise the rest of the
1241 // function is probably invalid and likely to abort.
1242 if (!isTrigLibCall(CI))
1245 Value *Arg = CI->getArgOperand(0);
1246 SmallVector<CallInst *, 1> SinCalls;
1247 SmallVector<CallInst *, 1> CosCalls;
1248 SmallVector<CallInst *, 1> SinCosCalls;
1250 bool IsFloat = Arg->getType()->isFloatTy();
1252 // Look for all compatible sinpi, cospi and sincospi calls with the same
1253 // argument. If there are enough (in some sense) we can make the
1255 for (User *U : Arg->users())
1256 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1259 // It's only worthwhile if both sinpi and cospi are actually used.
1260 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1263 Value *Sin, *Cos, *SinCos;
1264 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1266 replaceTrigInsts(SinCalls, Sin);
1267 replaceTrigInsts(CosCalls, Cos);
1268 replaceTrigInsts(SinCosCalls, SinCos);
1273 static bool isTrigLibCall(CallInst *CI) {
1274 Function *Callee = CI->getCalledFunction();
1275 FunctionType *FT = Callee->getFunctionType();
1277 // We can only hope to do anything useful if we can ignore things like errno
1278 // and floating-point exceptions.
1279 bool AttributesSafe =
1280 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1282 // Other than that we need float(float) or double(double)
1283 return AttributesSafe && FT->getNumParams() == 1 &&
1284 FT->getReturnType() == FT->getParamType(0) &&
1285 (FT->getParamType(0)->isFloatTy() ||
1286 FT->getParamType(0)->isDoubleTy());
1290 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1291 SmallVectorImpl<CallInst *> &SinCalls,
1292 SmallVectorImpl<CallInst *> &CosCalls,
1293 SmallVectorImpl<CallInst *> &SinCosCalls) {
1294 CallInst *CI = dyn_cast<CallInst>(Val);
1299 Function *Callee = CI->getCalledFunction();
1300 StringRef FuncName = Callee->getName();
1302 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1306 if (Func == LibFunc::sinpif)
1307 SinCalls.push_back(CI);
1308 else if (Func == LibFunc::cospif)
1309 CosCalls.push_back(CI);
1310 else if (Func == LibFunc::sincospif_stret)
1311 SinCosCalls.push_back(CI);
1313 if (Func == LibFunc::sinpi)
1314 SinCalls.push_back(CI);
1315 else if (Func == LibFunc::cospi)
1316 CosCalls.push_back(CI);
1317 else if (Func == LibFunc::sincospi_stret)
1318 SinCosCalls.push_back(CI);
1322 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1324 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1326 replaceAllUsesWith(*I, Res);
1330 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1331 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1332 Type *ArgTy = Arg->getType();
1336 Triple T(OrigCallee->getParent()->getTargetTriple());
1338 Name = "__sincospif_stret";
1340 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1341 // x86_64 can't use {float, float} since that would be returned in both
1342 // xmm0 and xmm1, which isn't what a real struct would do.
1343 ResTy = T.getArch() == Triple::x86_64
1344 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1345 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1347 Name = "__sincospi_stret";
1348 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1351 Module *M = OrigCallee->getParent();
1352 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1353 ResTy, ArgTy, NULL);
1355 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1356 // If the argument is an instruction, it must dominate all uses so put our
1357 // sincos call there.
1358 BasicBlock::iterator Loc = ArgInst;
1359 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1361 // Otherwise (e.g. for a constant) the beginning of the function is as
1362 // good a place as any.
1363 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1364 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1367 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1369 if (SinCos->getType()->isStructTy()) {
1370 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1371 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1373 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1375 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1380 //===----------------------------------------------------------------------===//
1381 // Integer Library Call Optimizations
1382 //===----------------------------------------------------------------------===//
1384 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1385 Function *Callee = CI->getCalledFunction();
1386 FunctionType *FT = Callee->getFunctionType();
1387 // Just make sure this has 2 arguments of the same FP type, which match the
1389 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1390 !FT->getParamType(0)->isIntegerTy())
1393 Value *Op = CI->getArgOperand(0);
1396 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1397 if (CI->isZero()) // ffs(0) -> 0.
1398 return B.getInt32(0);
1399 // ffs(c) -> cttz(c)+1
1400 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1403 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1404 Type *ArgType = Op->getType();
1406 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1407 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1408 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1409 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1411 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1412 return B.CreateSelect(Cond, V, B.getInt32(0));
1415 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1416 Function *Callee = CI->getCalledFunction();
1417 FunctionType *FT = Callee->getFunctionType();
1418 // We require integer(integer) where the types agree.
1419 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1420 FT->getParamType(0) != FT->getReturnType())
1423 // abs(x) -> x >s -1 ? x : -x
1424 Value *Op = CI->getArgOperand(0);
1426 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1427 Value *Neg = B.CreateNeg(Op, "neg");
1428 return B.CreateSelect(Pos, Op, Neg);
1431 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1432 Function *Callee = CI->getCalledFunction();
1433 FunctionType *FT = Callee->getFunctionType();
1434 // We require integer(i32)
1435 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1436 !FT->getParamType(0)->isIntegerTy(32))
1439 // isdigit(c) -> (c-'0') <u 10
1440 Value *Op = CI->getArgOperand(0);
1441 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1442 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1443 return B.CreateZExt(Op, CI->getType());
1446 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1447 Function *Callee = CI->getCalledFunction();
1448 FunctionType *FT = Callee->getFunctionType();
1449 // We require integer(i32)
1450 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1451 !FT->getParamType(0)->isIntegerTy(32))
1454 // isascii(c) -> c <u 128
1455 Value *Op = CI->getArgOperand(0);
1456 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1457 return B.CreateZExt(Op, CI->getType());
1460 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1461 Function *Callee = CI->getCalledFunction();
1462 FunctionType *FT = Callee->getFunctionType();
1463 // We require i32(i32)
1464 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1465 !FT->getParamType(0)->isIntegerTy(32))
1468 // toascii(c) -> c & 0x7f
1469 return B.CreateAnd(CI->getArgOperand(0),
1470 ConstantInt::get(CI->getType(), 0x7F));
1473 //===----------------------------------------------------------------------===//
1474 // Formatting and IO Library Call Optimizations
1475 //===----------------------------------------------------------------------===//
1477 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1479 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1481 // Error reporting calls should be cold, mark them as such.
1482 // This applies even to non-builtin calls: it is only a hint and applies to
1483 // functions that the frontend might not understand as builtins.
1485 // This heuristic was suggested in:
1486 // Improving Static Branch Prediction in a Compiler
1487 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1488 // Proceedings of PACT'98, Oct. 1998, IEEE
1489 Function *Callee = CI->getCalledFunction();
1491 if (!CI->hasFnAttr(Attribute::Cold) &&
1492 isReportingError(Callee, CI, StreamArg)) {
1493 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1499 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1500 if (!ColdErrorCalls)
1503 if (!Callee || !Callee->isDeclaration())
1509 // These functions might be considered cold, but only if their stream
1510 // argument is stderr.
1512 if (StreamArg >= (int)CI->getNumArgOperands())
1514 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1517 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1518 if (!GV || !GV->isDeclaration())
1520 return GV->getName() == "stderr";
1523 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1524 // Check for a fixed format string.
1525 StringRef FormatStr;
1526 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1529 // Empty format string -> noop.
1530 if (FormatStr.empty()) // Tolerate printf's declared void.
1531 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1533 // Do not do any of the following transformations if the printf return value
1534 // is used, in general the printf return value is not compatible with either
1535 // putchar() or puts().
1536 if (!CI->use_empty())
1539 // printf("x") -> putchar('x'), even for '%'.
1540 if (FormatStr.size() == 1) {
1541 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1542 if (CI->use_empty() || !Res)
1544 return B.CreateIntCast(Res, CI->getType(), true);
1547 // printf("foo\n") --> puts("foo")
1548 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1549 FormatStr.find('%') == StringRef::npos) { // No format characters.
1550 // Create a string literal with no \n on it. We expect the constant merge
1551 // pass to be run after this pass, to merge duplicate strings.
1552 FormatStr = FormatStr.drop_back();
1553 Value *GV = B.CreateGlobalString(FormatStr, "str");
1554 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1555 return (CI->use_empty() || !NewCI)
1557 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1560 // Optimize specific format strings.
1561 // printf("%c", chr) --> putchar(chr)
1562 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1563 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1564 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1566 if (CI->use_empty() || !Res)
1568 return B.CreateIntCast(Res, CI->getType(), true);
1571 // printf("%s\n", str) --> puts(str)
1572 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1573 CI->getArgOperand(1)->getType()->isPointerTy()) {
1574 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1579 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1581 Function *Callee = CI->getCalledFunction();
1582 // Require one fixed pointer argument and an integer/void result.
1583 FunctionType *FT = Callee->getFunctionType();
1584 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1585 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1588 if (Value *V = optimizePrintFString(CI, B)) {
1592 // printf(format, ...) -> iprintf(format, ...) if no floating point
1594 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1595 Module *M = B.GetInsertBlock()->getParent()->getParent();
1596 Constant *IPrintFFn =
1597 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1598 CallInst *New = cast<CallInst>(CI->clone());
1599 New->setCalledFunction(IPrintFFn);
1606 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1607 // Check for a fixed format string.
1608 StringRef FormatStr;
1609 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1612 // If we just have a format string (nothing else crazy) transform it.
1613 if (CI->getNumArgOperands() == 2) {
1614 // Make sure there's no % in the constant array. We could try to handle
1615 // %% -> % in the future if we cared.
1616 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1617 if (FormatStr[i] == '%')
1618 return nullptr; // we found a format specifier, bail out.
1620 // These optimizations require DataLayout.
1624 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1626 CI->getArgOperand(0), CI->getArgOperand(1),
1627 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1628 FormatStr.size() + 1),
1629 1); // Copy the null byte.
1630 return ConstantInt::get(CI->getType(), FormatStr.size());
1633 // The remaining optimizations require the format string to be "%s" or "%c"
1634 // and have an extra operand.
1635 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1636 CI->getNumArgOperands() < 3)
1639 // Decode the second character of the format string.
1640 if (FormatStr[1] == 'c') {
1641 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1642 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1644 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1645 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1646 B.CreateStore(V, Ptr);
1647 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1648 B.CreateStore(B.getInt8(0), Ptr);
1650 return ConstantInt::get(CI->getType(), 1);
1653 if (FormatStr[1] == 's') {
1654 // These optimizations require DataLayout.
1658 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1659 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1662 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1666 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1667 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1669 // The sprintf result is the unincremented number of bytes in the string.
1670 return B.CreateIntCast(Len, CI->getType(), false);
1675 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1676 Function *Callee = CI->getCalledFunction();
1677 // Require two fixed pointer arguments and an integer result.
1678 FunctionType *FT = Callee->getFunctionType();
1679 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1680 !FT->getParamType(1)->isPointerTy() ||
1681 !FT->getReturnType()->isIntegerTy())
1684 if (Value *V = optimizeSPrintFString(CI, B)) {
1688 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1690 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1691 Module *M = B.GetInsertBlock()->getParent()->getParent();
1692 Constant *SIPrintFFn =
1693 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1694 CallInst *New = cast<CallInst>(CI->clone());
1695 New->setCalledFunction(SIPrintFFn);
1702 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1703 optimizeErrorReporting(CI, B, 0);
1705 // All the optimizations depend on the format string.
1706 StringRef FormatStr;
1707 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1710 // Do not do any of the following transformations if the fprintf return
1711 // value is used, in general the fprintf return value is not compatible
1712 // with fwrite(), fputc() or fputs().
1713 if (!CI->use_empty())
1716 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1717 if (CI->getNumArgOperands() == 2) {
1718 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1719 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1720 return nullptr; // We found a format specifier.
1722 // These optimizations require DataLayout.
1727 CI->getArgOperand(1),
1728 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1729 CI->getArgOperand(0), B, DL, TLI);
1732 // The remaining optimizations require the format string to be "%s" or "%c"
1733 // and have an extra operand.
1734 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1735 CI->getNumArgOperands() < 3)
1738 // Decode the second character of the format string.
1739 if (FormatStr[1] == 'c') {
1740 // fprintf(F, "%c", chr) --> fputc(chr, F)
1741 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1743 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1746 if (FormatStr[1] == 's') {
1747 // fprintf(F, "%s", str) --> fputs(str, F)
1748 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1750 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1755 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1756 Function *Callee = CI->getCalledFunction();
1757 // Require two fixed paramters as pointers and integer result.
1758 FunctionType *FT = Callee->getFunctionType();
1759 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1760 !FT->getParamType(1)->isPointerTy() ||
1761 !FT->getReturnType()->isIntegerTy())
1764 if (Value *V = optimizeFPrintFString(CI, B)) {
1768 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1769 // floating point arguments.
1770 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1771 Module *M = B.GetInsertBlock()->getParent()->getParent();
1772 Constant *FIPrintFFn =
1773 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1774 CallInst *New = cast<CallInst>(CI->clone());
1775 New->setCalledFunction(FIPrintFFn);
1782 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1783 optimizeErrorReporting(CI, B, 3);
1785 Function *Callee = CI->getCalledFunction();
1786 // Require a pointer, an integer, an integer, a pointer, returning integer.
1787 FunctionType *FT = Callee->getFunctionType();
1788 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1789 !FT->getParamType(1)->isIntegerTy() ||
1790 !FT->getParamType(2)->isIntegerTy() ||
1791 !FT->getParamType(3)->isPointerTy() ||
1792 !FT->getReturnType()->isIntegerTy())
1795 // Get the element size and count.
1796 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1797 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1798 if (!SizeC || !CountC)
1800 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1802 // If this is writing zero records, remove the call (it's a noop).
1804 return ConstantInt::get(CI->getType(), 0);
1806 // If this is writing one byte, turn it into fputc.
1807 // This optimisation is only valid, if the return value is unused.
1808 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1809 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1810 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1811 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1817 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1818 optimizeErrorReporting(CI, B, 1);
1820 Function *Callee = CI->getCalledFunction();
1822 // These optimizations require DataLayout.
1826 // Require two pointers. Also, we can't optimize if return value is used.
1827 FunctionType *FT = Callee->getFunctionType();
1828 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1829 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1832 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1833 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1837 // Known to have no uses (see above).
1839 CI->getArgOperand(0),
1840 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1841 CI->getArgOperand(1), B, DL, TLI);
1844 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1845 Function *Callee = CI->getCalledFunction();
1846 // Require one fixed pointer argument and an integer/void result.
1847 FunctionType *FT = Callee->getFunctionType();
1848 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1849 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1852 // Check for a constant string.
1854 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1857 if (Str.empty() && CI->use_empty()) {
1858 // puts("") -> putchar('\n')
1859 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
1860 if (CI->use_empty() || !Res)
1862 return B.CreateIntCast(Res, CI->getType(), true);
1868 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
1870 SmallString<20> FloatFuncName = FuncName;
1871 FloatFuncName += 'f';
1872 if (TLI->getLibFunc(FloatFuncName, Func))
1873 return TLI->has(Func);
1877 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1878 if (CI->isNoBuiltin())
1882 Function *Callee = CI->getCalledFunction();
1883 StringRef FuncName = Callee->getName();
1884 IRBuilder<> Builder(CI);
1885 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
1887 // Next check for intrinsics.
1888 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1889 if (!isCallingConvC)
1891 switch (II->getIntrinsicID()) {
1892 case Intrinsic::pow:
1893 return optimizePow(CI, Builder);
1894 case Intrinsic::exp2:
1895 return optimizeExp2(CI, Builder);
1901 // Then check for known library functions.
1902 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1903 // We never change the calling convention.
1904 if (!ignoreCallingConv(Func) && !isCallingConvC)
1907 case LibFunc::strcat:
1908 return optimizeStrCat(CI, Builder);
1909 case LibFunc::strncat:
1910 return optimizeStrNCat(CI, Builder);
1911 case LibFunc::strchr:
1912 return optimizeStrChr(CI, Builder);
1913 case LibFunc::strrchr:
1914 return optimizeStrRChr(CI, Builder);
1915 case LibFunc::strcmp:
1916 return optimizeStrCmp(CI, Builder);
1917 case LibFunc::strncmp:
1918 return optimizeStrNCmp(CI, Builder);
1919 case LibFunc::strcpy:
1920 return optimizeStrCpy(CI, Builder);
1921 case LibFunc::stpcpy:
1922 return optimizeStpCpy(CI, Builder);
1923 case LibFunc::strncpy:
1924 return optimizeStrNCpy(CI, Builder);
1925 case LibFunc::strlen:
1926 return optimizeStrLen(CI, Builder);
1927 case LibFunc::strpbrk:
1928 return optimizeStrPBrk(CI, Builder);
1929 case LibFunc::strtol:
1930 case LibFunc::strtod:
1931 case LibFunc::strtof:
1932 case LibFunc::strtoul:
1933 case LibFunc::strtoll:
1934 case LibFunc::strtold:
1935 case LibFunc::strtoull:
1936 return optimizeStrTo(CI, Builder);
1937 case LibFunc::strspn:
1938 return optimizeStrSpn(CI, Builder);
1939 case LibFunc::strcspn:
1940 return optimizeStrCSpn(CI, Builder);
1941 case LibFunc::strstr:
1942 return optimizeStrStr(CI, Builder);
1943 case LibFunc::memcmp:
1944 return optimizeMemCmp(CI, Builder);
1945 case LibFunc::memcpy:
1946 return optimizeMemCpy(CI, Builder);
1947 case LibFunc::memmove:
1948 return optimizeMemMove(CI, Builder);
1949 case LibFunc::memset:
1950 return optimizeMemSet(CI, Builder);
1954 return optimizeCos(CI, Builder);
1955 case LibFunc::sinpif:
1956 case LibFunc::sinpi:
1957 case LibFunc::cospif:
1958 case LibFunc::cospi:
1959 return optimizeSinCosPi(CI, Builder);
1963 return optimizePow(CI, Builder);
1964 case LibFunc::exp2l:
1966 case LibFunc::exp2f:
1967 return optimizeExp2(CI, Builder);
1970 case LibFunc::ffsll:
1971 return optimizeFFS(CI, Builder);
1974 case LibFunc::llabs:
1975 return optimizeAbs(CI, Builder);
1976 case LibFunc::isdigit:
1977 return optimizeIsDigit(CI, Builder);
1978 case LibFunc::isascii:
1979 return optimizeIsAscii(CI, Builder);
1980 case LibFunc::toascii:
1981 return optimizeToAscii(CI, Builder);
1982 case LibFunc::printf:
1983 return optimizePrintF(CI, Builder);
1984 case LibFunc::sprintf:
1985 return optimizeSPrintF(CI, Builder);
1986 case LibFunc::fprintf:
1987 return optimizeFPrintF(CI, Builder);
1988 case LibFunc::fwrite:
1989 return optimizeFWrite(CI, Builder);
1990 case LibFunc::fputs:
1991 return optimizeFPuts(CI, Builder);
1993 return optimizePuts(CI, Builder);
1994 case LibFunc::perror:
1995 return optimizeErrorReporting(CI, Builder);
1996 case LibFunc::vfprintf:
1997 case LibFunc::fiprintf:
1998 return optimizeErrorReporting(CI, Builder, 0);
1999 case LibFunc::fputc:
2000 return optimizeErrorReporting(CI, Builder, 1);
2003 case LibFunc::floor:
2005 case LibFunc::round:
2006 case LibFunc::nearbyint:
2007 case LibFunc::trunc:
2008 if (hasFloatVersion(FuncName))
2009 return optimizeUnaryDoubleFP(CI, Builder, false);
2012 case LibFunc::acosh:
2014 case LibFunc::asinh:
2016 case LibFunc::atanh:
2020 case LibFunc::exp10:
2021 case LibFunc::expm1:
2023 case LibFunc::log10:
2024 case LibFunc::log1p:
2032 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2033 return optimizeUnaryDoubleFP(CI, Builder, true);
2037 if (hasFloatVersion(FuncName))
2038 return optimizeBinaryDoubleFP(CI, Builder);
2040 case LibFunc::memcpy_chk:
2041 return optimizeMemCpyChk(CI, Builder);
2047 if (!isCallingConvC)
2050 // Finally check for fortified library calls.
2051 if (FuncName.endswith("_chk")) {
2052 if (FuncName == "__memmove_chk")
2053 return optimizeMemMoveChk(CI, Builder);
2054 else if (FuncName == "__memset_chk")
2055 return optimizeMemSetChk(CI, Builder);
2056 else if (FuncName == "__strcpy_chk")
2057 return optimizeStrCpyChk(CI, Builder);
2058 else if (FuncName == "__stpcpy_chk")
2059 return optimizeStpCpyChk(CI, Builder);
2060 else if (FuncName == "__strncpy_chk")
2061 return optimizeStrNCpyChk(CI, Builder);
2062 else if (FuncName == "__stpncpy_chk")
2063 return optimizeStrNCpyChk(CI, Builder);
2069 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2070 const TargetLibraryInfo *TLI,
2071 bool UnsafeFPShrink) :
2074 UnsafeFPShrink(UnsafeFPShrink) {
2077 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2078 I->replaceAllUsesWith(With);
2079 I->eraseFromParent();
2083 // Additional cases that we need to add to this file:
2086 // * cbrt(expN(X)) -> expN(x/3)
2087 // * cbrt(sqrt(x)) -> pow(x,1/6)
2088 // * cbrt(sqrt(x)) -> pow(x,1/9)
2091 // * exp(log(x)) -> x
2094 // * log(exp(x)) -> x
2095 // * log(x**y) -> y*log(x)
2096 // * log(exp(y)) -> y*log(e)
2097 // * log(exp2(y)) -> y*log(2)
2098 // * log(exp10(y)) -> y*log(10)
2099 // * log(sqrt(x)) -> 0.5*log(x)
2100 // * log(pow(x,y)) -> y*log(x)
2102 // lround, lroundf, lroundl:
2103 // * lround(cnst) -> cnst'
2106 // * pow(exp(x),y) -> exp(x*y)
2107 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2108 // * pow(pow(x,y),z)-> pow(x,y*z)
2110 // round, roundf, roundl:
2111 // * round(cnst) -> cnst'
2114 // * signbit(cnst) -> cnst'
2115 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2117 // sqrt, sqrtf, sqrtl:
2118 // * sqrt(expN(x)) -> expN(x*0.5)
2119 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2120 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2123 // * tan(atan(x)) -> x
2125 // trunc, truncf, truncl:
2126 // * trunc(cnst) -> cnst'