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