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