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