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 
1010   // memchr(x, y, 0) -> null
1011   if (LenC) {
1012     if (LenC->isZero())
1013       return Constant::getNullValue(CI->getType());
1014 
1015     if (LenC->isOne()) {
1016       // Fold memchr(x, y, 1) --> *x == y ? x : null for any x and y,
1017       // constant or otherwise.
1018       Value *Val = B.CreateLoad(B.getInt8Ty(), SrcStr, "memchr.char0");
1019       // Slice off the character's high end bits.
1020       CharVal = B.CreateTrunc(CharVal, B.getInt8Ty());
1021       Value *Cmp = B.CreateICmpEQ(Val, CharVal, "memchr.char0cmp");
1022       Value *NullPtr = Constant::getNullValue(CI->getType());
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 Constant::getNullValue(CI->getType());
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 *NullPtr = Constant::getNullValue(CI->getType());
1044     Value *SrcPlus =
1045         B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(Pos), "memchr.ptr");
1046     return B.CreateSelect(Cmp, NullPtr, SrcPlus);
1047   }
1048 
1049   if (!LenC)
1050     // From now on we need a constant length and constant array.
1051     return nullptr;
1052 
1053   // Truncate the string to LenC without slicing when targeting LP64
1054   // on an ILP32 host.
1055   Str = substr(Str, LenC->getZExtValue());
1056 
1057   // If the char is variable but the input str and length are not we can turn
1058   // this memchr call into a simple bit field test. Of course this only works
1059   // when the return value is only checked against null.
1060   //
1061   // It would be really nice to reuse switch lowering here but we can't change
1062   // the CFG at this point.
1063   //
1064   // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
1065   // != 0
1066   //   after bounds check.
1067   if (Str.empty() || !isOnlyUsedInZeroEqualityComparison(CI))
1068     return nullptr;
1069 
1070   unsigned char Max =
1071       *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
1072                         reinterpret_cast<const unsigned char *>(Str.end()));
1073 
1074   // Make sure the bit field we're about to create fits in a register on the
1075   // target.
1076   // FIXME: On a 64 bit architecture this prevents us from using the
1077   // interesting range of alpha ascii chars. We could do better by emitting
1078   // two bitfields or shifting the range by 64 if no lower chars are used.
1079   if (!DL.fitsInLegalInteger(Max + 1))
1080     return nullptr;
1081 
1082   // For the bit field use a power-of-2 type with at least 8 bits to avoid
1083   // creating unnecessary illegal types.
1084   unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
1085 
1086   // Now build the bit field.
1087   APInt Bitfield(Width, 0);
1088   for (char C : Str)
1089     Bitfield.setBit((unsigned char)C);
1090   Value *BitfieldC = B.getInt(Bitfield);
1091 
1092   // Adjust width of "C" to the bitfield width, then mask off the high bits.
1093   Value *C = B.CreateZExtOrTrunc(CharVal, BitfieldC->getType());
1094   C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
1095 
1096   // First check that the bit field access is within bounds.
1097   Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
1098                                "memchr.bounds");
1099 
1100   // Create code that checks if the given bit is set in the field.
1101   Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
1102   Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
1103 
1104   // Finally merge both checks and cast to pointer type. The inttoptr
1105   // implicitly zexts the i1 to intptr type.
1106   return B.CreateIntToPtr(B.CreateLogicalAnd(Bounds, Bits, "memchr"),
1107                           CI->getType());
1108 }
1109 
1110 static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
1111                                          uint64_t Len, IRBuilderBase &B,
1112                                          const DataLayout &DL) {
1113   if (Len == 0) // memcmp(s1,s2,0) -> 0
1114     return Constant::getNullValue(CI->getType());
1115 
1116   // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1117   if (Len == 1) {
1118     Value *LHSV =
1119         B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
1120                      CI->getType(), "lhsv");
1121     Value *RHSV =
1122         B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
1123                      CI->getType(), "rhsv");
1124     return B.CreateSub(LHSV, RHSV, "chardiff");
1125   }
1126 
1127   // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
1128   // TODO: The case where both inputs are constants does not need to be limited
1129   // to legal integers or equality comparison. See block below this.
1130   if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
1131     IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1132     unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
1133 
1134     // First, see if we can fold either argument to a constant.
1135     Value *LHSV = nullptr;
1136     if (auto *LHSC = dyn_cast<Constant>(LHS)) {
1137       LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
1138       LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1139     }
1140     Value *RHSV = nullptr;
1141     if (auto *RHSC = dyn_cast<Constant>(RHS)) {
1142       RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
1143       RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1144     }
1145 
1146     // Don't generate unaligned loads. If either source is constant data,
1147     // alignment doesn't matter for that source because there is no load.
1148     if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1149         (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1150       if (!LHSV) {
1151         Type *LHSPtrTy =
1152             IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
1153         LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
1154       }
1155       if (!RHSV) {
1156         Type *RHSPtrTy =
1157             IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
1158         RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
1159       }
1160       return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
1161     }
1162   }
1163 
1164   // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
1165   // TODO: This is limited to i8 arrays.
1166   StringRef LHSStr, RHSStr;
1167   if (getConstantStringInfo(LHS, LHSStr) &&
1168       getConstantStringInfo(RHS, RHSStr)) {
1169     // Make sure we're not reading out-of-bounds memory.
1170     if (Len > LHSStr.size() || Len > RHSStr.size())
1171       return nullptr;
1172     // Fold the memcmp and normalize the result.  This way we get consistent
1173     // results across multiple platforms.
1174     uint64_t Ret = 0;
1175     int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1176     if (Cmp < 0)
1177       Ret = -1;
1178     else if (Cmp > 0)
1179       Ret = 1;
1180     return ConstantInt::get(CI->getType(), Ret);
1181   }
1182 
1183   return nullptr;
1184 }
1185 
1186 // Most simplifications for memcmp also apply to bcmp.
1187 Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1188                                                    IRBuilderBase &B) {
1189   Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1190   Value *Size = CI->getArgOperand(2);
1191 
1192   if (LHS == RHS) // memcmp(s,s,x) -> 0
1193     return Constant::getNullValue(CI->getType());
1194 
1195   annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1196   // Handle constant lengths.
1197   ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1198   if (!LenC)
1199     return nullptr;
1200 
1201   // memcmp(d,s,0) -> 0
1202   if (LenC->getZExtValue() == 0)
1203     return Constant::getNullValue(CI->getType());
1204 
1205   if (Value *Res =
1206           optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL))
1207     return Res;
1208   return nullptr;
1209 }
1210 
1211 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilderBase &B) {
1212   Module *M = CI->getModule();
1213   if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1214     return V;
1215 
1216   // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
1217   // bcmp can be more efficient than memcmp because it only has to know that
1218   // there is a difference, not how different one is to the other.
1219   if (isLibFuncEmittable(M, TLI, LibFunc_bcmp) &&
1220       isOnlyUsedInZeroEqualityComparison(CI)) {
1221     Value *LHS = CI->getArgOperand(0);
1222     Value *RHS = CI->getArgOperand(1);
1223     Value *Size = CI->getArgOperand(2);
1224     return copyFlags(*CI, emitBCmp(LHS, RHS, Size, B, DL, TLI));
1225   }
1226 
1227   return nullptr;
1228 }
1229 
1230 Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilderBase &B) {
1231   return optimizeMemCmpBCmpCommon(CI, B);
1232 }
1233 
1234 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilderBase &B) {
1235   Value *Size = CI->getArgOperand(2);
1236   annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1237   if (isa<IntrinsicInst>(CI))
1238     return nullptr;
1239 
1240   // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
1241   CallInst *NewCI = B.CreateMemCpy(CI->getArgOperand(0), Align(1),
1242                                    CI->getArgOperand(1), Align(1), Size);
1243   NewCI->setAttributes(CI->getAttributes());
1244   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1245   copyFlags(*CI, NewCI);
1246   return CI->getArgOperand(0);
1247 }
1248 
1249 Value *LibCallSimplifier::optimizeMemCCpy(CallInst *CI, IRBuilderBase &B) {
1250   Value *Dst = CI->getArgOperand(0);
1251   Value *Src = CI->getArgOperand(1);
1252   ConstantInt *StopChar = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1253   ConstantInt *N = dyn_cast<ConstantInt>(CI->getArgOperand(3));
1254   StringRef SrcStr;
1255   if (CI->use_empty() && Dst == Src)
1256     return Dst;
1257   // memccpy(d, s, c, 0) -> nullptr
1258   if (N) {
1259     if (N->isNullValue())
1260       return Constant::getNullValue(CI->getType());
1261     if (!getConstantStringInfo(Src, SrcStr, /*Offset=*/0,
1262                                /*TrimAtNul=*/false) ||
1263         !StopChar)
1264       return nullptr;
1265   } else {
1266     return nullptr;
1267   }
1268 
1269   // Wrap arg 'c' of type int to char
1270   size_t Pos = SrcStr.find(StopChar->getSExtValue() & 0xFF);
1271   if (Pos == StringRef::npos) {
1272     if (N->getZExtValue() <= SrcStr.size()) {
1273       copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1),
1274                                     CI->getArgOperand(3)));
1275       return Constant::getNullValue(CI->getType());
1276     }
1277     return nullptr;
1278   }
1279 
1280   Value *NewN =
1281       ConstantInt::get(N->getType(), std::min(uint64_t(Pos + 1), N->getZExtValue()));
1282   // memccpy -> llvm.memcpy
1283   copyFlags(*CI, B.CreateMemCpy(Dst, Align(1), Src, Align(1), NewN));
1284   return Pos + 1 <= N->getZExtValue()
1285              ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, NewN)
1286              : Constant::getNullValue(CI->getType());
1287 }
1288 
1289 Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilderBase &B) {
1290   Value *Dst = CI->getArgOperand(0);
1291   Value *N = CI->getArgOperand(2);
1292   // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1293   CallInst *NewCI =
1294       B.CreateMemCpy(Dst, Align(1), CI->getArgOperand(1), Align(1), N);
1295   // Propagate attributes, but memcpy has no return value, so make sure that
1296   // any return attributes are compliant.
1297   // TODO: Attach return value attributes to the 1st operand to preserve them?
1298   NewCI->setAttributes(CI->getAttributes());
1299   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1300   copyFlags(*CI, NewCI);
1301   return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1302 }
1303 
1304 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilderBase &B) {
1305   Value *Size = CI->getArgOperand(2);
1306   annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1307   if (isa<IntrinsicInst>(CI))
1308     return nullptr;
1309 
1310   // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
1311   CallInst *NewCI = B.CreateMemMove(CI->getArgOperand(0), Align(1),
1312                                     CI->getArgOperand(1), Align(1), Size);
1313   NewCI->setAttributes(CI->getAttributes());
1314   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1315   copyFlags(*CI, NewCI);
1316   return CI->getArgOperand(0);
1317 }
1318 
1319 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilderBase &B) {
1320   Value *Size = CI->getArgOperand(2);
1321   annotateNonNullAndDereferenceable(CI, 0, Size, DL);
1322   if (isa<IntrinsicInst>(CI))
1323     return nullptr;
1324 
1325   // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
1326   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1327   CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, Align(1));
1328   NewCI->setAttributes(CI->getAttributes());
1329   NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
1330   copyFlags(*CI, NewCI);
1331   return CI->getArgOperand(0);
1332 }
1333 
1334 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilderBase &B) {
1335   if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1336     return copyFlags(*CI, emitMalloc(CI->getArgOperand(1), B, DL, TLI));
1337 
1338   return nullptr;
1339 }
1340 
1341 //===----------------------------------------------------------------------===//
1342 // Math Library Optimizations
1343 //===----------------------------------------------------------------------===//
1344 
1345 // Replace a libcall \p CI with a call to intrinsic \p IID
1346 static Value *replaceUnaryCall(CallInst *CI, IRBuilderBase &B,
1347                                Intrinsic::ID IID) {
1348   // Propagate fast-math flags from the existing call to the new call.
1349   IRBuilderBase::FastMathFlagGuard Guard(B);
1350   B.setFastMathFlags(CI->getFastMathFlags());
1351 
1352   Module *M = CI->getModule();
1353   Value *V = CI->getArgOperand(0);
1354   Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1355   CallInst *NewCall = B.CreateCall(F, V);
1356   NewCall->takeName(CI);
1357   return copyFlags(*CI, NewCall);
1358 }
1359 
1360 /// Return a variant of Val with float type.
1361 /// Currently this works in two cases: If Val is an FPExtension of a float
1362 /// value to something bigger, simply return the operand.
1363 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1364 /// loss of precision do so.
1365 static Value *valueHasFloatPrecision(Value *Val) {
1366   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1367     Value *Op = Cast->getOperand(0);
1368     if (Op->getType()->isFloatTy())
1369       return Op;
1370   }
1371   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1372     APFloat F = Const->getValueAPF();
1373     bool losesInfo;
1374     (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
1375                     &losesInfo);
1376     if (!losesInfo)
1377       return ConstantFP::get(Const->getContext(), F);
1378   }
1379   return nullptr;
1380 }
1381 
1382 /// Shrink double -> float functions.
1383 static Value *optimizeDoubleFP(CallInst *CI, IRBuilderBase &B,
1384                                bool isBinary, const TargetLibraryInfo *TLI,
1385                                bool isPrecise = false) {
1386   Function *CalleeFn = CI->getCalledFunction();
1387   if (!CI->getType()->isDoubleTy() || !CalleeFn)
1388     return nullptr;
1389 
1390   // If not all the uses of the function are converted to float, then bail out.
1391   // This matters if the precision of the result is more important than the
1392   // precision of the arguments.
1393   if (isPrecise)
1394     for (User *U : CI->users()) {
1395       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1396       if (!Cast || !Cast->getType()->isFloatTy())
1397         return nullptr;
1398     }
1399 
1400   // If this is something like 'g((double) float)', convert to 'gf(float)'.
1401   Value *V[2];
1402   V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1403   V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1404   if (!V[0] || (isBinary && !V[1]))
1405     return nullptr;
1406 
1407   // If call isn't an intrinsic, check that it isn't within a function with the
1408   // same name as the float version of this call, otherwise the result is an
1409   // infinite loop.  For example, from MinGW-w64:
1410   //
1411   // float expf(float val) { return (float) exp((double) val); }
1412   StringRef CalleeName = CalleeFn->getName();
1413   bool IsIntrinsic = CalleeFn->isIntrinsic();
1414   if (!IsIntrinsic) {
1415     StringRef CallerName = CI->getFunction()->getName();
1416     if (!CallerName.empty() && CallerName.back() == 'f' &&
1417         CallerName.size() == (CalleeName.size() + 1) &&
1418         CallerName.startswith(CalleeName))
1419       return nullptr;
1420   }
1421 
1422   // Propagate the math semantics from the current function to the new function.
1423   IRBuilderBase::FastMathFlagGuard Guard(B);
1424   B.setFastMathFlags(CI->getFastMathFlags());
1425 
1426   // g((double) float) -> (double) gf(float)
1427   Value *R;
1428   if (IsIntrinsic) {
1429     Module *M = CI->getModule();
1430     Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1431     Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1432     R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
1433   } else {
1434     AttributeList CalleeAttrs = CalleeFn->getAttributes();
1435     R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], TLI, CalleeName, B,
1436                                          CalleeAttrs)
1437                  : emitUnaryFloatFnCall(V[0], TLI, CalleeName, B, CalleeAttrs);
1438   }
1439   return B.CreateFPExt(R, B.getDoubleTy());
1440 }
1441 
1442 /// Shrink double -> float for unary functions.
1443 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilderBase &B,
1444                                     const TargetLibraryInfo *TLI,
1445                                     bool isPrecise = false) {
1446   return optimizeDoubleFP(CI, B, false, TLI, isPrecise);
1447 }
1448 
1449 /// Shrink double -> float for binary functions.
1450 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilderBase &B,
1451                                      const TargetLibraryInfo *TLI,
1452                                      bool isPrecise = false) {
1453   return optimizeDoubleFP(CI, B, true, TLI, isPrecise);
1454 }
1455 
1456 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1457 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilderBase &B) {
1458   if (!CI->isFast())
1459     return nullptr;
1460 
1461   // Propagate fast-math flags from the existing call to new instructions.
1462   IRBuilderBase::FastMathFlagGuard Guard(B);
1463   B.setFastMathFlags(CI->getFastMathFlags());
1464 
1465   Value *Real, *Imag;
1466   if (CI->arg_size() == 1) {
1467     Value *Op = CI->getArgOperand(0);
1468     assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1469     Real = B.CreateExtractValue(Op, 0, "real");
1470     Imag = B.CreateExtractValue(Op, 1, "imag");
1471   } else {
1472     assert(CI->arg_size() == 2 && "Unexpected signature for cabs!");
1473     Real = CI->getArgOperand(0);
1474     Imag = CI->getArgOperand(1);
1475   }
1476 
1477   Value *RealReal = B.CreateFMul(Real, Real);
1478   Value *ImagImag = B.CreateFMul(Imag, Imag);
1479 
1480   Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1481                                               CI->getType());
1482   return copyFlags(
1483       *CI, B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs"));
1484 }
1485 
1486 static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1487                                       IRBuilderBase &B) {
1488   if (!isa<FPMathOperator>(Call))
1489     return nullptr;
1490 
1491   IRBuilderBase::FastMathFlagGuard Guard(B);
1492   B.setFastMathFlags(Call->getFastMathFlags());
1493 
1494   // TODO: Can this be shared to also handle LLVM intrinsics?
1495   Value *X;
1496   switch (Func) {
1497   case LibFunc_sin:
1498   case LibFunc_sinf:
1499   case LibFunc_sinl:
1500   case LibFunc_tan:
1501   case LibFunc_tanf:
1502   case LibFunc_tanl:
1503     // sin(-X) --> -sin(X)
1504     // tan(-X) --> -tan(X)
1505     if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
1506       return B.CreateFNeg(
1507           copyFlags(*Call, B.CreateCall(Call->getCalledFunction(), X)));
1508     break;
1509   case LibFunc_cos:
1510   case LibFunc_cosf:
1511   case LibFunc_cosl:
1512     // cos(-X) --> cos(X)
1513     if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1514       return copyFlags(*Call,
1515                        B.CreateCall(Call->getCalledFunction(), X, "cos"));
1516     break;
1517   default:
1518     break;
1519   }
1520   return nullptr;
1521 }
1522 
1523 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilderBase &B) {
1524   // Multiplications calculated using Addition Chains.
1525   // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1526 
1527   assert(Exp != 0 && "Incorrect exponent 0 not handled");
1528 
1529   if (InnerChain[Exp])
1530     return InnerChain[Exp];
1531 
1532   static const unsigned AddChain[33][2] = {
1533       {0, 0}, // Unused.
1534       {0, 0}, // Unused (base case = pow1).
1535       {1, 1}, // Unused (pre-computed).
1536       {1, 2},  {2, 2},   {2, 3},  {3, 3},   {2, 5},  {4, 4},
1537       {1, 8},  {5, 5},   {1, 10}, {6, 6},   {4, 9},  {7, 7},
1538       {3, 12}, {8, 8},   {8, 9},  {2, 16},  {1, 18}, {10, 10},
1539       {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1540       {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1541   };
1542 
1543   InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1544                                  getPow(InnerChain, AddChain[Exp][1], B));
1545   return InnerChain[Exp];
1546 }
1547 
1548 // Return a properly extended integer (DstWidth bits wide) if the operation is
1549 // an itofp.
1550 static Value *getIntToFPVal(Value *I2F, IRBuilderBase &B, unsigned DstWidth) {
1551   if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
1552     Value *Op = cast<Instruction>(I2F)->getOperand(0);
1553     // Make sure that the exponent fits inside an "int" of size DstWidth,
1554     // thus avoiding any range issues that FP has not.
1555     unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits();
1556     if (BitWidth < DstWidth ||
1557         (BitWidth == DstWidth && isa<SIToFPInst>(I2F)))
1558       return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getIntNTy(DstWidth))
1559                                   : B.CreateZExt(Op, B.getIntNTy(DstWidth));
1560   }
1561 
1562   return nullptr;
1563 }
1564 
1565 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
1566 /// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
1567 /// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
1568 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilderBase &B) {
1569   Module *M = Pow->getModule();
1570   Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1571   AttributeList Attrs; // Attributes are only meaningful on the original call
1572   Module *Mod = Pow->getModule();
1573   Type *Ty = Pow->getType();
1574   bool Ignored;
1575 
1576   // Evaluate special cases related to a nested function as the base.
1577 
1578   // pow(exp(x), y) -> exp(x * y)
1579   // pow(exp2(x), y) -> exp2(x * y)
1580   // If exp{,2}() is used only once, it is better to fold two transcendental
1581   // math functions into one.  If used again, exp{,2}() would still have to be
1582   // called with the original argument, then keep both original transcendental
1583   // functions.  However, this transformation is only safe with fully relaxed
1584   // math semantics, since, besides rounding differences, it changes overflow
1585   // and underflow behavior quite dramatically.  For example:
1586   //   pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1587   // Whereas:
1588   //   exp(1000 * 0.001) = exp(1)
1589   // TODO: Loosen the requirement for fully relaxed math semantics.
1590   // TODO: Handle exp10() when more targets have it available.
1591   CallInst *BaseFn = dyn_cast<CallInst>(Base);
1592   if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
1593     LibFunc LibFn;
1594 
1595     Function *CalleeFn = BaseFn->getCalledFunction();
1596     if (CalleeFn &&
1597         TLI->getLibFunc(CalleeFn->getName(), LibFn) &&
1598         isLibFuncEmittable(M, TLI, LibFn)) {
1599       StringRef ExpName;
1600       Intrinsic::ID ID;
1601       Value *ExpFn;
1602       LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
1603 
1604       switch (LibFn) {
1605       default:
1606         return nullptr;
1607       case LibFunc_expf:  case LibFunc_exp:  case LibFunc_expl:
1608         ExpName = TLI->getName(LibFunc_exp);
1609         ID = Intrinsic::exp;
1610         LibFnFloat = LibFunc_expf;
1611         LibFnDouble = LibFunc_exp;
1612         LibFnLongDouble = LibFunc_expl;
1613         break;
1614       case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
1615         ExpName = TLI->getName(LibFunc_exp2);
1616         ID = Intrinsic::exp2;
1617         LibFnFloat = LibFunc_exp2f;
1618         LibFnDouble = LibFunc_exp2;
1619         LibFnLongDouble = LibFunc_exp2l;
1620         break;
1621       }
1622 
1623       // Create new exp{,2}() with the product as its argument.
1624       Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1625       ExpFn = BaseFn->doesNotAccessMemory()
1626               ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1627                              FMul, ExpName)
1628               : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1629                                      LibFnLongDouble, B,
1630                                      BaseFn->getAttributes());
1631 
1632       // Since the new exp{,2}() is different from the original one, dead code
1633       // elimination cannot be trusted to remove it, since it may have side
1634       // effects (e.g., errno).  When the only consumer for the original
1635       // exp{,2}() is pow(), then it has to be explicitly erased.
1636       substituteInParent(BaseFn, ExpFn);
1637       return ExpFn;
1638     }
1639   }
1640 
1641   // Evaluate special cases related to a constant base.
1642 
1643   const APFloat *BaseF;
1644   if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1645     return nullptr;
1646 
1647   // pow(2.0, itofp(x)) -> ldexp(1.0, x)
1648   if (match(Base, m_SpecificFP(2.0)) &&
1649       (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
1650       hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1651     if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
1652       return copyFlags(*Pow,
1653                        emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI,
1654                                              TLI, LibFunc_ldexp, LibFunc_ldexpf,
1655                                              LibFunc_ldexpl, B, Attrs));
1656   }
1657 
1658   // pow(2.0 ** n, x) -> exp2(n * x)
1659   if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1660     APFloat BaseR = APFloat(1.0);
1661     BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1662     BaseR = BaseR / *BaseF;
1663     bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
1664     const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1665     APSInt NI(64, false);
1666     if ((IsInteger || IsReciprocal) &&
1667         NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
1668             APFloat::opOK &&
1669         NI > 1 && NI.isPowerOf2()) {
1670       double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1671       Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1672       if (Pow->doesNotAccessMemory())
1673         return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration(
1674                                                 Mod, Intrinsic::exp2, Ty),
1675                                             FMul, "exp2"));
1676       else
1677         return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
1678                                                     LibFunc_exp2f,
1679                                                     LibFunc_exp2l, B, Attrs));
1680     }
1681   }
1682 
1683   // pow(10.0, x) -> exp10(x)
1684   // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1685   if (match(Base, m_SpecificFP(10.0)) &&
1686       hasFloatFn(M, TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1687     return copyFlags(*Pow, emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10,
1688                                                 LibFunc_exp10f, LibFunc_exp10l,
1689                                                 B, Attrs));
1690 
1691   // pow(x, y) -> exp2(log2(x) * y)
1692   if (Pow->hasApproxFunc() && Pow->hasNoNaNs() && BaseF->isFiniteNonZero() &&
1693       !BaseF->isNegative()) {
1694     // pow(1, inf) is defined to be 1 but exp2(log2(1) * inf) evaluates to NaN.
1695     // Luckily optimizePow has already handled the x == 1 case.
1696     assert(!match(Base, m_FPOne()) &&
1697            "pow(1.0, y) should have been simplified earlier!");
1698 
1699     Value *Log = nullptr;
1700     if (Ty->isFloatTy())
1701       Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
1702     else if (Ty->isDoubleTy())
1703       Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
1704 
1705     if (Log) {
1706       Value *FMul = B.CreateFMul(Log, Expo, "mul");
1707       if (Pow->doesNotAccessMemory())
1708         return copyFlags(*Pow, B.CreateCall(Intrinsic::getDeclaration(
1709                                                 Mod, Intrinsic::exp2, Ty),
1710                                             FMul, "exp2"));
1711       else if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f,
1712                           LibFunc_exp2l))
1713         return copyFlags(*Pow, emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2,
1714                                                     LibFunc_exp2f,
1715                                                     LibFunc_exp2l, B, Attrs));
1716     }
1717   }
1718 
1719   return nullptr;
1720 }
1721 
1722 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1723                           Module *M, IRBuilderBase &B,
1724                           const TargetLibraryInfo *TLI) {
1725   // If errno is never set, then use the intrinsic for sqrt().
1726   if (NoErrno) {
1727     Function *SqrtFn =
1728         Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1729     return B.CreateCall(SqrtFn, V, "sqrt");
1730   }
1731 
1732   // Otherwise, use the libcall for sqrt().
1733   if (hasFloatFn(M, TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1734                  LibFunc_sqrtl))
1735     // TODO: We also should check that the target can in fact lower the sqrt()
1736     // libcall. We currently have no way to ask this question, so we ask if
1737     // the target has a sqrt() libcall, which is not exactly the same.
1738     return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1739                                 LibFunc_sqrtl, B, Attrs);
1740 
1741   return nullptr;
1742 }
1743 
1744 /// Use square root in place of pow(x, +/-0.5).
1745 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilderBase &B) {
1746   Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1747   AttributeList Attrs; // Attributes are only meaningful on the original call
1748   Module *Mod = Pow->getModule();
1749   Type *Ty = Pow->getType();
1750 
1751   const APFloat *ExpoF;
1752   if (!match(Expo, m_APFloat(ExpoF)) ||
1753       (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1754     return nullptr;
1755 
1756   // Converting pow(X, -0.5) to 1/sqrt(X) may introduce an extra rounding step,
1757   // so that requires fast-math-flags (afn or reassoc).
1758   if (ExpoF->isNegative() && (!Pow->hasApproxFunc() && !Pow->hasAllowReassoc()))
1759     return nullptr;
1760 
1761   // If we have a pow() library call (accesses memory) and we can't guarantee
1762   // that the base is not an infinity, give up:
1763   // pow(-Inf, 0.5) is optionally required to have a result of +Inf (not setting
1764   // errno), but sqrt(-Inf) is required by various standards to set errno.
1765   if (!Pow->doesNotAccessMemory() && !Pow->hasNoInfs() &&
1766       !isKnownNeverInfinity(Base, TLI))
1767     return nullptr;
1768 
1769   Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1770   if (!Sqrt)
1771     return nullptr;
1772 
1773   // Handle signed zero base by expanding to fabs(sqrt(x)).
1774   if (!Pow->hasNoSignedZeros()) {
1775     Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1776     Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1777   }
1778 
1779   Sqrt = copyFlags(*Pow, Sqrt);
1780 
1781   // Handle non finite base by expanding to
1782   // (x == -infinity ? +infinity : sqrt(x)).
1783   if (!Pow->hasNoInfs()) {
1784     Value *PosInf = ConstantFP::getInfinity(Ty),
1785           *NegInf = ConstantFP::getInfinity(Ty, true);
1786     Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1787     Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1788   }
1789 
1790   // If the exponent is negative, then get the reciprocal.
1791   if (ExpoF->isNegative())
1792     Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
1793 
1794   return Sqrt;
1795 }
1796 
1797 static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
1798                                            IRBuilderBase &B) {
1799   Value *Args[] = {Base, Expo};
1800   Type *Types[] = {Base->getType(), Expo->getType()};
1801   Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Types);
1802   return B.CreateCall(F, Args);
1803 }
1804 
1805 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilderBase &B) {
1806   Value *Base = Pow->getArgOperand(0);
1807   Value *Expo = Pow->getArgOperand(1);
1808   Function *Callee = Pow->getCalledFunction();
1809   StringRef Name = Callee->getName();
1810   Type *Ty = Pow->getType();
1811   Module *M = Pow->getModule();
1812   bool AllowApprox = Pow->hasApproxFunc();
1813   bool Ignored;
1814 
1815   // Propagate the math semantics from the call to any created instructions.
1816   IRBuilderBase::FastMathFlagGuard Guard(B);
1817   B.setFastMathFlags(Pow->getFastMathFlags());
1818   // Evaluate special cases related to the base.
1819 
1820   // pow(1.0, x) -> 1.0
1821   if (match(Base, m_FPOne()))
1822     return Base;
1823 
1824   if (Value *Exp = replacePowWithExp(Pow, B))
1825     return Exp;
1826 
1827   // Evaluate special cases related to the exponent.
1828 
1829   // pow(x, -1.0) -> 1.0 / x
1830   if (match(Expo, m_SpecificFP(-1.0)))
1831     return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1832 
1833   // pow(x, +/-0.0) -> 1.0
1834   if (match(Expo, m_AnyZeroFP()))
1835     return ConstantFP::get(Ty, 1.0);
1836 
1837   // pow(x, 1.0) -> x
1838   if (match(Expo, m_FPOne()))
1839     return Base;
1840 
1841   // pow(x, 2.0) -> x * x
1842   if (match(Expo, m_SpecificFP(2.0)))
1843     return B.CreateFMul(Base, Base, "square");
1844 
1845   if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1846     return Sqrt;
1847 
1848   // pow(x, n) -> x * x * x * ...
1849   const APFloat *ExpoF;
1850   if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
1851       !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
1852     // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
1853     // If the exponent is an integer+0.5 we generate a call to sqrt and an
1854     // additional fmul.
1855     // TODO: This whole transformation should be backend specific (e.g. some
1856     //       backends might prefer libcalls or the limit for the exponent might
1857     //       be different) and it should also consider optimizing for size.
1858     APFloat LimF(ExpoF->getSemantics(), 33),
1859             ExpoA(abs(*ExpoF));
1860     if (ExpoA < LimF) {
1861       // This transformation applies to integer or integer+0.5 exponents only.
1862       // For integer+0.5, we create a sqrt(Base) call.
1863       Value *Sqrt = nullptr;
1864       if (!ExpoA.isInteger()) {
1865         APFloat Expo2 = ExpoA;
1866         // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1867         // is no floating point exception and the result is an integer, then
1868         // ExpoA == integer + 0.5
1869         if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1870           return nullptr;
1871 
1872         if (!Expo2.isInteger())
1873           return nullptr;
1874 
1875         Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1876                            Pow->doesNotAccessMemory(), M, B, TLI);
1877         if (!Sqrt)
1878           return nullptr;
1879       }
1880 
1881       // We will memoize intermediate products of the Addition Chain.
1882       Value *InnerChain[33] = {nullptr};
1883       InnerChain[1] = Base;
1884       InnerChain[2] = B.CreateFMul(Base, Base, "square");
1885 
1886       // We cannot readily convert a non-double type (like float) to a double.
1887       // So we first convert it to something which could be converted to double.
1888       ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1889       Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
1890 
1891       // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1892       if (Sqrt)
1893         FMul = B.CreateFMul(FMul, Sqrt);
1894 
1895       // If the exponent is negative, then get the reciprocal.
1896       if (ExpoF->isNegative())
1897         FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
1898 
1899       return FMul;
1900     }
1901 
1902     APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
1903     // powf(x, n) -> powi(x, n) if n is a constant signed integer value
1904     if (ExpoF->isInteger() &&
1905         ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
1906             APFloat::opOK) {
1907       return copyFlags(
1908           *Pow,
1909           createPowWithIntegerExponent(
1910               Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
1911               M, B));
1912     }
1913   }
1914 
1915   // powf(x, itofp(y)) -> powi(x, y)
1916   if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
1917     if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
1918       return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
1919   }
1920 
1921   // Shrink pow() to powf() if the arguments are single precision,
1922   // unless the result is expected to be double precision.
1923   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
1924       hasFloatVersion(M, Name)) {
1925     if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true))
1926       return Shrunk;
1927   }
1928 
1929   return nullptr;
1930 }
1931 
1932 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
1933   Module *M = CI->getModule();
1934   Function *Callee = CI->getCalledFunction();
1935   AttributeList Attrs; // Attributes are only meaningful on the original call
1936   StringRef Name = Callee->getName();
1937   Value *Ret = nullptr;
1938   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
1939       hasFloatVersion(M, Name))
1940     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
1941 
1942   Type *Ty = CI->getType();
1943   Value *Op = CI->getArgOperand(0);
1944 
1945   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= IntSize
1946   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < IntSize
1947   if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
1948       hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1949     if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize()))
1950       return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
1951                                    LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1952                                    B, Attrs);
1953   }
1954 
1955   return Ret;
1956 }
1957 
1958 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) {
1959   Module *M = CI->getModule();
1960 
1961   // If we can shrink the call to a float function rather than a double
1962   // function, do that first.
1963   Function *Callee = CI->getCalledFunction();
1964   StringRef Name = Callee->getName();
1965   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name))
1966     if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI))
1967       return Ret;
1968 
1969   // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
1970   // the intrinsics for improved optimization (for example, vectorization).
1971   // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
1972   // From the C standard draft WG14/N1256:
1973   // "Ideally, fmax would be sensitive to the sign of zero, for example
1974   // fmax(-0.0, +0.0) would return +0; however, implementation in software
1975   // might be impractical."
1976   IRBuilderBase::FastMathFlagGuard Guard(B);
1977   FastMathFlags FMF = CI->getFastMathFlags();
1978   FMF.setNoSignedZeros();
1979   B.setFastMathFlags(FMF);
1980 
1981   Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
1982                                                            : Intrinsic::maxnum;
1983   Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
1984   return copyFlags(
1985       *CI, B.CreateCall(F, {CI->getArgOperand(0), CI->getArgOperand(1)}));
1986 }
1987 
1988 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
1989   Function *LogFn = Log->getCalledFunction();
1990   AttributeList Attrs; // Attributes are only meaningful on the original call
1991   StringRef LogNm = LogFn->getName();
1992   Intrinsic::ID LogID = LogFn->getIntrinsicID();
1993   Module *Mod = Log->getModule();
1994   Type *Ty = Log->getType();
1995   Value *Ret = nullptr;
1996 
1997   if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm))
1998     Ret = optimizeUnaryDoubleFP(Log, B, TLI, true);
1999 
2000   // The earlier call must also be 'fast' in order to do these transforms.
2001   CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
2002   if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
2003     return Ret;
2004 
2005   LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
2006 
2007   // This is only applicable to log(), log2(), log10().
2008   if (TLI->getLibFunc(LogNm, LogLb))
2009     switch (LogLb) {
2010     case LibFunc_logf:
2011       LogID = Intrinsic::log;
2012       ExpLb = LibFunc_expf;
2013       Exp2Lb = LibFunc_exp2f;
2014       Exp10Lb = LibFunc_exp10f;
2015       PowLb = LibFunc_powf;
2016       break;
2017     case LibFunc_log:
2018       LogID = Intrinsic::log;
2019       ExpLb = LibFunc_exp;
2020       Exp2Lb = LibFunc_exp2;
2021       Exp10Lb = LibFunc_exp10;
2022       PowLb = LibFunc_pow;
2023       break;
2024     case LibFunc_logl:
2025       LogID = Intrinsic::log;
2026       ExpLb = LibFunc_expl;
2027       Exp2Lb = LibFunc_exp2l;
2028       Exp10Lb = LibFunc_exp10l;
2029       PowLb = LibFunc_powl;
2030       break;
2031     case LibFunc_log2f:
2032       LogID = Intrinsic::log2;
2033       ExpLb = LibFunc_expf;
2034       Exp2Lb = LibFunc_exp2f;
2035       Exp10Lb = LibFunc_exp10f;
2036       PowLb = LibFunc_powf;
2037       break;
2038     case LibFunc_log2:
2039       LogID = Intrinsic::log2;
2040       ExpLb = LibFunc_exp;
2041       Exp2Lb = LibFunc_exp2;
2042       Exp10Lb = LibFunc_exp10;
2043       PowLb = LibFunc_pow;
2044       break;
2045     case LibFunc_log2l:
2046       LogID = Intrinsic::log2;
2047       ExpLb = LibFunc_expl;
2048       Exp2Lb = LibFunc_exp2l;
2049       Exp10Lb = LibFunc_exp10l;
2050       PowLb = LibFunc_powl;
2051       break;
2052     case LibFunc_log10f:
2053       LogID = Intrinsic::log10;
2054       ExpLb = LibFunc_expf;
2055       Exp2Lb = LibFunc_exp2f;
2056       Exp10Lb = LibFunc_exp10f;
2057       PowLb = LibFunc_powf;
2058       break;
2059     case LibFunc_log10:
2060       LogID = Intrinsic::log10;
2061       ExpLb = LibFunc_exp;
2062       Exp2Lb = LibFunc_exp2;
2063       Exp10Lb = LibFunc_exp10;
2064       PowLb = LibFunc_pow;
2065       break;
2066     case LibFunc_log10l:
2067       LogID = Intrinsic::log10;
2068       ExpLb = LibFunc_expl;
2069       Exp2Lb = LibFunc_exp2l;
2070       Exp10Lb = LibFunc_exp10l;
2071       PowLb = LibFunc_powl;
2072       break;
2073     default:
2074       return Ret;
2075     }
2076   else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
2077            LogID == Intrinsic::log10) {
2078     if (Ty->getScalarType()->isFloatTy()) {
2079       ExpLb = LibFunc_expf;
2080       Exp2Lb = LibFunc_exp2f;
2081       Exp10Lb = LibFunc_exp10f;
2082       PowLb = LibFunc_powf;
2083     } else if (Ty->getScalarType()->isDoubleTy()) {
2084       ExpLb = LibFunc_exp;
2085       Exp2Lb = LibFunc_exp2;
2086       Exp10Lb = LibFunc_exp10;
2087       PowLb = LibFunc_pow;
2088     } else
2089       return Ret;
2090   } else
2091     return Ret;
2092 
2093   IRBuilderBase::FastMathFlagGuard Guard(B);
2094   B.setFastMathFlags(FastMathFlags::getFast());
2095 
2096   Intrinsic::ID ArgID = Arg->getIntrinsicID();
2097   LibFunc ArgLb = NotLibFunc;
2098   TLI->getLibFunc(*Arg, ArgLb);
2099 
2100   // log(pow(x,y)) -> y*log(x)
2101   if (ArgLb == PowLb || ArgID == Intrinsic::pow) {
2102     Value *LogX =
2103         Log->doesNotAccessMemory()
2104             ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
2105                            Arg->getOperand(0), "log")
2106             : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, Attrs);
2107     Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul");
2108     // Since pow() may have side effects, e.g. errno,
2109     // dead code elimination may not be trusted to remove it.
2110     substituteInParent(Arg, MulY);
2111     return MulY;
2112   }
2113 
2114   // log(exp{,2,10}(y)) -> y*log({e,2,10})
2115   // TODO: There is no exp10() intrinsic yet.
2116   if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
2117            ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
2118     Constant *Eul;
2119     if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
2120       // FIXME: Add more precise value of e for long double.
2121       Eul = ConstantFP::get(Log->getType(), numbers::e);
2122     else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
2123       Eul = ConstantFP::get(Log->getType(), 2.0);
2124     else
2125       Eul = ConstantFP::get(Log->getType(), 10.0);
2126     Value *LogE = Log->doesNotAccessMemory()
2127                       ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
2128                                      Eul, "log")
2129                       : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, Attrs);
2130     Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
2131     // Since exp() may have side effects, e.g. errno,
2132     // dead code elimination may not be trusted to remove it.
2133     substituteInParent(Arg, MulY);
2134     return MulY;
2135   }
2136 
2137   return Ret;
2138 }
2139 
2140 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
2141   Module *M = CI->getModule();
2142   Function *Callee = CI->getCalledFunction();
2143   Value *Ret = nullptr;
2144   // TODO: Once we have a way (other than checking for the existince of the
2145   // libcall) to tell whether our target can lower @llvm.sqrt, relax the
2146   // condition below.
2147   if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) &&
2148       (Callee->getName() == "sqrt" ||
2149        Callee->getIntrinsicID() == Intrinsic::sqrt))
2150     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2151 
2152   if (!CI->isFast())
2153     return Ret;
2154 
2155   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
2156   if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
2157     return Ret;
2158 
2159   // We're looking for a repeated factor in a multiplication tree,
2160   // so we can do this fold: sqrt(x * x) -> fabs(x);
2161   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
2162   Value *Op0 = I->getOperand(0);
2163   Value *Op1 = I->getOperand(1);
2164   Value *RepeatOp = nullptr;
2165   Value *OtherOp = nullptr;
2166   if (Op0 == Op1) {
2167     // Simple match: the operands of the multiply are identical.
2168     RepeatOp = Op0;
2169   } else {
2170     // Look for a more complicated pattern: one of the operands is itself
2171     // a multiply, so search for a common factor in that multiply.
2172     // Note: We don't bother looking any deeper than this first level or for
2173     // variations of this pattern because instcombine's visitFMUL and/or the
2174     // reassociation pass should give us this form.
2175     Value *OtherMul0, *OtherMul1;
2176     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
2177       // Pattern: sqrt((x * y) * z)
2178       if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
2179         // Matched: sqrt((x * x) * z)
2180         RepeatOp = OtherMul0;
2181         OtherOp = Op1;
2182       }
2183     }
2184   }
2185   if (!RepeatOp)
2186     return Ret;
2187 
2188   // Fast math flags for any created instructions should match the sqrt
2189   // and multiply.
2190   IRBuilderBase::FastMathFlagGuard Guard(B);
2191   B.setFastMathFlags(I->getFastMathFlags());
2192 
2193   // If we found a repeated factor, hoist it out of the square root and
2194   // replace it with the fabs of that factor.
2195   Type *ArgType = I->getType();
2196   Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
2197   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
2198   if (OtherOp) {
2199     // If we found a non-repeated factor, we still need to get its square
2200     // root. We then multiply that by the value that was simplified out
2201     // of the square root calculation.
2202     Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
2203     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
2204     return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall));
2205   }
2206   return copyFlags(*CI, FabsCall);
2207 }
2208 
2209 // TODO: Generalize to handle any trig function and its inverse.
2210 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilderBase &B) {
2211   Module *M = CI->getModule();
2212   Function *Callee = CI->getCalledFunction();
2213   Value *Ret = nullptr;
2214   StringRef Name = Callee->getName();
2215   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(M, Name))
2216     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2217 
2218   Value *Op1 = CI->getArgOperand(0);
2219   auto *OpC = dyn_cast<CallInst>(Op1);
2220   if (!OpC)
2221     return Ret;
2222 
2223   // Both calls must be 'fast' in order to remove them.
2224   if (!CI->isFast() || !OpC->isFast())
2225     return Ret;
2226 
2227   // tan(atan(x)) -> x
2228   // tanf(atanf(x)) -> x
2229   // tanl(atanl(x)) -> x
2230   LibFunc Func;
2231   Function *F = OpC->getCalledFunction();
2232   if (F && TLI->getLibFunc(F->getName(), Func) &&
2233       isLibFuncEmittable(M, TLI, Func) &&
2234       ((Func == LibFunc_atan && Callee->getName() == "tan") ||
2235        (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
2236        (Func == LibFunc_atanl && Callee->getName() == "tanl")))
2237     Ret = OpC->getArgOperand(0);
2238   return Ret;
2239 }
2240 
2241 static bool isTrigLibCall(CallInst *CI) {
2242   // We can only hope to do anything useful if we can ignore things like errno
2243   // and floating-point exceptions.
2244   // We already checked the prototype.
2245   return CI->hasFnAttr(Attribute::NoUnwind) &&
2246          CI->hasFnAttr(Attribute::ReadNone);
2247 }
2248 
2249 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
2250                              bool UseFloat, Value *&Sin, Value *&Cos,
2251                              Value *&SinCos, const TargetLibraryInfo *TLI) {
2252   Module *M = OrigCallee->getParent();
2253   Type *ArgTy = Arg->getType();
2254   Type *ResTy;
2255   StringRef Name;
2256 
2257   Triple T(OrigCallee->getParent()->getTargetTriple());
2258   if (UseFloat) {
2259     Name = "__sincospif_stret";
2260 
2261     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
2262     // x86_64 can't use {float, float} since that would be returned in both
2263     // xmm0 and xmm1, which isn't what a real struct would do.
2264     ResTy = T.getArch() == Triple::x86_64
2265                 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
2266                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
2267   } else {
2268     Name = "__sincospi_stret";
2269     ResTy = StructType::get(ArgTy, ArgTy);
2270   }
2271 
2272   if (!isLibFuncEmittable(M, TLI, Name))
2273     return false;
2274   LibFunc TheLibFunc;
2275   TLI->getLibFunc(Name, TheLibFunc);
2276   FunctionCallee Callee = getOrInsertLibFunc(
2277       M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy);
2278 
2279   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
2280     // If the argument is an instruction, it must dominate all uses so put our
2281     // sincos call there.
2282     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
2283   } else {
2284     // Otherwise (e.g. for a constant) the beginning of the function is as
2285     // good a place as any.
2286     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
2287     B.SetInsertPoint(&EntryBB, EntryBB.begin());
2288   }
2289 
2290   SinCos = B.CreateCall(Callee, Arg, "sincospi");
2291 
2292   if (SinCos->getType()->isStructTy()) {
2293     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
2294     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
2295   } else {
2296     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
2297                                  "sinpi");
2298     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
2299                                  "cospi");
2300   }
2301 
2302   return true;
2303 }
2304 
2305 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilderBase &B) {
2306   // Make sure the prototype is as expected, otherwise the rest of the
2307   // function is probably invalid and likely to abort.
2308   if (!isTrigLibCall(CI))
2309     return nullptr;
2310 
2311   Value *Arg = CI->getArgOperand(0);
2312   SmallVector<CallInst *, 1> SinCalls;
2313   SmallVector<CallInst *, 1> CosCalls;
2314   SmallVector<CallInst *, 1> SinCosCalls;
2315 
2316   bool IsFloat = Arg->getType()->isFloatTy();
2317 
2318   // Look for all compatible sinpi, cospi and sincospi calls with the same
2319   // argument. If there are enough (in some sense) we can make the
2320   // substitution.
2321   Function *F = CI->getFunction();
2322   for (User *U : Arg->users())
2323     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
2324 
2325   // It's only worthwhile if both sinpi and cospi are actually used.
2326   if (SinCalls.empty() || CosCalls.empty())
2327     return nullptr;
2328 
2329   Value *Sin, *Cos, *SinCos;
2330   if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
2331                         SinCos, TLI))
2332     return nullptr;
2333 
2334   auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
2335                                  Value *Res) {
2336     for (CallInst *C : Calls)
2337       replaceAllUsesWith(C, Res);
2338   };
2339 
2340   replaceTrigInsts(SinCalls, Sin);
2341   replaceTrigInsts(CosCalls, Cos);
2342   replaceTrigInsts(SinCosCalls, SinCos);
2343 
2344   return nullptr;
2345 }
2346 
2347 void LibCallSimplifier::classifyArgUse(
2348     Value *Val, Function *F, bool IsFloat,
2349     SmallVectorImpl<CallInst *> &SinCalls,
2350     SmallVectorImpl<CallInst *> &CosCalls,
2351     SmallVectorImpl<CallInst *> &SinCosCalls) {
2352   CallInst *CI = dyn_cast<CallInst>(Val);
2353   Module *M = CI->getModule();
2354 
2355   if (!CI || CI->use_empty())
2356     return;
2357 
2358   // Don't consider calls in other functions.
2359   if (CI->getFunction() != F)
2360     return;
2361 
2362   Function *Callee = CI->getCalledFunction();
2363   LibFunc Func;
2364   if (!Callee || !TLI->getLibFunc(*Callee, Func) ||
2365       !isLibFuncEmittable(M, TLI, Func) ||
2366       !isTrigLibCall(CI))
2367     return;
2368 
2369   if (IsFloat) {
2370     if (Func == LibFunc_sinpif)
2371       SinCalls.push_back(CI);
2372     else if (Func == LibFunc_cospif)
2373       CosCalls.push_back(CI);
2374     else if (Func == LibFunc_sincospif_stret)
2375       SinCosCalls.push_back(CI);
2376   } else {
2377     if (Func == LibFunc_sinpi)
2378       SinCalls.push_back(CI);
2379     else if (Func == LibFunc_cospi)
2380       CosCalls.push_back(CI);
2381     else if (Func == LibFunc_sincospi_stret)
2382       SinCosCalls.push_back(CI);
2383   }
2384 }
2385 
2386 //===----------------------------------------------------------------------===//
2387 // Integer Library Call Optimizations
2388 //===----------------------------------------------------------------------===//
2389 
2390 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
2391   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
2392   Value *Op = CI->getArgOperand(0);
2393   Type *ArgType = Op->getType();
2394   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2395                                           Intrinsic::cttz, ArgType);
2396   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
2397   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
2398   V = B.CreateIntCast(V, B.getInt32Ty(), false);
2399 
2400   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
2401   return B.CreateSelect(Cond, V, B.getInt32(0));
2402 }
2403 
2404 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
2405   // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
2406   Value *Op = CI->getArgOperand(0);
2407   Type *ArgType = Op->getType();
2408   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2409                                           Intrinsic::ctlz, ArgType);
2410   Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
2411   V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
2412                   V);
2413   return B.CreateIntCast(V, CI->getType(), false);
2414 }
2415 
2416 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
2417   // abs(x) -> x <s 0 ? -x : x
2418   // The negation has 'nsw' because abs of INT_MIN is undefined.
2419   Value *X = CI->getArgOperand(0);
2420   Value *IsNeg = B.CreateIsNeg(X);
2421   Value *NegX = B.CreateNSWNeg(X, "neg");
2422   return B.CreateSelect(IsNeg, NegX, X);
2423 }
2424 
2425 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
2426   // isdigit(c) -> (c-'0') <u 10
2427   Value *Op = CI->getArgOperand(0);
2428   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
2429   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
2430   return B.CreateZExt(Op, CI->getType());
2431 }
2432 
2433 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
2434   // isascii(c) -> c <u 128
2435   Value *Op = CI->getArgOperand(0);
2436   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
2437   return B.CreateZExt(Op, CI->getType());
2438 }
2439 
2440 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
2441   // toascii(c) -> c & 0x7f
2442   return B.CreateAnd(CI->getArgOperand(0),
2443                      ConstantInt::get(CI->getType(), 0x7F));
2444 }
2445 
2446 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
2447   StringRef Str;
2448   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2449     return nullptr;
2450 
2451   return convertStrToNumber(CI, Str, 10);
2452 }
2453 
2454 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilderBase &B) {
2455   StringRef Str;
2456   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2457     return nullptr;
2458 
2459   if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
2460     return nullptr;
2461 
2462   if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
2463     return convertStrToNumber(CI, Str, CInt->getSExtValue());
2464   }
2465 
2466   return nullptr;
2467 }
2468 
2469 //===----------------------------------------------------------------------===//
2470 // Formatting and IO Library Call Optimizations
2471 //===----------------------------------------------------------------------===//
2472 
2473 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
2474 
2475 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
2476                                                  int StreamArg) {
2477   Function *Callee = CI->getCalledFunction();
2478   // Error reporting calls should be cold, mark them as such.
2479   // This applies even to non-builtin calls: it is only a hint and applies to
2480   // functions that the frontend might not understand as builtins.
2481 
2482   // This heuristic was suggested in:
2483   // Improving Static Branch Prediction in a Compiler
2484   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2485   // Proceedings of PACT'98, Oct. 1998, IEEE
2486   if (!CI->hasFnAttr(Attribute::Cold) &&
2487       isReportingError(Callee, CI, StreamArg)) {
2488     CI->addFnAttr(Attribute::Cold);
2489   }
2490 
2491   return nullptr;
2492 }
2493 
2494 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
2495   if (!Callee || !Callee->isDeclaration())
2496     return false;
2497 
2498   if (StreamArg < 0)
2499     return true;
2500 
2501   // These functions might be considered cold, but only if their stream
2502   // argument is stderr.
2503 
2504   if (StreamArg >= (int)CI->arg_size())
2505     return false;
2506   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2507   if (!LI)
2508     return false;
2509   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2510   if (!GV || !GV->isDeclaration())
2511     return false;
2512   return GV->getName() == "stderr";
2513 }
2514 
2515 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
2516   // Check for a fixed format string.
2517   StringRef FormatStr;
2518   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
2519     return nullptr;
2520 
2521   // Empty format string -> noop.
2522   if (FormatStr.empty()) // Tolerate printf's declared void.
2523     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
2524 
2525   // Do not do any of the following transformations if the printf return value
2526   // is used, in general the printf return value is not compatible with either
2527   // putchar() or puts().
2528   if (!CI->use_empty())
2529     return nullptr;
2530 
2531   // printf("x") -> putchar('x'), even for "%" and "%%".
2532   if (FormatStr.size() == 1 || FormatStr == "%%")
2533     return copyFlags(*CI, emitPutChar(B.getInt32(FormatStr[0]), B, TLI));
2534 
2535   // Try to remove call or emit putchar/puts.
2536   if (FormatStr == "%s" && CI->arg_size() > 1) {
2537     StringRef OperandStr;
2538     if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
2539       return nullptr;
2540     // printf("%s", "") --> NOP
2541     if (OperandStr.empty())
2542       return (Value *)CI;
2543     // printf("%s", "a") --> putchar('a')
2544     if (OperandStr.size() == 1)
2545       return copyFlags(*CI, emitPutChar(B.getInt32(OperandStr[0]), B, TLI));
2546     // printf("%s", str"\n") --> puts(str)
2547     if (OperandStr.back() == '\n') {
2548       OperandStr = OperandStr.drop_back();
2549       Value *GV = B.CreateGlobalString(OperandStr, "str");
2550       return copyFlags(*CI, emitPutS(GV, B, TLI));
2551     }
2552     return nullptr;
2553   }
2554 
2555   // printf("foo\n") --> puts("foo")
2556   if (FormatStr.back() == '\n' &&
2557       !FormatStr.contains('%')) { // No format characters.
2558     // Create a string literal with no \n on it.  We expect the constant merge
2559     // pass to be run after this pass, to merge duplicate strings.
2560     FormatStr = FormatStr.drop_back();
2561     Value *GV = B.CreateGlobalString(FormatStr, "str");
2562     return copyFlags(*CI, emitPutS(GV, B, TLI));
2563   }
2564 
2565   // Optimize specific format strings.
2566   // printf("%c", chr) --> putchar(chr)
2567   if (FormatStr == "%c" && CI->arg_size() > 1 &&
2568       CI->getArgOperand(1)->getType()->isIntegerTy())
2569     return copyFlags(*CI, emitPutChar(CI->getArgOperand(1), B, TLI));
2570 
2571   // printf("%s\n", str) --> puts(str)
2572   if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
2573       CI->getArgOperand(1)->getType()->isPointerTy())
2574     return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
2575   return nullptr;
2576 }
2577 
2578 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
2579 
2580   Module *M = CI->getModule();
2581   Function *Callee = CI->getCalledFunction();
2582   FunctionType *FT = Callee->getFunctionType();
2583   if (Value *V = optimizePrintFString(CI, B)) {
2584     return V;
2585   }
2586 
2587   // printf(format, ...) -> iprintf(format, ...) if no floating point
2588   // arguments.
2589   if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) &&
2590       !callHasFloatingPointArgument(CI)) {
2591     FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT,
2592                                                   Callee->getAttributes());
2593     CallInst *New = cast<CallInst>(CI->clone());
2594     New->setCalledFunction(IPrintFFn);
2595     B.Insert(New);
2596     return New;
2597   }
2598 
2599   // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2600   // arguments.
2601   if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) &&
2602       !callHasFP128Argument(CI)) {
2603     auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT,
2604                                             Callee->getAttributes());
2605     CallInst *New = cast<CallInst>(CI->clone());
2606     New->setCalledFunction(SmallPrintFFn);
2607     B.Insert(New);
2608     return New;
2609   }
2610 
2611   annotateNonNullNoUndefBasedOnAccess(CI, 0);
2612   return nullptr;
2613 }
2614 
2615 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
2616                                                 IRBuilderBase &B) {
2617   // Check for a fixed format string.
2618   StringRef FormatStr;
2619   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2620     return nullptr;
2621 
2622   // If we just have a format string (nothing else crazy) transform it.
2623   Value *Dest = CI->getArgOperand(0);
2624   if (CI->arg_size() == 2) {
2625     // Make sure there's no % in the constant array.  We could try to handle
2626     // %% -> % in the future if we cared.
2627     if (FormatStr.contains('%'))
2628       return nullptr; // we found a format specifier, bail out.
2629 
2630     // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2631     B.CreateMemCpy(
2632         Dest, Align(1), CI->getArgOperand(1), Align(1),
2633         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2634                          FormatStr.size() + 1)); // Copy the null byte.
2635     return ConstantInt::get(CI->getType(), FormatStr.size());
2636   }
2637 
2638   // The remaining optimizations require the format string to be "%s" or "%c"
2639   // and have an extra operand.
2640   if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
2641     return nullptr;
2642 
2643   // Decode the second character of the format string.
2644   if (FormatStr[1] == 'c') {
2645     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2646     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2647       return nullptr;
2648     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2649     Value *Ptr = castToCStr(Dest, B);
2650     B.CreateStore(V, Ptr);
2651     Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2652     B.CreateStore(B.getInt8(0), Ptr);
2653 
2654     return ConstantInt::get(CI->getType(), 1);
2655   }
2656 
2657   if (FormatStr[1] == 's') {
2658     // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2659     // strlen(str)+1)
2660     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2661       return nullptr;
2662 
2663     if (CI->use_empty())
2664       // sprintf(dest, "%s", str) -> strcpy(dest, str)
2665       return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
2666 
2667     uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
2668     if (SrcLen) {
2669       B.CreateMemCpy(
2670           Dest, Align(1), CI->getArgOperand(2), Align(1),
2671           ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen));
2672       // Returns total number of characters written without null-character.
2673       return ConstantInt::get(CI->getType(), SrcLen - 1);
2674     } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
2675       // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
2676       // Handle mismatched pointer types (goes away with typeless pointers?).
2677       V = B.CreatePointerCast(V, B.getInt8PtrTy());
2678       Dest = B.CreatePointerCast(Dest, B.getInt8PtrTy());
2679       Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest);
2680       return B.CreateIntCast(PtrDiff, CI->getType(), false);
2681     }
2682 
2683     bool OptForSize = CI->getFunction()->hasOptSize() ||
2684                       llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
2685                                                   PGSOQueryType::IRPass);
2686     if (OptForSize)
2687       return nullptr;
2688 
2689     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
2690     if (!Len)
2691       return nullptr;
2692     Value *IncLen =
2693         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2694     B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
2695 
2696     // The sprintf result is the unincremented number of bytes in the string.
2697     return B.CreateIntCast(Len, CI->getType(), false);
2698   }
2699   return nullptr;
2700 }
2701 
2702 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
2703   Module *M = CI->getModule();
2704   Function *Callee = CI->getCalledFunction();
2705   FunctionType *FT = Callee->getFunctionType();
2706   if (Value *V = optimizeSPrintFString(CI, B)) {
2707     return V;
2708   }
2709 
2710   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2711   // point arguments.
2712   if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) &&
2713       !callHasFloatingPointArgument(CI)) {
2714     FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf,
2715                                                    FT, Callee->getAttributes());
2716     CallInst *New = cast<CallInst>(CI->clone());
2717     New->setCalledFunction(SIPrintFFn);
2718     B.Insert(New);
2719     return New;
2720   }
2721 
2722   // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2723   // floating point arguments.
2724   if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) &&
2725       !callHasFP128Argument(CI)) {
2726     auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT,
2727                                              Callee->getAttributes());
2728     CallInst *New = cast<CallInst>(CI->clone());
2729     New->setCalledFunction(SmallSPrintFFn);
2730     B.Insert(New);
2731     return New;
2732   }
2733 
2734   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
2735   return nullptr;
2736 }
2737 
2738 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
2739                                                  IRBuilderBase &B) {
2740   // Check for size
2741   ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2742   if (!Size)
2743     return nullptr;
2744 
2745   uint64_t N = Size->getZExtValue();
2746   // Check for a fixed format string.
2747   StringRef FormatStr;
2748   if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2749     return nullptr;
2750 
2751   // If we just have a format string (nothing else crazy) transform it.
2752   if (CI->arg_size() == 3) {
2753     // Make sure there's no % in the constant array.  We could try to handle
2754     // %% -> % in the future if we cared.
2755     if (FormatStr.contains('%'))
2756       return nullptr; // we found a format specifier, bail out.
2757 
2758     if (N == 0)
2759       return ConstantInt::get(CI->getType(), FormatStr.size());
2760     else if (N < FormatStr.size() + 1)
2761       return nullptr;
2762 
2763     // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
2764     // strlen(fmt)+1)
2765     copyFlags(
2766         *CI,
2767         B.CreateMemCpy(
2768             CI->getArgOperand(0), Align(1), CI->getArgOperand(2), Align(1),
2769             ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2770                              FormatStr.size() + 1))); // Copy the null byte.
2771     return ConstantInt::get(CI->getType(), FormatStr.size());
2772   }
2773 
2774   // The remaining optimizations require the format string to be "%s" or "%c"
2775   // and have an extra operand.
2776   if (FormatStr.size() == 2 && FormatStr[0] == '%' && CI->arg_size() == 4) {
2777 
2778     // Decode the second character of the format string.
2779     if (FormatStr[1] == 'c') {
2780       if (N == 0)
2781         return ConstantInt::get(CI->getType(), 1);
2782       else if (N == 1)
2783         return nullptr;
2784 
2785       // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2786       if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2787         return nullptr;
2788       Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2789       Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2790       B.CreateStore(V, Ptr);
2791       Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2792       B.CreateStore(B.getInt8(0), Ptr);
2793 
2794       return ConstantInt::get(CI->getType(), 1);
2795     }
2796 
2797     if (FormatStr[1] == 's') {
2798       // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2799       StringRef Str;
2800       if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2801         return nullptr;
2802 
2803       if (N == 0)
2804         return ConstantInt::get(CI->getType(), Str.size());
2805       else if (N < Str.size() + 1)
2806         return nullptr;
2807 
2808       copyFlags(
2809           *CI, B.CreateMemCpy(CI->getArgOperand(0), Align(1),
2810                               CI->getArgOperand(3), Align(1),
2811                               ConstantInt::get(CI->getType(), Str.size() + 1)));
2812 
2813       // The snprintf result is the unincremented number of bytes in the string.
2814       return ConstantInt::get(CI->getType(), Str.size());
2815     }
2816   }
2817   return nullptr;
2818 }
2819 
2820 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
2821   if (Value *V = optimizeSnPrintFString(CI, B)) {
2822     return V;
2823   }
2824 
2825   if (isKnownNonZero(CI->getOperand(1), DL))
2826     annotateNonNullNoUndefBasedOnAccess(CI, 0);
2827   return nullptr;
2828 }
2829 
2830 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
2831                                                 IRBuilderBase &B) {
2832   optimizeErrorReporting(CI, B, 0);
2833 
2834   // All the optimizations depend on the format string.
2835   StringRef FormatStr;
2836   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2837     return nullptr;
2838 
2839   // Do not do any of the following transformations if the fprintf return
2840   // value is used, in general the fprintf return value is not compatible
2841   // with fwrite(), fputc() or fputs().
2842   if (!CI->use_empty())
2843     return nullptr;
2844 
2845   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2846   if (CI->arg_size() == 2) {
2847     // Could handle %% -> % if we cared.
2848     if (FormatStr.contains('%'))
2849       return nullptr; // We found a format specifier.
2850 
2851     return copyFlags(
2852         *CI, emitFWrite(CI->getArgOperand(1),
2853                         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2854                                          FormatStr.size()),
2855                         CI->getArgOperand(0), B, DL, TLI));
2856   }
2857 
2858   // The remaining optimizations require the format string to be "%s" or "%c"
2859   // and have an extra operand.
2860   if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
2861     return nullptr;
2862 
2863   // Decode the second character of the format string.
2864   if (FormatStr[1] == 'c') {
2865     // fprintf(F, "%c", chr) --> fputc(chr, F)
2866     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2867       return nullptr;
2868     return copyFlags(
2869         *CI, emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
2870   }
2871 
2872   if (FormatStr[1] == 's') {
2873     // fprintf(F, "%s", str) --> fputs(str, F)
2874     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2875       return nullptr;
2876     return copyFlags(
2877         *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
2878   }
2879   return nullptr;
2880 }
2881 
2882 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
2883   Module *M = CI->getModule();
2884   Function *Callee = CI->getCalledFunction();
2885   FunctionType *FT = Callee->getFunctionType();
2886   if (Value *V = optimizeFPrintFString(CI, B)) {
2887     return V;
2888   }
2889 
2890   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2891   // floating point arguments.
2892   if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) &&
2893       !callHasFloatingPointArgument(CI)) {
2894     FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf,
2895                                                    FT, Callee->getAttributes());
2896     CallInst *New = cast<CallInst>(CI->clone());
2897     New->setCalledFunction(FIPrintFFn);
2898     B.Insert(New);
2899     return New;
2900   }
2901 
2902   // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2903   // 128-bit floating point arguments.
2904   if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) &&
2905       !callHasFP128Argument(CI)) {
2906     auto SmallFPrintFFn =
2907         getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT,
2908                            Callee->getAttributes());
2909     CallInst *New = cast<CallInst>(CI->clone());
2910     New->setCalledFunction(SmallFPrintFFn);
2911     B.Insert(New);
2912     return New;
2913   }
2914 
2915   return nullptr;
2916 }
2917 
2918 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
2919   optimizeErrorReporting(CI, B, 3);
2920 
2921   // Get the element size and count.
2922   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2923   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2924   if (SizeC && CountC) {
2925     uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2926 
2927     // If this is writing zero records, remove the call (it's a noop).
2928     if (Bytes == 0)
2929       return ConstantInt::get(CI->getType(), 0);
2930 
2931     // If this is writing one byte, turn it into fputc.
2932     // This optimisation is only valid, if the return value is unused.
2933     if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2934       Value *Char = B.CreateLoad(B.getInt8Ty(),
2935                                  castToCStr(CI->getArgOperand(0), B), "char");
2936       Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2937       return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2938     }
2939   }
2940 
2941   return nullptr;
2942 }
2943 
2944 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
2945   optimizeErrorReporting(CI, B, 1);
2946 
2947   // Don't rewrite fputs to fwrite when optimising for size because fwrite
2948   // requires more arguments and thus extra MOVs are required.
2949   bool OptForSize = CI->getFunction()->hasOptSize() ||
2950                     llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
2951                                                 PGSOQueryType::IRPass);
2952   if (OptForSize)
2953     return nullptr;
2954 
2955   // We can't optimize if return value is used.
2956   if (!CI->use_empty())
2957     return nullptr;
2958 
2959   // fputs(s,F) --> fwrite(s,strlen(s),1,F)
2960   uint64_t Len = GetStringLength(CI->getArgOperand(0));
2961   if (!Len)
2962     return nullptr;
2963 
2964   // Known to have no uses (see above).
2965   return copyFlags(
2966       *CI,
2967       emitFWrite(CI->getArgOperand(0),
2968                  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2969                  CI->getArgOperand(1), B, DL, TLI));
2970 }
2971 
2972 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
2973   annotateNonNullNoUndefBasedOnAccess(CI, 0);
2974   if (!CI->use_empty())
2975     return nullptr;
2976 
2977   // Check for a constant string.
2978   // puts("") -> putchar('\n')
2979   StringRef Str;
2980   if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2981     return copyFlags(*CI, emitPutChar(B.getInt32('\n'), B, TLI));
2982 
2983   return nullptr;
2984 }
2985 
2986 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
2987   // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
2988   return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
2989                                         CI->getArgOperand(0), Align(1),
2990                                         CI->getArgOperand(2)));
2991 }
2992 
2993 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) {
2994   SmallString<20> FloatFuncName = FuncName;
2995   FloatFuncName += 'f';
2996   return isLibFuncEmittable(M, TLI, FloatFuncName);
2997 }
2998 
2999 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
3000                                                       IRBuilderBase &Builder) {
3001   Module *M = CI->getModule();
3002   LibFunc Func;
3003   Function *Callee = CI->getCalledFunction();
3004   // Check for string/memory library functions.
3005   if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3006     // Make sure we never change the calling convention.
3007     assert(
3008         (ignoreCallingConv(Func) ||
3009          TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) &&
3010         "Optimizing string/memory libcall would change the calling convention");
3011     switch (Func) {
3012     case LibFunc_strcat:
3013       return optimizeStrCat(CI, Builder);
3014     case LibFunc_strncat:
3015       return optimizeStrNCat(CI, Builder);
3016     case LibFunc_strchr:
3017       return optimizeStrChr(CI, Builder);
3018     case LibFunc_strrchr:
3019       return optimizeStrRChr(CI, Builder);
3020     case LibFunc_strcmp:
3021       return optimizeStrCmp(CI, Builder);
3022     case LibFunc_strncmp:
3023       return optimizeStrNCmp(CI, Builder);
3024     case LibFunc_strcpy:
3025       return optimizeStrCpy(CI, Builder);
3026     case LibFunc_stpcpy:
3027       return optimizeStpCpy(CI, Builder);
3028     case LibFunc_strncpy:
3029       return optimizeStrNCpy(CI, Builder);
3030     case LibFunc_strlen:
3031       return optimizeStrLen(CI, Builder);
3032     case LibFunc_strnlen:
3033       return optimizeStrNLen(CI, Builder);
3034     case LibFunc_strpbrk:
3035       return optimizeStrPBrk(CI, Builder);
3036     case LibFunc_strndup:
3037       return optimizeStrNDup(CI, Builder);
3038     case LibFunc_strtol:
3039     case LibFunc_strtod:
3040     case LibFunc_strtof:
3041     case LibFunc_strtoul:
3042     case LibFunc_strtoll:
3043     case LibFunc_strtold:
3044     case LibFunc_strtoull:
3045       return optimizeStrTo(CI, Builder);
3046     case LibFunc_strspn:
3047       return optimizeStrSpn(CI, Builder);
3048     case LibFunc_strcspn:
3049       return optimizeStrCSpn(CI, Builder);
3050     case LibFunc_strstr:
3051       return optimizeStrStr(CI, Builder);
3052     case LibFunc_memchr:
3053       return optimizeMemChr(CI, Builder);
3054     case LibFunc_memrchr:
3055       return optimizeMemRChr(CI, Builder);
3056     case LibFunc_bcmp:
3057       return optimizeBCmp(CI, Builder);
3058     case LibFunc_memcmp:
3059       return optimizeMemCmp(CI, Builder);
3060     case LibFunc_memcpy:
3061       return optimizeMemCpy(CI, Builder);
3062     case LibFunc_memccpy:
3063       return optimizeMemCCpy(CI, Builder);
3064     case LibFunc_mempcpy:
3065       return optimizeMemPCpy(CI, Builder);
3066     case LibFunc_memmove:
3067       return optimizeMemMove(CI, Builder);
3068     case LibFunc_memset:
3069       return optimizeMemSet(CI, Builder);
3070     case LibFunc_realloc:
3071       return optimizeRealloc(CI, Builder);
3072     case LibFunc_wcslen:
3073       return optimizeWcslen(CI, Builder);
3074     case LibFunc_bcopy:
3075       return optimizeBCopy(CI, Builder);
3076     default:
3077       break;
3078     }
3079   }
3080   return nullptr;
3081 }
3082 
3083 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
3084                                                        LibFunc Func,
3085                                                        IRBuilderBase &Builder) {
3086   const Module *M = CI->getModule();
3087 
3088   // Don't optimize calls that require strict floating point semantics.
3089   if (CI->isStrictFP())
3090     return nullptr;
3091 
3092   if (Value *V = optimizeTrigReflections(CI, Func, Builder))
3093     return V;
3094 
3095   switch (Func) {
3096   case LibFunc_sinpif:
3097   case LibFunc_sinpi:
3098   case LibFunc_cospif:
3099   case LibFunc_cospi:
3100     return optimizeSinCosPi(CI, Builder);
3101   case LibFunc_powf:
3102   case LibFunc_pow:
3103   case LibFunc_powl:
3104     return optimizePow(CI, Builder);
3105   case LibFunc_exp2l:
3106   case LibFunc_exp2:
3107   case LibFunc_exp2f:
3108     return optimizeExp2(CI, Builder);
3109   case LibFunc_fabsf:
3110   case LibFunc_fabs:
3111   case LibFunc_fabsl:
3112     return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
3113   case LibFunc_sqrtf:
3114   case LibFunc_sqrt:
3115   case LibFunc_sqrtl:
3116     return optimizeSqrt(CI, Builder);
3117   case LibFunc_logf:
3118   case LibFunc_log:
3119   case LibFunc_logl:
3120   case LibFunc_log10f:
3121   case LibFunc_log10:
3122   case LibFunc_log10l:
3123   case LibFunc_log1pf:
3124   case LibFunc_log1p:
3125   case LibFunc_log1pl:
3126   case LibFunc_log2f:
3127   case LibFunc_log2:
3128   case LibFunc_log2l:
3129   case LibFunc_logbf:
3130   case LibFunc_logb:
3131   case LibFunc_logbl:
3132     return optimizeLog(CI, Builder);
3133   case LibFunc_tan:
3134   case LibFunc_tanf:
3135   case LibFunc_tanl:
3136     return optimizeTan(CI, Builder);
3137   case LibFunc_ceil:
3138     return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
3139   case LibFunc_floor:
3140     return replaceUnaryCall(CI, Builder, Intrinsic::floor);
3141   case LibFunc_round:
3142     return replaceUnaryCall(CI, Builder, Intrinsic::round);
3143   case LibFunc_roundeven:
3144     return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
3145   case LibFunc_nearbyint:
3146     return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
3147   case LibFunc_rint:
3148     return replaceUnaryCall(CI, Builder, Intrinsic::rint);
3149   case LibFunc_trunc:
3150     return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
3151   case LibFunc_acos:
3152   case LibFunc_acosh:
3153   case LibFunc_asin:
3154   case LibFunc_asinh:
3155   case LibFunc_atan:
3156   case LibFunc_atanh:
3157   case LibFunc_cbrt:
3158   case LibFunc_cosh:
3159   case LibFunc_exp:
3160   case LibFunc_exp10:
3161   case LibFunc_expm1:
3162   case LibFunc_cos:
3163   case LibFunc_sin:
3164   case LibFunc_sinh:
3165   case LibFunc_tanh:
3166     if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName()))
3167       return optimizeUnaryDoubleFP(CI, Builder, TLI, true);
3168     return nullptr;
3169   case LibFunc_copysign:
3170     if (hasFloatVersion(M, CI->getCalledFunction()->getName()))
3171       return optimizeBinaryDoubleFP(CI, Builder, TLI);
3172     return nullptr;
3173   case LibFunc_fminf:
3174   case LibFunc_fmin:
3175   case LibFunc_fminl:
3176   case LibFunc_fmaxf:
3177   case LibFunc_fmax:
3178   case LibFunc_fmaxl:
3179     return optimizeFMinFMax(CI, Builder);
3180   case LibFunc_cabs:
3181   case LibFunc_cabsf:
3182   case LibFunc_cabsl:
3183     return optimizeCAbs(CI, Builder);
3184   default:
3185     return nullptr;
3186   }
3187 }
3188 
3189 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) {
3190   Module *M = CI->getModule();
3191   assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
3192 
3193   // TODO: Split out the code below that operates on FP calls so that
3194   //       we can all non-FP calls with the StrictFP attribute to be
3195   //       optimized.
3196   if (CI->isNoBuiltin())
3197     return nullptr;
3198 
3199   LibFunc Func;
3200   Function *Callee = CI->getCalledFunction();
3201   bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
3202 
3203   SmallVector<OperandBundleDef, 2> OpBundles;
3204   CI->getOperandBundlesAsDefs(OpBundles);
3205 
3206   IRBuilderBase::OperandBundlesGuard Guard(Builder);
3207   Builder.setDefaultOperandBundles(OpBundles);
3208 
3209   // Command-line parameter overrides instruction attribute.
3210   // This can't be moved to optimizeFloatingPointLibCall() because it may be
3211   // used by the intrinsic optimizations.
3212   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
3213     UnsafeFPShrink = EnableUnsafeFPShrink;
3214   else if (isa<FPMathOperator>(CI) && CI->isFast())
3215     UnsafeFPShrink = true;
3216 
3217   // First, check for intrinsics.
3218   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
3219     if (!IsCallingConvC)
3220       return nullptr;
3221     // The FP intrinsics have corresponding constrained versions so we don't
3222     // need to check for the StrictFP attribute here.
3223     switch (II->getIntrinsicID()) {
3224     case Intrinsic::pow:
3225       return optimizePow(CI, Builder);
3226     case Intrinsic::exp2:
3227       return optimizeExp2(CI, Builder);
3228     case Intrinsic::log:
3229     case Intrinsic::log2:
3230     case Intrinsic::log10:
3231       return optimizeLog(CI, Builder);
3232     case Intrinsic::sqrt:
3233       return optimizeSqrt(CI, Builder);
3234     case Intrinsic::memset:
3235       return optimizeMemSet(CI, Builder);
3236     case Intrinsic::memcpy:
3237       return optimizeMemCpy(CI, Builder);
3238     case Intrinsic::memmove:
3239       return optimizeMemMove(CI, Builder);
3240     default:
3241       return nullptr;
3242     }
3243   }
3244 
3245   // Also try to simplify calls to fortified library functions.
3246   if (Value *SimplifiedFortifiedCI =
3247           FortifiedSimplifier.optimizeCall(CI, Builder)) {
3248     // Try to further simplify the result.
3249     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
3250     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
3251       // Ensure that SimplifiedCI's uses are complete, since some calls have
3252       // their uses analyzed.
3253       replaceAllUsesWith(CI, SimplifiedCI);
3254 
3255       // Set insertion point to SimplifiedCI to guarantee we reach all uses
3256       // we might replace later on.
3257       IRBuilderBase::InsertPointGuard Guard(Builder);
3258       Builder.SetInsertPoint(SimplifiedCI);
3259       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
3260         // If we were able to further simplify, remove the now redundant call.
3261         substituteInParent(SimplifiedCI, V);
3262         return V;
3263       }
3264     }
3265     return SimplifiedFortifiedCI;
3266   }
3267 
3268   // Then check for known library functions.
3269   if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3270     // We never change the calling convention.
3271     if (!ignoreCallingConv(Func) && !IsCallingConvC)
3272       return nullptr;
3273     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
3274       return V;
3275     if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
3276       return V;
3277     switch (Func) {
3278     case LibFunc_ffs:
3279     case LibFunc_ffsl:
3280     case LibFunc_ffsll:
3281       return optimizeFFS(CI, Builder);
3282     case LibFunc_fls:
3283     case LibFunc_flsl:
3284     case LibFunc_flsll:
3285       return optimizeFls(CI, Builder);
3286     case LibFunc_abs:
3287     case LibFunc_labs:
3288     case LibFunc_llabs:
3289       return optimizeAbs(CI, Builder);
3290     case LibFunc_isdigit:
3291       return optimizeIsDigit(CI, Builder);
3292     case LibFunc_isascii:
3293       return optimizeIsAscii(CI, Builder);
3294     case LibFunc_toascii:
3295       return optimizeToAscii(CI, Builder);
3296     case LibFunc_atoi:
3297     case LibFunc_atol:
3298     case LibFunc_atoll:
3299       return optimizeAtoi(CI, Builder);
3300     case LibFunc_strtol:
3301     case LibFunc_strtoll:
3302       return optimizeStrtol(CI, Builder);
3303     case LibFunc_printf:
3304       return optimizePrintF(CI, Builder);
3305     case LibFunc_sprintf:
3306       return optimizeSPrintF(CI, Builder);
3307     case LibFunc_snprintf:
3308       return optimizeSnPrintF(CI, Builder);
3309     case LibFunc_fprintf:
3310       return optimizeFPrintF(CI, Builder);
3311     case LibFunc_fwrite:
3312       return optimizeFWrite(CI, Builder);
3313     case LibFunc_fputs:
3314       return optimizeFPuts(CI, Builder);
3315     case LibFunc_puts:
3316       return optimizePuts(CI, Builder);
3317     case LibFunc_perror:
3318       return optimizeErrorReporting(CI, Builder);
3319     case LibFunc_vfprintf:
3320     case LibFunc_fiprintf:
3321       return optimizeErrorReporting(CI, Builder, 0);
3322     default:
3323       return nullptr;
3324     }
3325   }
3326   return nullptr;
3327 }
3328 
3329 LibCallSimplifier::LibCallSimplifier(
3330     const DataLayout &DL, const TargetLibraryInfo *TLI,
3331     OptimizationRemarkEmitter &ORE,
3332     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
3333     function_ref<void(Instruction *, Value *)> Replacer,
3334     function_ref<void(Instruction *)> Eraser)
3335     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
3336       Replacer(Replacer), Eraser(Eraser) {}
3337 
3338 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
3339   // Indirect through the replacer used in this instance.
3340   Replacer(I, With);
3341 }
3342 
3343 void LibCallSimplifier::eraseFromParent(Instruction *I) {
3344   Eraser(I);
3345 }
3346 
3347 // TODO:
3348 //   Additional cases that we need to add to this file:
3349 //
3350 // cbrt:
3351 //   * cbrt(expN(X))  -> expN(x/3)
3352 //   * cbrt(sqrt(x))  -> pow(x,1/6)
3353 //   * cbrt(cbrt(x))  -> pow(x,1/9)
3354 //
3355 // exp, expf, expl:
3356 //   * exp(log(x))  -> x
3357 //
3358 // log, logf, logl:
3359 //   * log(exp(x))   -> x
3360 //   * log(exp(y))   -> y*log(e)
3361 //   * log(exp10(y)) -> y*log(10)
3362 //   * log(sqrt(x))  -> 0.5*log(x)
3363 //
3364 // pow, powf, powl:
3365 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
3366 //   * pow(pow(x,y),z)-> pow(x,y*z)
3367 //
3368 // signbit:
3369 //   * signbit(cnst) -> cnst'
3370 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
3371 //
3372 // sqrt, sqrtf, sqrtl:
3373 //   * sqrt(expN(x))  -> expN(x*0.5)
3374 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
3375 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
3376 //
3377 
3378 //===----------------------------------------------------------------------===//
3379 // Fortified Library Call Optimizations
3380 //===----------------------------------------------------------------------===//
3381 
3382 bool
3383 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
3384                                                     unsigned ObjSizeOp,
3385                                                     Optional<unsigned> SizeOp,
3386                                                     Optional<unsigned> StrOp,
3387                                                     Optional<unsigned> FlagOp) {
3388   // If this function takes a flag argument, the implementation may use it to
3389   // perform extra checks. Don't fold into the non-checking variant.
3390   if (FlagOp) {
3391     ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
3392     if (!Flag || !Flag->isZero())
3393       return false;
3394   }
3395 
3396   if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
3397     return true;
3398 
3399   if (ConstantInt *ObjSizeCI =
3400           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
3401     if (ObjSizeCI->isMinusOne())
3402       return true;
3403     // If the object size wasn't -1 (unknown), bail out if we were asked to.
3404     if (OnlyLowerUnknownSize)
3405       return false;
3406     if (StrOp) {
3407       uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
3408       // If the length is 0 we don't know how long it is and so we can't
3409       // remove the check.
3410       if (Len)
3411         annotateDereferenceableBytes(CI, *StrOp, Len);
3412       else
3413         return false;
3414       return ObjSizeCI->getZExtValue() >= Len;
3415     }
3416 
3417     if (SizeOp) {
3418       if (ConstantInt *SizeCI =
3419               dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
3420         return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
3421     }
3422   }
3423   return false;
3424 }
3425 
3426 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
3427                                                      IRBuilderBase &B) {
3428   if (isFortifiedCallFoldable(CI, 3, 2)) {
3429     CallInst *NewCI =
3430         B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
3431                        Align(1), CI->getArgOperand(2));
3432     NewCI->setAttributes(CI->getAttributes());
3433     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3434     copyFlags(*CI, NewCI);
3435     return CI->getArgOperand(0);
3436   }
3437   return nullptr;
3438 }
3439 
3440 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
3441                                                       IRBuilderBase &B) {
3442   if (isFortifiedCallFoldable(CI, 3, 2)) {
3443     CallInst *NewCI =
3444         B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
3445                         Align(1), CI->getArgOperand(2));
3446     NewCI->setAttributes(CI->getAttributes());
3447     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3448     copyFlags(*CI, NewCI);
3449     return CI->getArgOperand(0);
3450   }
3451   return nullptr;
3452 }
3453 
3454 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
3455                                                      IRBuilderBase &B) {
3456   if (isFortifiedCallFoldable(CI, 3, 2)) {
3457     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
3458     CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
3459                                      CI->getArgOperand(2), Align(1));
3460     NewCI->setAttributes(CI->getAttributes());
3461     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3462     copyFlags(*CI, NewCI);
3463     return CI->getArgOperand(0);
3464   }
3465   return nullptr;
3466 }
3467 
3468 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
3469                                                       IRBuilderBase &B) {
3470   const DataLayout &DL = CI->getModule()->getDataLayout();
3471   if (isFortifiedCallFoldable(CI, 3, 2))
3472     if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3473                                   CI->getArgOperand(2), B, DL, TLI)) {
3474       CallInst *NewCI = cast<CallInst>(Call);
3475       NewCI->setAttributes(CI->getAttributes());
3476       NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3477       return copyFlags(*CI, NewCI);
3478     }
3479   return nullptr;
3480 }
3481 
3482 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
3483                                                       IRBuilderBase &B,
3484                                                       LibFunc Func) {
3485   const DataLayout &DL = CI->getModule()->getDataLayout();
3486   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
3487         *ObjSize = CI->getArgOperand(2);
3488 
3489   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
3490   if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
3491     Value *StrLen = emitStrLen(Src, B, DL, TLI);
3492     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
3493   }
3494 
3495   // If a) we don't have any length information, or b) we know this will
3496   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
3497   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
3498   // TODO: It might be nice to get a maximum length out of the possible
3499   // string lengths for varying.
3500   if (isFortifiedCallFoldable(CI, 2, None, 1)) {
3501     if (Func == LibFunc_strcpy_chk)
3502       return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
3503     else
3504       return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
3505   }
3506 
3507   if (OnlyLowerUnknownSize)
3508     return nullptr;
3509 
3510   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
3511   uint64_t Len = GetStringLength(Src);
3512   if (Len)
3513     annotateDereferenceableBytes(CI, 1, Len);
3514   else
3515     return nullptr;
3516 
3517   // FIXME: There is really no guarantee that sizeof(size_t) is equal to
3518   // sizeof(int*) for every target. So the assumption used here to derive the
3519   // SizeTBits based on the size of an integer pointer in address space zero
3520   // isn't always valid.
3521   Type *SizeTTy = DL.getIntPtrType(CI->getContext(), /*AddressSpace=*/0);
3522   Value *LenV = ConstantInt::get(SizeTTy, Len);
3523   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
3524   // If the function was an __stpcpy_chk, and we were able to fold it into
3525   // a __memcpy_chk, we still need to return the correct end pointer.
3526   if (Ret && Func == LibFunc_stpcpy_chk)
3527     return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
3528   return copyFlags(*CI, cast<CallInst>(Ret));
3529 }
3530 
3531 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
3532                                                      IRBuilderBase &B) {
3533   if (isFortifiedCallFoldable(CI, 1, None, 0))
3534     return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
3535                                      CI->getModule()->getDataLayout(), TLI));
3536   return nullptr;
3537 }
3538 
3539 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
3540                                                        IRBuilderBase &B,
3541                                                        LibFunc Func) {
3542   if (isFortifiedCallFoldable(CI, 3, 2)) {
3543     if (Func == LibFunc_strncpy_chk)
3544       return copyFlags(*CI,
3545                        emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3546                                    CI->getArgOperand(2), B, TLI));
3547     else
3548       return copyFlags(*CI,
3549                        emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3550                                    CI->getArgOperand(2), B, TLI));
3551   }
3552 
3553   return nullptr;
3554 }
3555 
3556 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
3557                                                       IRBuilderBase &B) {
3558   if (isFortifiedCallFoldable(CI, 4, 3))
3559     return copyFlags(
3560         *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3561                          CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
3562 
3563   return nullptr;
3564 }
3565 
3566 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3567                                                        IRBuilderBase &B) {
3568   if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3569     SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
3570     return copyFlags(*CI,
3571                      emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3572                                   CI->getArgOperand(4), VariadicArgs, B, TLI));
3573   }
3574 
3575   return nullptr;
3576 }
3577 
3578 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3579                                                       IRBuilderBase &B) {
3580   if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3581     SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
3582     return copyFlags(*CI,
3583                      emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3584                                  VariadicArgs, B, TLI));
3585   }
3586 
3587   return nullptr;
3588 }
3589 
3590 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3591                                                      IRBuilderBase &B) {
3592   if (isFortifiedCallFoldable(CI, 2))
3593     return copyFlags(
3594         *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
3595 
3596   return nullptr;
3597 }
3598 
3599 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3600                                                    IRBuilderBase &B) {
3601   if (isFortifiedCallFoldable(CI, 3))
3602     return copyFlags(*CI,
3603                      emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3604                                  CI->getArgOperand(2), B, TLI));
3605 
3606   return nullptr;
3607 }
3608 
3609 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3610                                                       IRBuilderBase &B) {
3611   if (isFortifiedCallFoldable(CI, 3))
3612     return copyFlags(*CI,
3613                      emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3614                                  CI->getArgOperand(2), B, TLI));
3615 
3616   return nullptr;
3617 }
3618 
3619 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3620                                                       IRBuilderBase &B) {
3621   if (isFortifiedCallFoldable(CI, 3))
3622     return copyFlags(*CI,
3623                      emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3624                                  CI->getArgOperand(2), B, TLI));
3625 
3626   return nullptr;
3627 }
3628 
3629 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3630                                                         IRBuilderBase &B) {
3631   if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3632     return copyFlags(
3633         *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3634                            CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
3635 
3636   return nullptr;
3637 }
3638 
3639 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3640                                                        IRBuilderBase &B) {
3641   if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3642     return copyFlags(*CI,
3643                      emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3644                                   CI->getArgOperand(4), B, TLI));
3645 
3646   return nullptr;
3647 }
3648 
3649 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI,
3650                                                 IRBuilderBase &Builder) {
3651   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3652   // Some clang users checked for _chk libcall availability using:
3653   //   __has_builtin(__builtin___memcpy_chk)
3654   // When compiling with -fno-builtin, this is always true.
3655   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3656   // end up with fortified libcalls, which isn't acceptable in a freestanding
3657   // environment which only provides their non-fortified counterparts.
3658   //
3659   // Until we change clang and/or teach external users to check for availability
3660   // differently, disregard the "nobuiltin" attribute and TLI::has.
3661   //
3662   // PR23093.
3663 
3664   LibFunc Func;
3665   Function *Callee = CI->getCalledFunction();
3666   bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
3667 
3668   SmallVector<OperandBundleDef, 2> OpBundles;
3669   CI->getOperandBundlesAsDefs(OpBundles);
3670 
3671   IRBuilderBase::OperandBundlesGuard Guard(Builder);
3672   Builder.setDefaultOperandBundles(OpBundles);
3673 
3674   // First, check that this is a known library functions and that the prototype
3675   // is correct.
3676   if (!TLI->getLibFunc(*Callee, Func))
3677     return nullptr;
3678 
3679   // We never change the calling convention.
3680   if (!ignoreCallingConv(Func) && !IsCallingConvC)
3681     return nullptr;
3682 
3683   switch (Func) {
3684   case LibFunc_memcpy_chk:
3685     return optimizeMemCpyChk(CI, Builder);
3686   case LibFunc_mempcpy_chk:
3687     return optimizeMemPCpyChk(CI, Builder);
3688   case LibFunc_memmove_chk:
3689     return optimizeMemMoveChk(CI, Builder);
3690   case LibFunc_memset_chk:
3691     return optimizeMemSetChk(CI, Builder);
3692   case LibFunc_stpcpy_chk:
3693   case LibFunc_strcpy_chk:
3694     return optimizeStrpCpyChk(CI, Builder, Func);
3695   case LibFunc_strlen_chk:
3696     return optimizeStrLenChk(CI, Builder);
3697   case LibFunc_stpncpy_chk:
3698   case LibFunc_strncpy_chk:
3699     return optimizeStrpNCpyChk(CI, Builder, Func);
3700   case LibFunc_memccpy_chk:
3701     return optimizeMemCCpyChk(CI, Builder);
3702   case LibFunc_snprintf_chk:
3703     return optimizeSNPrintfChk(CI, Builder);
3704   case LibFunc_sprintf_chk:
3705     return optimizeSPrintfChk(CI, Builder);
3706   case LibFunc_strcat_chk:
3707     return optimizeStrCatChk(CI, Builder);
3708   case LibFunc_strlcat_chk:
3709     return optimizeStrLCat(CI, Builder);
3710   case LibFunc_strncat_chk:
3711     return optimizeStrNCatChk(CI, Builder);
3712   case LibFunc_strlcpy_chk:
3713     return optimizeStrLCpyChk(CI, Builder);
3714   case LibFunc_vsnprintf_chk:
3715     return optimizeVSNPrintfChk(CI, Builder);
3716   case LibFunc_vsprintf_chk:
3717     return optimizeVSPrintfChk(CI, Builder);
3718   default:
3719     break;
3720   }
3721   return nullptr;
3722 }
3723 
3724 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3725     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
3726     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
3727