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