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