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