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