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