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