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