]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/Transforms/Utils/SimplifyLibCalls.cpp
[SimplifyLibCalls] Factor out str/mem libcall optimizations.
[opencl/llvm.git] / lib / Transforms / Utils / SimplifyLibCalls.cpp
1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DiagnosticInfo.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Target/TargetLibraryInfo.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
36 using namespace llvm;
37 using namespace PatternMatch;
39 static cl::opt<bool>
40     ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41                    cl::desc("Treat error-reporting calls as cold"));
43 static cl::opt<bool>
44     EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
45                          cl::init(false),
46                          cl::desc("Enable unsafe double to float "
47                                   "shrinking for math lib calls"));
50 //===----------------------------------------------------------------------===//
51 // Helper Functions
52 //===----------------------------------------------------------------------===//
54 static bool ignoreCallingConv(LibFunc::Func Func) {
55   switch (Func) {
56   case LibFunc::abs:
57   case LibFunc::labs:
58   case LibFunc::llabs:
59   case LibFunc::strlen:
60     return true;
61   default:
62     return false;
63   }
64   llvm_unreachable("All cases should be covered in the switch.");
65 }
67 /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
68 /// value is equal or not-equal to zero.
69 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
70   for (User *U : V->users()) {
71     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
72       if (IC->isEquality())
73         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
74           if (C->isNullValue())
75             continue;
76     // Unknown instruction.
77     return false;
78   }
79   return true;
80 }
82 /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
83 /// comparisons with With.
84 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
85   for (User *U : V->users()) {
86     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
87       if (IC->isEquality() && IC->getOperand(1) == With)
88         continue;
89     // Unknown instruction.
90     return false;
91   }
92   return true;
93 }
95 static bool callHasFloatingPointArgument(const CallInst *CI) {
96   for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
97        it != e; ++it) {
98     if ((*it)->getType()->isFloatingPointTy())
99       return true;
100   }
101   return false;
104 /// \brief Check whether the overloaded unary floating point function
105 /// corresponing to \a Ty is available.
106 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
107                             LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
108                             LibFunc::Func LongDoubleFn) {
109   switch (Ty->getTypeID()) {
110   case Type::FloatTyID:
111     return TLI->has(FloatFn);
112   case Type::DoubleTyID:
113     return TLI->has(DoubleFn);
114   default:
115     return TLI->has(LongDoubleFn);
116   }
119 /// \brief Returns whether \p F matches the signature expected for the
120 /// string/memory copying library function \p Func.
121 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
122 /// Their fortified (_chk) counterparts are also accepted.
123 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func,
124                                             const DataLayout *DL) {
125   FunctionType *FT = F->getFunctionType();
126   LLVMContext &Context = F->getContext();
127   Type *PCharTy = Type::getInt8PtrTy(Context);
128   Type *SizeTTy = DL ? DL->getIntPtrType(Context) : nullptr;
129   unsigned NumParams = FT->getNumParams();
131   // All string libfuncs return the same type as the first parameter.
132   if (FT->getReturnType() != FT->getParamType(0))
133     return false;
135   switch (Func) {
136   default:
137     llvm_unreachable("Can't check signature for non-string-copy libfunc.");
138   case LibFunc::stpncpy_chk:
139   case LibFunc::strncpy_chk:
140     --NumParams; // fallthrough
141   case LibFunc::stpncpy:
142   case LibFunc::strncpy: {
143     if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
144         FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
145       return false;
146     break;
147   }
148   case LibFunc::strcpy_chk:
149   case LibFunc::stpcpy_chk:
150     --NumParams; // fallthrough
151   case LibFunc::stpcpy:
152   case LibFunc::strcpy: {
153     if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
154         FT->getParamType(0) != PCharTy)
155       return false;
156     break;
157   }
158   case LibFunc::memmove_chk:
159   case LibFunc::memcpy_chk:
160     --NumParams; // fallthrough
161   case LibFunc::memmove:
162   case LibFunc::memcpy: {
163     if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
164         !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
165       return false;
166     break;
167   }
168   case LibFunc::memset_chk:
169     --NumParams; // fallthrough
170   case LibFunc::memset: {
171     if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172         !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
173       return false;
174     break;
175   }
176   }
177   // If this is a fortified libcall, the last parameter is a size_t.
178   if (NumParams == FT->getNumParams() - 1)
179     return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
180   return true;
183 //===----------------------------------------------------------------------===//
184 // Fortified Library Call Optimizations
185 //===----------------------------------------------------------------------===//
187 static bool isFortifiedCallFoldable(CallInst *CI, unsigned SizeCIOp, unsigned SizeArgOp,
188                        bool isString) {
189   if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
190     return true;
191   if (ConstantInt *SizeCI =
192           dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
193     if (SizeCI->isAllOnesValue())
194       return true;
195     if (isString) {
196       uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
197       // If the length is 0 we don't know how long it is and so we can't
198       // remove the check.
199       if (Len == 0)
200         return false;
201       return SizeCI->getZExtValue() >= Len;
202     }
203     if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getArgOperand(SizeArgOp)))
204       return SizeCI->getZExtValue() >= Arg->getZExtValue();
205   }
206   return false;
209 Value *LibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
210   Function *Callee = CI->getCalledFunction();
211   FunctionType *FT = Callee->getFunctionType();
212   LLVMContext &Context = CI->getContext();
214   // Check if this has the right signature.
215   if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
216       !FT->getParamType(0)->isPointerTy() ||
217       !FT->getParamType(1)->isPointerTy() ||
218       FT->getParamType(2) != DL->getIntPtrType(Context) ||
219       FT->getParamType(3) != DL->getIntPtrType(Context))
220     return nullptr;
222   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
223     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
224                    CI->getArgOperand(2), 1);
225     return CI->getArgOperand(0);
226   }
227   return nullptr;
230 Value *LibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
231   Function *Callee = CI->getCalledFunction();
232   FunctionType *FT = Callee->getFunctionType();
233   LLVMContext &Context = CI->getContext();
235   // Check if this has the right signature.
236   if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
237       !FT->getParamType(0)->isPointerTy() ||
238       !FT->getParamType(1)->isPointerTy() ||
239       FT->getParamType(2) != DL->getIntPtrType(Context) ||
240       FT->getParamType(3) != DL->getIntPtrType(Context))
241     return nullptr;
243   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
244     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
245                     CI->getArgOperand(2), 1);
246     return CI->getArgOperand(0);
247   }
248   return nullptr;
251 Value *LibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
252   Function *Callee = CI->getCalledFunction();
253   FunctionType *FT = Callee->getFunctionType();
254   LLVMContext &Context = CI->getContext();
256   // Check if this has the right signature.
257   if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
258       !FT->getParamType(0)->isPointerTy() ||
259       !FT->getParamType(1)->isIntegerTy() ||
260       FT->getParamType(2) != DL->getIntPtrType(Context) ||
261       FT->getParamType(3) != DL->getIntPtrType(Context))
262     return nullptr;
264   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
265     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
266     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
267     return CI->getArgOperand(0);
268   }
269   return nullptr;
272 Value *LibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
273   Function *Callee = CI->getCalledFunction();
274   StringRef Name = Callee->getName();
275   FunctionType *FT = Callee->getFunctionType();
276   LLVMContext &Context = CI->getContext();
278   // Check if this has the right signature.
279   if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
280       FT->getParamType(0) != FT->getParamType(1) ||
281       FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
282       FT->getParamType(2) != DL->getIntPtrType(Context))
283     return nullptr;
285   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
286   if (Dst == Src) // __strcpy_chk(x,x)  -> x
287     return Src;
289   // If a) we don't have any length information, or b) we know this will
290   // fit then just lower to a plain strcpy. Otherwise we'll keep our
291   // strcpy_chk call which may fail at runtime if the size is too long.
292   // TODO: It might be nice to get a maximum length out of the possible
293   // string lengths for varying.
294   if (isFortifiedCallFoldable(CI, 2, 1, true)) {
295     Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
296     return Ret;
297   } else {
298     // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
299     uint64_t Len = GetStringLength(Src);
300     if (Len == 0)
301       return nullptr;
303     // This optimization require DataLayout.
304     if (!DL)
305       return nullptr;
307     Value *Ret = EmitMemCpyChk(
308         Dst, Src, ConstantInt::get(DL->getIntPtrType(Context), Len),
309         CI->getArgOperand(2), B, DL, TLI);
310     return Ret;
311   }
312   return nullptr;
315 Value *LibCallSimplifier::optimizeStpCpyChk(CallInst *CI, IRBuilder<> &B) {
316   Function *Callee = CI->getCalledFunction();
317   StringRef Name = Callee->getName();
318   FunctionType *FT = Callee->getFunctionType();
319   LLVMContext &Context = CI->getContext();
321   // Check if this has the right signature.
322   if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
323       FT->getParamType(0) != FT->getParamType(1) ||
324       FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
325       FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
326     return nullptr;
328   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
329   if (Dst == Src) { // stpcpy(x,x)  -> x+strlen(x)
330     Value *StrLen = EmitStrLen(Src, B, DL, TLI);
331     return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
332   }
334   // If a) we don't have any length information, or b) we know this will
335   // fit then just lower to a plain stpcpy. Otherwise we'll keep our
336   // stpcpy_chk call which may fail at runtime if the size is too long.
337   // TODO: It might be nice to get a maximum length out of the possible
338   // string lengths for varying.
339   if (isFortifiedCallFoldable(CI, 2, 1, true)) {
340     Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
341     return Ret;
342   } else {
343     // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
344     uint64_t Len = GetStringLength(Src);
345     if (Len == 0)
346       return nullptr;
348     // This optimization require DataLayout.
349     if (!DL)
350       return nullptr;
352     Type *PT = FT->getParamType(0);
353     Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
354     Value *DstEnd =
355         B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
356     if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
357       return nullptr;
358     return DstEnd;
359   }
360   return nullptr;
363 Value *LibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
364   Function *Callee = CI->getCalledFunction();
365   StringRef Name = Callee->getName();
366   FunctionType *FT = Callee->getFunctionType();
367   LLVMContext &Context = CI->getContext();
369   // Check if this has the right signature.
370   if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
371       FT->getParamType(0) != FT->getParamType(1) ||
372       FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
373       !FT->getParamType(2)->isIntegerTy() ||
374       FT->getParamType(3) != DL->getIntPtrType(Context))
375     return nullptr;
377   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
378     Value *Ret =
379         EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
380                     CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
381     return Ret;
382   }
383   return nullptr;
386 //===----------------------------------------------------------------------===//
387 // String and Memory Library Call Optimizations
388 //===----------------------------------------------------------------------===//
390 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
391   Function *Callee = CI->getCalledFunction();
392   // Verify the "strcat" function prototype.
393   FunctionType *FT = Callee->getFunctionType();
394   if (FT->getNumParams() != 2||
395       FT->getReturnType() != B.getInt8PtrTy() ||
396       FT->getParamType(0) != FT->getReturnType() ||
397       FT->getParamType(1) != FT->getReturnType())
398     return nullptr;
400   // Extract some information from the instruction
401   Value *Dst = CI->getArgOperand(0);
402   Value *Src = CI->getArgOperand(1);
404   // See if we can get the length of the input string.
405   uint64_t Len = GetStringLength(Src);
406   if (Len == 0)
407     return nullptr;
408   --Len; // Unbias length.
410   // Handle the simple, do-nothing case: strcat(x, "") -> x
411   if (Len == 0)
412     return Dst;
414   // These optimizations require DataLayout.
415   if (!DL)
416     return nullptr;
418   return emitStrLenMemCpy(Src, Dst, Len, B);
421 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
422                                            IRBuilder<> &B) {
423   // We need to find the end of the destination string.  That's where the
424   // memory is to be moved to. We just generate a call to strlen.
425   Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
426   if (!DstLen)
427     return nullptr;
429   // Now that we have the destination's length, we must index into the
430   // destination's pointer to get the actual memcpy destination (end of
431   // the string .. we're concatenating).
432   Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
434   // We have enough information to now generate the memcpy call to do the
435   // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
436   B.CreateMemCpy(
437       CpyDst, Src,
438       ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
439   return Dst;
442 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
443   Function *Callee = CI->getCalledFunction();
444   // Verify the "strncat" function prototype.
445   FunctionType *FT = Callee->getFunctionType();
446   if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
447       FT->getParamType(0) != FT->getReturnType() ||
448       FT->getParamType(1) != FT->getReturnType() ||
449       !FT->getParamType(2)->isIntegerTy())
450     return nullptr;
452   // Extract some information from the instruction
453   Value *Dst = CI->getArgOperand(0);
454   Value *Src = CI->getArgOperand(1);
455   uint64_t Len;
457   // We don't do anything if length is not constant
458   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
459     Len = LengthArg->getZExtValue();
460   else
461     return nullptr;
463   // See if we can get the length of the input string.
464   uint64_t SrcLen = GetStringLength(Src);
465   if (SrcLen == 0)
466     return nullptr;
467   --SrcLen; // Unbias length.
469   // Handle the simple, do-nothing cases:
470   // strncat(x, "", c) -> x
471   // strncat(x,  c, 0) -> x
472   if (SrcLen == 0 || Len == 0)
473     return Dst;
475   // These optimizations require DataLayout.
476   if (!DL)
477     return nullptr;
479   // We don't optimize this case
480   if (Len < SrcLen)
481     return nullptr;
483   // strncat(x, s, c) -> strcat(x, s)
484   // s is constant so the strcat can be optimized further
485   return emitStrLenMemCpy(Src, Dst, SrcLen, B);
488 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
489   Function *Callee = CI->getCalledFunction();
490   // Verify the "strchr" function prototype.
491   FunctionType *FT = Callee->getFunctionType();
492   if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
493       FT->getParamType(0) != FT->getReturnType() ||
494       !FT->getParamType(1)->isIntegerTy(32))
495     return nullptr;
497   Value *SrcStr = CI->getArgOperand(0);
499   // If the second operand is non-constant, see if we can compute the length
500   // of the input string and turn this into memchr.
501   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
502   if (!CharC) {
503     // These optimizations require DataLayout.
504     if (!DL)
505       return nullptr;
507     uint64_t Len = GetStringLength(SrcStr);
508     if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
509       return nullptr;
511     return EmitMemChr(
512         SrcStr, CI->getArgOperand(1), // include nul.
513         ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
514   }
516   // Otherwise, the character is a constant, see if the first argument is
517   // a string literal.  If so, we can constant fold.
518   StringRef Str;
519   if (!getConstantStringInfo(SrcStr, Str)) {
520     if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
521       return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
522     return nullptr;
523   }
525   // Compute the offset, make sure to handle the case when we're searching for
526   // zero (a weird way to spell strlen).
527   size_t I = (0xFF & CharC->getSExtValue()) == 0
528                  ? Str.size()
529                  : Str.find(CharC->getSExtValue());
530   if (I == StringRef::npos) // Didn't find the char.  strchr returns null.
531     return Constant::getNullValue(CI->getType());
533   // strchr(s+n,c)  -> gep(s+n+i,c)
534   return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
537 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
538   Function *Callee = CI->getCalledFunction();
539   // Verify the "strrchr" function prototype.
540   FunctionType *FT = Callee->getFunctionType();
541   if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
542       FT->getParamType(0) != FT->getReturnType() ||
543       !FT->getParamType(1)->isIntegerTy(32))
544     return nullptr;
546   Value *SrcStr = CI->getArgOperand(0);
547   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
549   // Cannot fold anything if we're not looking for a constant.
550   if (!CharC)
551     return nullptr;
553   StringRef Str;
554   if (!getConstantStringInfo(SrcStr, Str)) {
555     // strrchr(s, 0) -> strchr(s, 0)
556     if (DL && CharC->isZero())
557       return EmitStrChr(SrcStr, '\0', B, DL, TLI);
558     return nullptr;
559   }
561   // Compute the offset.
562   size_t I = (0xFF & CharC->getSExtValue()) == 0
563                  ? Str.size()
564                  : Str.rfind(CharC->getSExtValue());
565   if (I == StringRef::npos) // Didn't find the char. Return null.
566     return Constant::getNullValue(CI->getType());
568   // strrchr(s+n,c) -> gep(s+n+i,c)
569   return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
572 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
573   Function *Callee = CI->getCalledFunction();
574   // Verify the "strcmp" function prototype.
575   FunctionType *FT = Callee->getFunctionType();
576   if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
577       FT->getParamType(0) != FT->getParamType(1) ||
578       FT->getParamType(0) != B.getInt8PtrTy())
579     return nullptr;
581   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
582   if (Str1P == Str2P) // strcmp(x,x)  -> 0
583     return ConstantInt::get(CI->getType(), 0);
585   StringRef Str1, Str2;
586   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
587   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
589   // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
590   if (HasStr1 && HasStr2)
591     return ConstantInt::get(CI->getType(), Str1.compare(Str2));
593   if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
594     return B.CreateNeg(
595         B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
597   if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
598     return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
600   // strcmp(P, "x") -> memcmp(P, "x", 2)
601   uint64_t Len1 = GetStringLength(Str1P);
602   uint64_t Len2 = GetStringLength(Str2P);
603   if (Len1 && Len2) {
604     // These optimizations require DataLayout.
605     if (!DL)
606       return nullptr;
608     return EmitMemCmp(Str1P, Str2P,
609                       ConstantInt::get(DL->getIntPtrType(CI->getContext()),
610                                        std::min(Len1, Len2)),
611                       B, DL, TLI);
612   }
614   return nullptr;
617 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
618   Function *Callee = CI->getCalledFunction();
619   // Verify the "strncmp" function prototype.
620   FunctionType *FT = Callee->getFunctionType();
621   if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
622       FT->getParamType(0) != FT->getParamType(1) ||
623       FT->getParamType(0) != B.getInt8PtrTy() ||
624       !FT->getParamType(2)->isIntegerTy())
625     return nullptr;
627   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
628   if (Str1P == Str2P) // strncmp(x,x,n)  -> 0
629     return ConstantInt::get(CI->getType(), 0);
631   // Get the length argument if it is constant.
632   uint64_t Length;
633   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
634     Length = LengthArg->getZExtValue();
635   else
636     return nullptr;
638   if (Length == 0) // strncmp(x,y,0)   -> 0
639     return ConstantInt::get(CI->getType(), 0);
641   if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
642     return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
644   StringRef Str1, Str2;
645   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
646   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
648   // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
649   if (HasStr1 && HasStr2) {
650     StringRef SubStr1 = Str1.substr(0, Length);
651     StringRef SubStr2 = Str2.substr(0, Length);
652     return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
653   }
655   if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
656     return B.CreateNeg(
657         B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
659   if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
660     return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
662   return nullptr;
665 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
666   Function *Callee = CI->getCalledFunction();
668   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy, DL))
669     return nullptr;
671   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
672   if (Dst == Src) // strcpy(x,x)  -> x
673     return Src;
675   // These optimizations require DataLayout.
676   if (!DL)
677     return nullptr;
679   // See if we can get the length of the input string.
680   uint64_t Len = GetStringLength(Src);
681   if (Len == 0)
682     return nullptr;
684   // We have enough information to now generate the memcpy call to do the
685   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
686   B.CreateMemCpy(Dst, Src,
687                  ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
688   return Dst;
691 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
692   Function *Callee = CI->getCalledFunction();
693   // Verify the "stpcpy" function prototype.
694   FunctionType *FT = Callee->getFunctionType();
696   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy, DL))
697     return nullptr;
699   // These optimizations require DataLayout.
700   if (!DL)
701     return nullptr;
703   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
704   if (Dst == Src) { // stpcpy(x,x)  -> x+strlen(x)
705     Value *StrLen = EmitStrLen(Src, B, DL, TLI);
706     return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
707   }
709   // See if we can get the length of the input string.
710   uint64_t Len = GetStringLength(Src);
711   if (Len == 0)
712     return nullptr;
714   Type *PT = FT->getParamType(0);
715   Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
716   Value *DstEnd =
717       B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
719   // We have enough information to now generate the memcpy call to do the
720   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
721   B.CreateMemCpy(Dst, Src, LenV, 1);
722   return DstEnd;
725 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
726   Function *Callee = CI->getCalledFunction();
727   FunctionType *FT = Callee->getFunctionType();
729   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy, DL))
730     return nullptr;
732   Value *Dst = CI->getArgOperand(0);
733   Value *Src = CI->getArgOperand(1);
734   Value *LenOp = CI->getArgOperand(2);
736   // See if we can get the length of the input string.
737   uint64_t SrcLen = GetStringLength(Src);
738   if (SrcLen == 0)
739     return nullptr;
740   --SrcLen;
742   if (SrcLen == 0) {
743     // strncpy(x, "", y) -> memset(x, '\0', y, 1)
744     B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
745     return Dst;
746   }
748   uint64_t Len;
749   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
750     Len = LengthArg->getZExtValue();
751   else
752     return nullptr;
754   if (Len == 0)
755     return Dst; // strncpy(x, y, 0) -> x
757   // These optimizations require DataLayout.
758   if (!DL)
759     return nullptr;
761   // Let strncpy handle the zero padding
762   if (Len > SrcLen + 1)
763     return nullptr;
765   Type *PT = FT->getParamType(0);
766   // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
767   B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
769   return Dst;
772 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
773   Function *Callee = CI->getCalledFunction();
774   FunctionType *FT = Callee->getFunctionType();
775   if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
776       !FT->getReturnType()->isIntegerTy())
777     return nullptr;
779   Value *Src = CI->getArgOperand(0);
781   // Constant folding: strlen("xyz") -> 3
782   if (uint64_t Len = GetStringLength(Src))
783     return ConstantInt::get(CI->getType(), Len - 1);
785   // strlen(x?"foo":"bars") --> x ? 3 : 4
786   if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
787     uint64_t LenTrue = GetStringLength(SI->getTrueValue());
788     uint64_t LenFalse = GetStringLength(SI->getFalseValue());
789     if (LenTrue && LenFalse) {
790       Function *Caller = CI->getParent()->getParent();
791       emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
792                              SI->getDebugLoc(),
793                              "folded strlen(select) to select of constants");
794       return B.CreateSelect(SI->getCondition(),
795                             ConstantInt::get(CI->getType(), LenTrue - 1),
796                             ConstantInt::get(CI->getType(), LenFalse - 1));
797     }
798   }
800   // strlen(x) != 0 --> *x != 0
801   // strlen(x) == 0 --> *x == 0
802   if (isOnlyUsedInZeroEqualityComparison(CI))
803     return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
805   return nullptr;
808 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
809   Function *Callee = CI->getCalledFunction();
810   FunctionType *FT = Callee->getFunctionType();
811   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
812       FT->getParamType(1) != FT->getParamType(0) ||
813       FT->getReturnType() != FT->getParamType(0))
814     return nullptr;
816   StringRef S1, S2;
817   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
818   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
820   // strpbrk(s, "") -> nullptr
821   // strpbrk("", s) -> nullptr
822   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
823     return Constant::getNullValue(CI->getType());
825   // Constant folding.
826   if (HasS1 && HasS2) {
827     size_t I = S1.find_first_of(S2);
828     if (I == StringRef::npos) // No match.
829       return Constant::getNullValue(CI->getType());
831     return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
832   }
834   // strpbrk(s, "a") -> strchr(s, 'a')
835   if (DL && HasS2 && S2.size() == 1)
836     return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
838   return nullptr;
841 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
842   Function *Callee = CI->getCalledFunction();
843   FunctionType *FT = Callee->getFunctionType();
844   if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
845       !FT->getParamType(0)->isPointerTy() ||
846       !FT->getParamType(1)->isPointerTy())
847     return nullptr;
849   Value *EndPtr = CI->getArgOperand(1);
850   if (isa<ConstantPointerNull>(EndPtr)) {
851     // With a null EndPtr, this function won't capture the main argument.
852     // It would be readonly too, except that it still may write to errno.
853     CI->addAttribute(1, Attribute::NoCapture);
854   }
856   return nullptr;
859 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
860   Function *Callee = CI->getCalledFunction();
861   FunctionType *FT = Callee->getFunctionType();
862   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
863       FT->getParamType(1) != FT->getParamType(0) ||
864       !FT->getReturnType()->isIntegerTy())
865     return nullptr;
867   StringRef S1, S2;
868   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
869   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
871   // strspn(s, "") -> 0
872   // strspn("", s) -> 0
873   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
874     return Constant::getNullValue(CI->getType());
876   // Constant folding.
877   if (HasS1 && HasS2) {
878     size_t Pos = S1.find_first_not_of(S2);
879     if (Pos == StringRef::npos)
880       Pos = S1.size();
881     return ConstantInt::get(CI->getType(), Pos);
882   }
884   return nullptr;
887 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
888   Function *Callee = CI->getCalledFunction();
889   FunctionType *FT = Callee->getFunctionType();
890   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
891       FT->getParamType(1) != FT->getParamType(0) ||
892       !FT->getReturnType()->isIntegerTy())
893     return nullptr;
895   StringRef S1, S2;
896   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
897   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
899   // strcspn("", s) -> 0
900   if (HasS1 && S1.empty())
901     return Constant::getNullValue(CI->getType());
903   // Constant folding.
904   if (HasS1 && HasS2) {
905     size_t Pos = S1.find_first_of(S2);
906     if (Pos == StringRef::npos)
907       Pos = S1.size();
908     return ConstantInt::get(CI->getType(), Pos);
909   }
911   // strcspn(s, "") -> strlen(s)
912   if (DL && HasS2 && S2.empty())
913     return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
915   return nullptr;
918 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
919   Function *Callee = CI->getCalledFunction();
920   FunctionType *FT = Callee->getFunctionType();
921   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
922       !FT->getParamType(1)->isPointerTy() ||
923       !FT->getReturnType()->isPointerTy())
924     return nullptr;
926   // fold strstr(x, x) -> x.
927   if (CI->getArgOperand(0) == CI->getArgOperand(1))
928     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
930   // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
931   if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
932     Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
933     if (!StrLen)
934       return nullptr;
935     Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
936                                  StrLen, B, DL, TLI);
937     if (!StrNCmp)
938       return nullptr;
939     for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
940       ICmpInst *Old = cast<ICmpInst>(*UI++);
941       Value *Cmp =
942           B.CreateICmp(Old->getPredicate(), StrNCmp,
943                        ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
944       replaceAllUsesWith(Old, Cmp);
945     }
946     return CI;
947   }
949   // See if either input string is a constant string.
950   StringRef SearchStr, ToFindStr;
951   bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
952   bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
954   // fold strstr(x, "") -> x.
955   if (HasStr2 && ToFindStr.empty())
956     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
958   // If both strings are known, constant fold it.
959   if (HasStr1 && HasStr2) {
960     size_t Offset = SearchStr.find(ToFindStr);
962     if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
963       return Constant::getNullValue(CI->getType());
965     // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
966     Value *Result = CastToCStr(CI->getArgOperand(0), B);
967     Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
968     return B.CreateBitCast(Result, CI->getType());
969   }
971   // fold strstr(x, "y") -> strchr(x, 'y').
972   if (HasStr2 && ToFindStr.size() == 1) {
973     Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
974     return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
975   }
976   return nullptr;
979 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
980   Function *Callee = CI->getCalledFunction();
981   FunctionType *FT = Callee->getFunctionType();
982   if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
983       !FT->getParamType(1)->isPointerTy() ||
984       !FT->getReturnType()->isIntegerTy(32))
985     return nullptr;
987   Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
989   if (LHS == RHS) // memcmp(s,s,x) -> 0
990     return Constant::getNullValue(CI->getType());
992   // Make sure we have a constant length.
993   ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
994   if (!LenC)
995     return nullptr;
996   uint64_t Len = LenC->getZExtValue();
998   if (Len == 0) // memcmp(s1,s2,0) -> 0
999     return Constant::getNullValue(CI->getType());
1001   // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1002   if (Len == 1) {
1003     Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
1004                                CI->getType(), "lhsv");
1005     Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
1006                                CI->getType(), "rhsv");
1007     return B.CreateSub(LHSV, RHSV, "chardiff");
1008   }
1010   // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1011   StringRef LHSStr, RHSStr;
1012   if (getConstantStringInfo(LHS, LHSStr) &&
1013       getConstantStringInfo(RHS, RHSStr)) {
1014     // Make sure we're not reading out-of-bounds memory.
1015     if (Len > LHSStr.size() || Len > RHSStr.size())
1016       return nullptr;
1017     // Fold the memcmp and normalize the result.  This way we get consistent
1018     // results across multiple platforms.
1019     uint64_t Ret = 0;
1020     int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1021     if (Cmp < 0)
1022       Ret = -1;
1023     else if (Cmp > 0)
1024       Ret = 1;
1025     return ConstantInt::get(CI->getType(), Ret);
1026   }
1028   return nullptr;
1031 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
1032   Function *Callee = CI->getCalledFunction();
1033   // These optimizations require DataLayout.
1034   if (!DL)
1035     return nullptr;
1037   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy, DL))
1038     return nullptr;
1040   // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1041   B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1042                  CI->getArgOperand(2), 1);
1043   return CI->getArgOperand(0);
1046 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
1047   Function *Callee = CI->getCalledFunction();
1048   // These optimizations require DataLayout.
1049   if (!DL)
1050     return nullptr;
1052   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove, DL))
1053     return nullptr;
1055   // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1056   B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1057                   CI->getArgOperand(2), 1);
1058   return CI->getArgOperand(0);
1061 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1062   Function *Callee = CI->getCalledFunction();
1063   // These optimizations require DataLayout.
1064   if (!DL)
1065     return nullptr;
1067   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset, DL))
1068     return nullptr;
1070   // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1071   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1072   B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1073   return CI->getArgOperand(0);
1076 //===----------------------------------------------------------------------===//
1077 // Math Library Optimizations
1078 //===----------------------------------------------------------------------===//
1080 /// Return a variant of Val with float type.
1081 /// Currently this works in two cases: If Val is an FPExtension of a float
1082 /// value to something bigger, simply return the operand.
1083 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1084 /// loss of precision do so.
1085 static Value *valueHasFloatPrecision(Value *Val) {
1086   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1087     Value *Op = Cast->getOperand(0);
1088     if (Op->getType()->isFloatTy())
1089       return Op;
1090   }
1091   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1092     APFloat F = Const->getValueAPF();
1093     bool losesInfo;
1094     (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1095                     &losesInfo);
1096     if (!losesInfo)
1097       return ConstantFP::get(Const->getContext(), F);
1098   }
1099   return nullptr;
1102 //===----------------------------------------------------------------------===//
1103 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1105 Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1106                                                 bool CheckRetType) {
1107   Function *Callee = CI->getCalledFunction();
1108   FunctionType *FT = Callee->getFunctionType();
1109   if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1110       !FT->getParamType(0)->isDoubleTy())
1111     return nullptr;
1113   if (CheckRetType) {
1114     // Check if all the uses for function like 'sin' are converted to float.
1115     for (User *U : CI->users()) {
1116       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1117       if (!Cast || !Cast->getType()->isFloatTy())
1118         return nullptr;
1119     }
1120   }
1122   // If this is something like 'floor((double)floatval)', convert to floorf.
1123   Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1124   if (V == nullptr)
1125     return nullptr;
1127   // floor((double)floatval) -> (double)floorf(floatval)
1128   if (Callee->isIntrinsic()) {
1129     Module *M = CI->getParent()->getParent()->getParent();
1130     Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
1131     Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1132     V = B.CreateCall(F, V);
1133   } else {
1134     // The call is a library call rather than an intrinsic.
1135     V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1136   }
1138   return B.CreateFPExt(V, B.getDoubleTy());
1141 // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1142 Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1143   Function *Callee = CI->getCalledFunction();
1144   FunctionType *FT = Callee->getFunctionType();
1145   // Just make sure this has 2 arguments of the same FP type, which match the
1146   // result type.
1147   if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1148       FT->getParamType(0) != FT->getParamType(1) ||
1149       !FT->getParamType(0)->isFloatingPointTy())
1150     return nullptr;
1152   // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1153   // or fmin(1.0, (double)floatval), then we convert it to fminf.
1154   Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1155   if (V1 == nullptr)
1156     return nullptr;
1157   Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1158   if (V2 == nullptr)
1159     return nullptr;
1161   // fmin((double)floatval1, (double)floatval2)
1162   //                      -> (double)fminf(floatval1, floatval2)
1163   // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1164   Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1165                                    Callee->getAttributes());
1166   return B.CreateFPExt(V, B.getDoubleTy());
1169 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1170   Function *Callee = CI->getCalledFunction();
1171   Value *Ret = nullptr;
1172   if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1173     Ret = optimizeUnaryDoubleFP(CI, B, true);
1174   }
1176   FunctionType *FT = Callee->getFunctionType();
1177   // Just make sure this has 1 argument of FP type, which matches the
1178   // result type.
1179   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1180       !FT->getParamType(0)->isFloatingPointTy())
1181     return Ret;
1183   // cos(-x) -> cos(x)
1184   Value *Op1 = CI->getArgOperand(0);
1185   if (BinaryOperator::isFNeg(Op1)) {
1186     BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1187     return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1188   }
1189   return Ret;
1192 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1193   Function *Callee = CI->getCalledFunction();
1195   Value *Ret = nullptr;
1196   if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1197     Ret = optimizeUnaryDoubleFP(CI, B, true);
1198   }
1200   FunctionType *FT = Callee->getFunctionType();
1201   // Just make sure this has 2 arguments of the same FP type, which match the
1202   // result type.
1203   if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1204       FT->getParamType(0) != FT->getParamType(1) ||
1205       !FT->getParamType(0)->isFloatingPointTy())
1206     return Ret;
1208   Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1209   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1210     // pow(1.0, x) -> 1.0
1211     if (Op1C->isExactlyValue(1.0))
1212       return Op1C;
1213     // pow(2.0, x) -> exp2(x)
1214     if (Op1C->isExactlyValue(2.0) &&
1215         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1216                         LibFunc::exp2l))
1217       return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1218     // pow(10.0, x) -> exp10(x)
1219     if (Op1C->isExactlyValue(10.0) &&
1220         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1221                         LibFunc::exp10l))
1222       return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1223                                   Callee->getAttributes());
1224   }
1226   ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1227   if (!Op2C)
1228     return Ret;
1230   if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1231     return ConstantFP::get(CI->getType(), 1.0);
1233   if (Op2C->isExactlyValue(0.5) &&
1234       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1235                       LibFunc::sqrtl) &&
1236       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1237                       LibFunc::fabsl)) {
1238     // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1239     // This is faster than calling pow, and still handles negative zero
1240     // and negative infinity correctly.
1241     // TODO: In fast-math mode, this could be just sqrt(x).
1242     // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1243     Value *Inf = ConstantFP::getInfinity(CI->getType());
1244     Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1245     Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1246     Value *FAbs =
1247         EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1248     Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1249     Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1250     return Sel;
1251   }
1253   if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1254     return Op1;
1255   if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1256     return B.CreateFMul(Op1, Op1, "pow2");
1257   if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1258     return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1259   return nullptr;
1262 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1263   Function *Callee = CI->getCalledFunction();
1264   Function *Caller = CI->getParent()->getParent();
1266   Value *Ret = nullptr;
1267   if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1268       TLI->has(LibFunc::exp2f)) {
1269     Ret = optimizeUnaryDoubleFP(CI, B, true);
1270   }
1272   FunctionType *FT = Callee->getFunctionType();
1273   // Just make sure this has 1 argument of FP type, which matches the
1274   // result type.
1275   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1276       !FT->getParamType(0)->isFloatingPointTy())
1277     return Ret;
1279   Value *Op = CI->getArgOperand(0);
1280   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1281   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1282   LibFunc::Func LdExp = LibFunc::ldexpl;
1283   if (Op->getType()->isFloatTy())
1284     LdExp = LibFunc::ldexpf;
1285   else if (Op->getType()->isDoubleTy())
1286     LdExp = LibFunc::ldexp;
1288   if (TLI->has(LdExp)) {
1289     Value *LdExpArg = nullptr;
1290     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1291       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1292         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1293     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1294       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1295         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1296     }
1298     if (LdExpArg) {
1299       Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1300       if (!Op->getType()->isFloatTy())
1301         One = ConstantExpr::getFPExtend(One, Op->getType());
1303       Module *M = Caller->getParent();
1304       Value *Callee =
1305           M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1306                                  Op->getType(), B.getInt32Ty(), nullptr);
1307       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1308       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1309         CI->setCallingConv(F->getCallingConv());
1311       return CI;
1312     }
1313   }
1314   return Ret;
1317 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1318   Function *Callee = CI->getCalledFunction();
1320   Value *Ret = nullptr;
1321   if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1322     Ret = optimizeUnaryDoubleFP(CI, B, false);
1323   }
1325   FunctionType *FT = Callee->getFunctionType();
1326   // Make sure this has 1 argument of FP type which matches the result type.
1327   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1328       !FT->getParamType(0)->isFloatingPointTy())
1329     return Ret;
1331   Value *Op = CI->getArgOperand(0);
1332   if (Instruction *I = dyn_cast<Instruction>(Op)) {
1333     // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1334     if (I->getOpcode() == Instruction::FMul)
1335       if (I->getOperand(0) == I->getOperand(1))
1336         return Op;
1337   }
1338   return Ret;
1341 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1342   Function *Callee = CI->getCalledFunction();
1343   
1344   Value *Ret = nullptr;
1345   if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1346                                    Callee->getIntrinsicID() == Intrinsic::sqrt))
1347     Ret = optimizeUnaryDoubleFP(CI, B, true);
1349   // FIXME: For finer-grain optimization, we need intrinsics to have the same
1350   // fast-math flag decorations that are applied to FP instructions. For now,
1351   // we have to rely on the function-level unsafe-fp-math attribute to do this
1352   // optimization because there's no other way to express that the sqrt can be
1353   // reassociated.
1354   Function *F = CI->getParent()->getParent();
1355   if (F->hasFnAttribute("unsafe-fp-math")) {
1356     // Check for unsafe-fp-math = true.
1357     Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1358     if (Attr.getValueAsString() != "true")
1359       return Ret;
1360   }
1361   Value *Op = CI->getArgOperand(0);
1362   if (Instruction *I = dyn_cast<Instruction>(Op)) {
1363     if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1364       // We're looking for a repeated factor in a multiplication tree,
1365       // so we can do this fold: sqrt(x * x) -> fabs(x);
1366       // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1367       Value *Op0 = I->getOperand(0);
1368       Value *Op1 = I->getOperand(1);
1369       Value *RepeatOp = nullptr;
1370       Value *OtherOp = nullptr;
1371       if (Op0 == Op1) {
1372         // Simple match: the operands of the multiply are identical.
1373         RepeatOp = Op0;
1374       } else {
1375         // Look for a more complicated pattern: one of the operands is itself
1376         // a multiply, so search for a common factor in that multiply.
1377         // Note: We don't bother looking any deeper than this first level or for
1378         // variations of this pattern because instcombine's visitFMUL and/or the
1379         // reassociation pass should give us this form.
1380         Value *OtherMul0, *OtherMul1;
1381         if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1382           // Pattern: sqrt((x * y) * z)
1383           if (OtherMul0 == OtherMul1) {
1384             // Matched: sqrt((x * x) * z)
1385             RepeatOp = OtherMul0;
1386             OtherOp = Op1;
1387           }
1388         }
1389       }
1390       if (RepeatOp) {
1391         // Fast math flags for any created instructions should match the sqrt
1392         // and multiply.
1393         // FIXME: We're not checking the sqrt because it doesn't have
1394         // fast-math-flags (see earlier comment).
1395         IRBuilder<true, ConstantFolder,
1396           IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1397         B.SetFastMathFlags(I->getFastMathFlags());
1398         // If we found a repeated factor, hoist it out of the square root and
1399         // replace it with the fabs of that factor.
1400         Module *M = Callee->getParent();
1401         Type *ArgType = Op->getType();
1402         Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1403         Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1404         if (OtherOp) {
1405           // If we found a non-repeated factor, we still need to get its square
1406           // root. We then multiply that by the value that was simplified out
1407           // of the square root calculation.
1408           Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1409           Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1410           return B.CreateFMul(FabsCall, SqrtCall);
1411         }
1412         return FabsCall;
1413       }
1414     }
1415   }
1416   return Ret;
1419 static bool isTrigLibCall(CallInst *CI);
1420 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1421                              bool UseFloat, Value *&Sin, Value *&Cos,
1422                              Value *&SinCos);
1424 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1426   // Make sure the prototype is as expected, otherwise the rest of the
1427   // function is probably invalid and likely to abort.
1428   if (!isTrigLibCall(CI))
1429     return nullptr;
1431   Value *Arg = CI->getArgOperand(0);
1432   SmallVector<CallInst *, 1> SinCalls;
1433   SmallVector<CallInst *, 1> CosCalls;
1434   SmallVector<CallInst *, 1> SinCosCalls;
1436   bool IsFloat = Arg->getType()->isFloatTy();
1438   // Look for all compatible sinpi, cospi and sincospi calls with the same
1439   // argument. If there are enough (in some sense) we can make the
1440   // substitution.
1441   for (User *U : Arg->users())
1442     classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1443                    SinCosCalls);
1445   // It's only worthwhile if both sinpi and cospi are actually used.
1446   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1447     return nullptr;
1449   Value *Sin, *Cos, *SinCos;
1450   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1452   replaceTrigInsts(SinCalls, Sin);
1453   replaceTrigInsts(CosCalls, Cos);
1454   replaceTrigInsts(SinCosCalls, SinCos);
1456   return nullptr;
1459 static bool isTrigLibCall(CallInst *CI) {
1460   Function *Callee = CI->getCalledFunction();
1461   FunctionType *FT = Callee->getFunctionType();
1463   // We can only hope to do anything useful if we can ignore things like errno
1464   // and floating-point exceptions.
1465   bool AttributesSafe =
1466       CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1468   // Other than that we need float(float) or double(double)
1469   return AttributesSafe && FT->getNumParams() == 1 &&
1470          FT->getReturnType() == FT->getParamType(0) &&
1471          (FT->getParamType(0)->isFloatTy() ||
1472           FT->getParamType(0)->isDoubleTy());
1475 void
1476 LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1477                                   SmallVectorImpl<CallInst *> &SinCalls,
1478                                   SmallVectorImpl<CallInst *> &CosCalls,
1479                                   SmallVectorImpl<CallInst *> &SinCosCalls) {
1480   CallInst *CI = dyn_cast<CallInst>(Val);
1482   if (!CI)
1483     return;
1485   Function *Callee = CI->getCalledFunction();
1486   StringRef FuncName = Callee->getName();
1487   LibFunc::Func Func;
1488   if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1489     return;
1491   if (IsFloat) {
1492     if (Func == LibFunc::sinpif)
1493       SinCalls.push_back(CI);
1494     else if (Func == LibFunc::cospif)
1495       CosCalls.push_back(CI);
1496     else if (Func == LibFunc::sincospif_stret)
1497       SinCosCalls.push_back(CI);
1498   } else {
1499     if (Func == LibFunc::sinpi)
1500       SinCalls.push_back(CI);
1501     else if (Func == LibFunc::cospi)
1502       CosCalls.push_back(CI);
1503     else if (Func == LibFunc::sincospi_stret)
1504       SinCosCalls.push_back(CI);
1505   }
1508 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1509                                          Value *Res) {
1510   for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1511        I != E; ++I) {
1512     replaceAllUsesWith(*I, Res);
1513   }
1516 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1517                       bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1518   Type *ArgTy = Arg->getType();
1519   Type *ResTy;
1520   StringRef Name;
1522   Triple T(OrigCallee->getParent()->getTargetTriple());
1523   if (UseFloat) {
1524     Name = "__sincospif_stret";
1526     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1527     // x86_64 can't use {float, float} since that would be returned in both
1528     // xmm0 and xmm1, which isn't what a real struct would do.
1529     ResTy = T.getArch() == Triple::x86_64
1530                 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1531                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1532   } else {
1533     Name = "__sincospi_stret";
1534     ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1535   }
1537   Module *M = OrigCallee->getParent();
1538   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1539                                          ResTy, ArgTy, nullptr);
1541   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1542     // If the argument is an instruction, it must dominate all uses so put our
1543     // sincos call there.
1544     BasicBlock::iterator Loc = ArgInst;
1545     B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1546   } else {
1547     // Otherwise (e.g. for a constant) the beginning of the function is as
1548     // good a place as any.
1549     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1550     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1551   }
1553   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1555   if (SinCos->getType()->isStructTy()) {
1556     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1557     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1558   } else {
1559     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1560                                  "sinpi");
1561     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1562                                  "cospi");
1563   }
1566 //===----------------------------------------------------------------------===//
1567 // Integer Library Call Optimizations
1568 //===----------------------------------------------------------------------===//
1570 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1571   Function *Callee = CI->getCalledFunction();
1572   FunctionType *FT = Callee->getFunctionType();
1573   // Just make sure this has 2 arguments of the same FP type, which match the
1574   // result type.
1575   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1576       !FT->getParamType(0)->isIntegerTy())
1577     return nullptr;
1579   Value *Op = CI->getArgOperand(0);
1581   // Constant fold.
1582   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1583     if (CI->isZero()) // ffs(0) -> 0.
1584       return B.getInt32(0);
1585     // ffs(c) -> cttz(c)+1
1586     return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1587   }
1589   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1590   Type *ArgType = Op->getType();
1591   Value *F =
1592       Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1593   Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1594   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1595   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1597   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1598   return B.CreateSelect(Cond, V, B.getInt32(0));
1601 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1602   Function *Callee = CI->getCalledFunction();
1603   FunctionType *FT = Callee->getFunctionType();
1604   // We require integer(integer) where the types agree.
1605   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1606       FT->getParamType(0) != FT->getReturnType())
1607     return nullptr;
1609   // abs(x) -> x >s -1 ? x : -x
1610   Value *Op = CI->getArgOperand(0);
1611   Value *Pos =
1612       B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1613   Value *Neg = B.CreateNeg(Op, "neg");
1614   return B.CreateSelect(Pos, Op, Neg);
1617 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1618   Function *Callee = CI->getCalledFunction();
1619   FunctionType *FT = Callee->getFunctionType();
1620   // We require integer(i32)
1621   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1622       !FT->getParamType(0)->isIntegerTy(32))
1623     return nullptr;
1625   // isdigit(c) -> (c-'0') <u 10
1626   Value *Op = CI->getArgOperand(0);
1627   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1628   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1629   return B.CreateZExt(Op, CI->getType());
1632 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1633   Function *Callee = CI->getCalledFunction();
1634   FunctionType *FT = Callee->getFunctionType();
1635   // We require integer(i32)
1636   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1637       !FT->getParamType(0)->isIntegerTy(32))
1638     return nullptr;
1640   // isascii(c) -> c <u 128
1641   Value *Op = CI->getArgOperand(0);
1642   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1643   return B.CreateZExt(Op, CI->getType());
1646 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1647   Function *Callee = CI->getCalledFunction();
1648   FunctionType *FT = Callee->getFunctionType();
1649   // We require i32(i32)
1650   if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1651       !FT->getParamType(0)->isIntegerTy(32))
1652     return nullptr;
1654   // toascii(c) -> c & 0x7f
1655   return B.CreateAnd(CI->getArgOperand(0),
1656                      ConstantInt::get(CI->getType(), 0x7F));
1659 //===----------------------------------------------------------------------===//
1660 // Formatting and IO Library Call Optimizations
1661 //===----------------------------------------------------------------------===//
1663 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1665 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1666                                                  int StreamArg) {
1667   // Error reporting calls should be cold, mark them as such.
1668   // This applies even to non-builtin calls: it is only a hint and applies to
1669   // functions that the frontend might not understand as builtins.
1671   // This heuristic was suggested in:
1672   // Improving Static Branch Prediction in a Compiler
1673   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1674   // Proceedings of PACT'98, Oct. 1998, IEEE
1675   Function *Callee = CI->getCalledFunction();
1677   if (!CI->hasFnAttr(Attribute::Cold) &&
1678       isReportingError(Callee, CI, StreamArg)) {
1679     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1680   }
1682   return nullptr;
1685 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1686   if (!ColdErrorCalls)
1687     return false;
1689   if (!Callee || !Callee->isDeclaration())
1690     return false;
1692   if (StreamArg < 0)
1693     return true;
1695   // These functions might be considered cold, but only if their stream
1696   // argument is stderr.
1698   if (StreamArg >= (int)CI->getNumArgOperands())
1699     return false;
1700   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1701   if (!LI)
1702     return false;
1703   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1704   if (!GV || !GV->isDeclaration())
1705     return false;
1706   return GV->getName() == "stderr";
1709 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1710   // Check for a fixed format string.
1711   StringRef FormatStr;
1712   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1713     return nullptr;
1715   // Empty format string -> noop.
1716   if (FormatStr.empty()) // Tolerate printf's declared void.
1717     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1719   // Do not do any of the following transformations if the printf return value
1720   // is used, in general the printf return value is not compatible with either
1721   // putchar() or puts().
1722   if (!CI->use_empty())
1723     return nullptr;
1725   // printf("x") -> putchar('x'), even for '%'.
1726   if (FormatStr.size() == 1) {
1727     Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1728     if (CI->use_empty() || !Res)
1729       return Res;
1730     return B.CreateIntCast(Res, CI->getType(), true);
1731   }
1733   // printf("foo\n") --> puts("foo")
1734   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1735       FormatStr.find('%') == StringRef::npos) { // No format characters.
1736     // Create a string literal with no \n on it.  We expect the constant merge
1737     // pass to be run after this pass, to merge duplicate strings.
1738     FormatStr = FormatStr.drop_back();
1739     Value *GV = B.CreateGlobalString(FormatStr, "str");
1740     Value *NewCI = EmitPutS(GV, B, DL, TLI);
1741     return (CI->use_empty() || !NewCI)
1742                ? NewCI
1743                : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1744   }
1746   // Optimize specific format strings.
1747   // printf("%c", chr) --> putchar(chr)
1748   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1749       CI->getArgOperand(1)->getType()->isIntegerTy()) {
1750     Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
1752     if (CI->use_empty() || !Res)
1753       return Res;
1754     return B.CreateIntCast(Res, CI->getType(), true);
1755   }
1757   // printf("%s\n", str) --> puts(str)
1758   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1759       CI->getArgOperand(1)->getType()->isPointerTy()) {
1760     return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1761   }
1762   return nullptr;
1765 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1767   Function *Callee = CI->getCalledFunction();
1768   // Require one fixed pointer argument and an integer/void result.
1769   FunctionType *FT = Callee->getFunctionType();
1770   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1771       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1772     return nullptr;
1774   if (Value *V = optimizePrintFString(CI, B)) {
1775     return V;
1776   }
1778   // printf(format, ...) -> iprintf(format, ...) if no floating point
1779   // arguments.
1780   if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1781     Module *M = B.GetInsertBlock()->getParent()->getParent();
1782     Constant *IPrintFFn =
1783         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1784     CallInst *New = cast<CallInst>(CI->clone());
1785     New->setCalledFunction(IPrintFFn);
1786     B.Insert(New);
1787     return New;
1788   }
1789   return nullptr;
1792 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1793   // Check for a fixed format string.
1794   StringRef FormatStr;
1795   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1796     return nullptr;
1798   // If we just have a format string (nothing else crazy) transform it.
1799   if (CI->getNumArgOperands() == 2) {
1800     // Make sure there's no % in the constant array.  We could try to handle
1801     // %% -> % in the future if we cared.
1802     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1803       if (FormatStr[i] == '%')
1804         return nullptr; // we found a format specifier, bail out.
1806     // These optimizations require DataLayout.
1807     if (!DL)
1808       return nullptr;
1810     // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1811     B.CreateMemCpy(
1812         CI->getArgOperand(0), CI->getArgOperand(1),
1813         ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1814                          FormatStr.size() + 1),
1815         1); // Copy the null byte.
1816     return ConstantInt::get(CI->getType(), FormatStr.size());
1817   }
1819   // The remaining optimizations require the format string to be "%s" or "%c"
1820   // and have an extra operand.
1821   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1822       CI->getNumArgOperands() < 3)
1823     return nullptr;
1825   // Decode the second character of the format string.
1826   if (FormatStr[1] == 'c') {
1827     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1828     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1829       return nullptr;
1830     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1831     Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1832     B.CreateStore(V, Ptr);
1833     Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1834     B.CreateStore(B.getInt8(0), Ptr);
1836     return ConstantInt::get(CI->getType(), 1);
1837   }
1839   if (FormatStr[1] == 's') {
1840     // These optimizations require DataLayout.
1841     if (!DL)
1842       return nullptr;
1844     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1845     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1846       return nullptr;
1848     Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1849     if (!Len)
1850       return nullptr;
1851     Value *IncLen =
1852         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1853     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1855     // The sprintf result is the unincremented number of bytes in the string.
1856     return B.CreateIntCast(Len, CI->getType(), false);
1857   }
1858   return nullptr;
1861 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1862   Function *Callee = CI->getCalledFunction();
1863   // Require two fixed pointer arguments and an integer result.
1864   FunctionType *FT = Callee->getFunctionType();
1865   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1866       !FT->getParamType(1)->isPointerTy() ||
1867       !FT->getReturnType()->isIntegerTy())
1868     return nullptr;
1870   if (Value *V = optimizeSPrintFString(CI, B)) {
1871     return V;
1872   }
1874   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1875   // point arguments.
1876   if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1877     Module *M = B.GetInsertBlock()->getParent()->getParent();
1878     Constant *SIPrintFFn =
1879         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1880     CallInst *New = cast<CallInst>(CI->clone());
1881     New->setCalledFunction(SIPrintFFn);
1882     B.Insert(New);
1883     return New;
1884   }
1885   return nullptr;
1888 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1889   optimizeErrorReporting(CI, B, 0);
1891   // All the optimizations depend on the format string.
1892   StringRef FormatStr;
1893   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1894     return nullptr;
1896   // Do not do any of the following transformations if the fprintf return
1897   // value is used, in general the fprintf return value is not compatible
1898   // with fwrite(), fputc() or fputs().
1899   if (!CI->use_empty())
1900     return nullptr;
1902   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1903   if (CI->getNumArgOperands() == 2) {
1904     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1905       if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1906         return nullptr;        // We found a format specifier.
1908     // These optimizations require DataLayout.
1909     if (!DL)
1910       return nullptr;
1912     return EmitFWrite(
1913         CI->getArgOperand(1),
1914         ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1915         CI->getArgOperand(0), B, DL, TLI);
1916   }
1918   // The remaining optimizations require the format string to be "%s" or "%c"
1919   // and have an extra operand.
1920   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1921       CI->getNumArgOperands() < 3)
1922     return nullptr;
1924   // Decode the second character of the format string.
1925   if (FormatStr[1] == 'c') {
1926     // fprintf(F, "%c", chr) --> fputc(chr, F)
1927     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1928       return nullptr;
1929     return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1930   }
1932   if (FormatStr[1] == 's') {
1933     // fprintf(F, "%s", str) --> fputs(str, F)
1934     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1935       return nullptr;
1936     return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1937   }
1938   return nullptr;
1941 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1942   Function *Callee = CI->getCalledFunction();
1943   // Require two fixed paramters as pointers and integer result.
1944   FunctionType *FT = Callee->getFunctionType();
1945   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1946       !FT->getParamType(1)->isPointerTy() ||
1947       !FT->getReturnType()->isIntegerTy())
1948     return nullptr;
1950   if (Value *V = optimizeFPrintFString(CI, B)) {
1951     return V;
1952   }
1954   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1955   // floating point arguments.
1956   if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1957     Module *M = B.GetInsertBlock()->getParent()->getParent();
1958     Constant *FIPrintFFn =
1959         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1960     CallInst *New = cast<CallInst>(CI->clone());
1961     New->setCalledFunction(FIPrintFFn);
1962     B.Insert(New);
1963     return New;
1964   }
1965   return nullptr;
1968 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1969   optimizeErrorReporting(CI, B, 3);
1971   Function *Callee = CI->getCalledFunction();
1972   // Require a pointer, an integer, an integer, a pointer, returning integer.
1973   FunctionType *FT = Callee->getFunctionType();
1974   if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1975       !FT->getParamType(1)->isIntegerTy() ||
1976       !FT->getParamType(2)->isIntegerTy() ||
1977       !FT->getParamType(3)->isPointerTy() ||
1978       !FT->getReturnType()->isIntegerTy())
1979     return nullptr;
1981   // Get the element size and count.
1982   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1983   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1984   if (!SizeC || !CountC)
1985     return nullptr;
1986   uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1988   // If this is writing zero records, remove the call (it's a noop).
1989   if (Bytes == 0)
1990     return ConstantInt::get(CI->getType(), 0);
1992   // If this is writing one byte, turn it into fputc.
1993   // This optimisation is only valid, if the return value is unused.
1994   if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1995     Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1996     Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1997     return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1998   }
2000   return nullptr;
2003 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2004   optimizeErrorReporting(CI, B, 1);
2006   Function *Callee = CI->getCalledFunction();
2008   // These optimizations require DataLayout.
2009   if (!DL)
2010     return nullptr;
2012   // Require two pointers.  Also, we can't optimize if return value is used.
2013   FunctionType *FT = Callee->getFunctionType();
2014   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2015       !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2016     return nullptr;
2018   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2019   uint64_t Len = GetStringLength(CI->getArgOperand(0));
2020   if (!Len)
2021     return nullptr;
2023   // Known to have no uses (see above).
2024   return EmitFWrite(
2025       CI->getArgOperand(0),
2026       ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
2027       CI->getArgOperand(1), B, DL, TLI);
2030 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2031   Function *Callee = CI->getCalledFunction();
2032   // Require one fixed pointer argument and an integer/void result.
2033   FunctionType *FT = Callee->getFunctionType();
2034   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2035       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2036     return nullptr;
2038   // Check for a constant string.
2039   StringRef Str;
2040   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2041     return nullptr;
2043   if (Str.empty() && CI->use_empty()) {
2044     // puts("") -> putchar('\n')
2045     Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
2046     if (CI->use_empty() || !Res)
2047       return Res;
2048     return B.CreateIntCast(Res, CI->getType(), true);
2049   }
2051   return nullptr;
2054 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2055   LibFunc::Func Func;
2056   SmallString<20> FloatFuncName = FuncName;
2057   FloatFuncName += 'f';
2058   if (TLI->getLibFunc(FloatFuncName, Func))
2059     return TLI->has(Func);
2060   return false;
2063 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2064                                                       IRBuilder<> &Builder) {
2065   LibFunc::Func Func;
2066   Function *Callee = CI->getCalledFunction();
2067   StringRef FuncName = Callee->getName();
2069   // Check for string/memory library functions.
2070   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2071     // Make sure we never change the calling convention.
2072     assert((ignoreCallingConv(Func) ||
2073             CI->getCallingConv() == llvm::CallingConv::C) &&
2074       "Optimizing string/memory libcall would change the calling convention");
2075     switch (Func) {
2076     case LibFunc::strcat:
2077       return optimizeStrCat(CI, Builder);
2078     case LibFunc::strncat:
2079       return optimizeStrNCat(CI, Builder);
2080     case LibFunc::strchr:
2081       return optimizeStrChr(CI, Builder);
2082     case LibFunc::strrchr:
2083       return optimizeStrRChr(CI, Builder);
2084     case LibFunc::strcmp:
2085       return optimizeStrCmp(CI, Builder);
2086     case LibFunc::strncmp:
2087       return optimizeStrNCmp(CI, Builder);
2088     case LibFunc::strcpy:
2089       return optimizeStrCpy(CI, Builder);
2090     case LibFunc::stpcpy:
2091       return optimizeStpCpy(CI, Builder);
2092     case LibFunc::strncpy:
2093       return optimizeStrNCpy(CI, Builder);
2094     case LibFunc::strlen:
2095       return optimizeStrLen(CI, Builder);
2096     case LibFunc::strpbrk:
2097       return optimizeStrPBrk(CI, Builder);
2098     case LibFunc::strtol:
2099     case LibFunc::strtod:
2100     case LibFunc::strtof:
2101     case LibFunc::strtoul:
2102     case LibFunc::strtoll:
2103     case LibFunc::strtold:
2104     case LibFunc::strtoull:
2105       return optimizeStrTo(CI, Builder);
2106     case LibFunc::strspn:
2107       return optimizeStrSpn(CI, Builder);
2108     case LibFunc::strcspn:
2109       return optimizeStrCSpn(CI, Builder);
2110     case LibFunc::strstr:
2111       return optimizeStrStr(CI, Builder);
2112     case LibFunc::memcmp:
2113       return optimizeMemCmp(CI, Builder);
2114     case LibFunc::memcpy:
2115       return optimizeMemCpy(CI, Builder);
2116     case LibFunc::memmove:
2117       return optimizeMemMove(CI, Builder);
2118     case LibFunc::memset:
2119       return optimizeMemSet(CI, Builder);
2120     default:
2121       break;
2122     }
2123   }
2124   return nullptr;
2127 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2128   if (CI->isNoBuiltin())
2129     return nullptr;
2131   LibFunc::Func Func;
2132   Function *Callee = CI->getCalledFunction();
2133   StringRef FuncName = Callee->getName();
2134   IRBuilder<> Builder(CI);
2135   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2137   // Command-line parameter overrides function attribute.
2138   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2139     UnsafeFPShrink = EnableUnsafeFPShrink;
2140   else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2141     // FIXME: This is the same problem as described in optimizeSqrt().
2142     // If calls gain access to IR-level FMF, then use that instead of a
2143     // function attribute.
2145     // Check for unsafe-fp-math = true.
2146     Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2147     if (Attr.getValueAsString() == "true")
2148       UnsafeFPShrink = true;
2149   }
2151   // First, check for intrinsics.
2152   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2153     if (!isCallingConvC)
2154       return nullptr;
2155     switch (II->getIntrinsicID()) {
2156     case Intrinsic::pow:
2157       return optimizePow(CI, Builder);
2158     case Intrinsic::exp2:
2159       return optimizeExp2(CI, Builder);
2160     case Intrinsic::fabs:
2161       return optimizeFabs(CI, Builder);
2162     case Intrinsic::sqrt:
2163       return optimizeSqrt(CI, Builder);
2164     default:
2165       return nullptr;
2166     }
2167   }
2169   // Then check for known library functions.
2170   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2171     // We never change the calling convention.
2172     if (!ignoreCallingConv(Func) && !isCallingConvC)
2173       return nullptr;
2174     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2175       return V;
2176     switch (Func) {
2177     case LibFunc::cosf:
2178     case LibFunc::cos:
2179     case LibFunc::cosl:
2180       return optimizeCos(CI, Builder);
2181     case LibFunc::sinpif:
2182     case LibFunc::sinpi:
2183     case LibFunc::cospif:
2184     case LibFunc::cospi:
2185       return optimizeSinCosPi(CI, Builder);
2186     case LibFunc::powf:
2187     case LibFunc::pow:
2188     case LibFunc::powl:
2189       return optimizePow(CI, Builder);
2190     case LibFunc::exp2l:
2191     case LibFunc::exp2:
2192     case LibFunc::exp2f:
2193       return optimizeExp2(CI, Builder);
2194     case LibFunc::fabsf:
2195     case LibFunc::fabs:
2196     case LibFunc::fabsl:
2197       return optimizeFabs(CI, Builder);
2198     case LibFunc::sqrtf:
2199     case LibFunc::sqrt:
2200     case LibFunc::sqrtl:
2201       return optimizeSqrt(CI, Builder);
2202     case LibFunc::ffs:
2203     case LibFunc::ffsl:
2204     case LibFunc::ffsll:
2205       return optimizeFFS(CI, Builder);
2206     case LibFunc::abs:
2207     case LibFunc::labs:
2208     case LibFunc::llabs:
2209       return optimizeAbs(CI, Builder);
2210     case LibFunc::isdigit:
2211       return optimizeIsDigit(CI, Builder);
2212     case LibFunc::isascii:
2213       return optimizeIsAscii(CI, Builder);
2214     case LibFunc::toascii:
2215       return optimizeToAscii(CI, Builder);
2216     case LibFunc::printf:
2217       return optimizePrintF(CI, Builder);
2218     case LibFunc::sprintf:
2219       return optimizeSPrintF(CI, Builder);
2220     case LibFunc::fprintf:
2221       return optimizeFPrintF(CI, Builder);
2222     case LibFunc::fwrite:
2223       return optimizeFWrite(CI, Builder);
2224     case LibFunc::fputs:
2225       return optimizeFPuts(CI, Builder);
2226     case LibFunc::puts:
2227       return optimizePuts(CI, Builder);
2228     case LibFunc::perror:
2229       return optimizeErrorReporting(CI, Builder);
2230     case LibFunc::vfprintf:
2231     case LibFunc::fiprintf:
2232       return optimizeErrorReporting(CI, Builder, 0);
2233     case LibFunc::fputc:
2234       return optimizeErrorReporting(CI, Builder, 1);
2235     case LibFunc::ceil:
2236     case LibFunc::floor:
2237     case LibFunc::rint:
2238     case LibFunc::round:
2239     case LibFunc::nearbyint:
2240     case LibFunc::trunc:
2241       if (hasFloatVersion(FuncName))
2242         return optimizeUnaryDoubleFP(CI, Builder, false);
2243       return nullptr;
2244     case LibFunc::acos:
2245     case LibFunc::acosh:
2246     case LibFunc::asin:
2247     case LibFunc::asinh:
2248     case LibFunc::atan:
2249     case LibFunc::atanh:
2250     case LibFunc::cbrt:
2251     case LibFunc::cosh:
2252     case LibFunc::exp:
2253     case LibFunc::exp10:
2254     case LibFunc::expm1:
2255     case LibFunc::log:
2256     case LibFunc::log10:
2257     case LibFunc::log1p:
2258     case LibFunc::log2:
2259     case LibFunc::logb:
2260     case LibFunc::sin:
2261     case LibFunc::sinh:
2262     case LibFunc::tan:
2263     case LibFunc::tanh:
2264       if (UnsafeFPShrink && hasFloatVersion(FuncName))
2265         return optimizeUnaryDoubleFP(CI, Builder, true);
2266       return nullptr;
2267     case LibFunc::copysign:
2268     case LibFunc::fmin:
2269     case LibFunc::fmax:
2270       if (hasFloatVersion(FuncName))
2271         return optimizeBinaryDoubleFP(CI, Builder);
2272       return nullptr;
2273     case LibFunc::memcpy_chk:
2274       return optimizeMemCpyChk(CI, Builder);
2275     case LibFunc::memmove_chk:
2276       return optimizeMemMoveChk(CI, Builder);
2277     case LibFunc::memset_chk:
2278       return optimizeMemSetChk(CI, Builder);
2279     case LibFunc::strcpy_chk:
2280       return optimizeStrCpyChk(CI, Builder);
2281     case LibFunc::stpcpy_chk:
2282       return optimizeStpCpyChk(CI, Builder);
2283     case LibFunc::stpncpy_chk:
2284     case LibFunc::strncpy_chk:
2285       return optimizeStrNCpyChk(CI, Builder);
2286     default:
2287       return nullptr;
2288     }
2289   }
2291   return nullptr;
2294 LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
2295                                      const TargetLibraryInfo *TLI) :
2296                                      DL(DL),
2297                                      TLI(TLI),
2298                                      UnsafeFPShrink(false) {
2301 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2302   I->replaceAllUsesWith(With);
2303   I->eraseFromParent();
2306 // TODO:
2307 //   Additional cases that we need to add to this file:
2308 //
2309 // cbrt:
2310 //   * cbrt(expN(X))  -> expN(x/3)
2311 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2312 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2313 //
2314 // exp, expf, expl:
2315 //   * exp(log(x))  -> x
2316 //
2317 // log, logf, logl:
2318 //   * log(exp(x))   -> x
2319 //   * log(x**y)     -> y*log(x)
2320 //   * log(exp(y))   -> y*log(e)
2321 //   * log(exp2(y))  -> y*log(2)
2322 //   * log(exp10(y)) -> y*log(10)
2323 //   * log(sqrt(x))  -> 0.5*log(x)
2324 //   * log(pow(x,y)) -> y*log(x)
2325 //
2326 // lround, lroundf, lroundl:
2327 //   * lround(cnst) -> cnst'
2328 //
2329 // pow, powf, powl:
2330 //   * pow(exp(x),y)  -> exp(x*y)
2331 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2332 //   * pow(pow(x,y),z)-> pow(x,y*z)
2333 //
2334 // round, roundf, roundl:
2335 //   * round(cnst) -> cnst'
2336 //
2337 // signbit:
2338 //   * signbit(cnst) -> cnst'
2339 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2340 //
2341 // sqrt, sqrtf, sqrtl:
2342 //   * sqrt(expN(x))  -> expN(x*0.5)
2343 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2344 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2345 //
2346 // tan, tanf, tanl:
2347 //   * tan(atan(x)) -> x
2348 //
2349 // trunc, truncf, truncl:
2350 //   * trunc(cnst) -> cnst'
2351 //
2352 //