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