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