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