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   // If we can approximate pow:
1952   // pow(x, n) -> powi(x, n) * sqrt(x) if n has exactly a 0.5 fraction
1953   // pow(x, n) -> powi(x, n) if n is a constant signed integer value
1954   const APFloat *ExpoF;
1955   if (AllowApprox && match(Expo, m_APFloat(ExpoF)) &&
1956       !ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)) {
1957     APFloat ExpoA(abs(*ExpoF));
1958     APFloat ExpoI(*ExpoF);
1959     Value *Sqrt = nullptr;
1960     if (!ExpoA.isInteger()) {
1961       APFloat Expo2 = ExpoA;
1962       // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1963       // is no floating point exception and the result is an integer, then
1964       // ExpoA == integer + 0.5
1965       if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1966         return nullptr;
1967 
1968       if (!Expo2.isInteger())
1969         return nullptr;
1970 
1971       if (ExpoI.roundToIntegral(APFloat::rmTowardNegative) !=
1972           APFloat::opInexact)
1973         return nullptr;
1974       if (!ExpoI.isInteger())
1975         return nullptr;
1976       ExpoF = &ExpoI;
1977 
1978       Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1979                          Pow->doesNotAccessMemory(), M, B, TLI);
1980       if (!Sqrt)
1981         return nullptr;
1982     }
1983 
1984     // 0.5 fraction is now optionally handled.
1985     // Do pow -> powi for remaining integer exponent
1986     APSInt IntExpo(TLI->getIntSize(), /*isUnsigned=*/false);
1987     if (ExpoF->isInteger() &&
1988         ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
1989             APFloat::opOK) {
1990       Value *PowI = copyFlags(
1991           *Pow,
1992           createPowWithIntegerExponent(
1993               Base, ConstantInt::get(B.getIntNTy(TLI->getIntSize()), IntExpo),
1994               M, B));
1995 
1996       if (PowI && Sqrt)
1997         return B.CreateFMul(PowI, Sqrt);
1998 
1999       return PowI;
2000     }
2001   }
2002 
2003   // powf(x, itofp(y)) -> powi(x, y)
2004   if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
2005     if (Value *ExpoI = getIntToFPVal(Expo, B, TLI->getIntSize()))
2006       return copyFlags(*Pow, createPowWithIntegerExponent(Base, ExpoI, M, B));
2007   }
2008 
2009   // Shrink pow() to powf() if the arguments are single precision,
2010   // unless the result is expected to be double precision.
2011   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
2012       hasFloatVersion(M, Name)) {
2013     if (Value *Shrunk = optimizeBinaryDoubleFP(Pow, B, TLI, true))
2014       return Shrunk;
2015   }
2016 
2017   return nullptr;
2018 }
2019 
2020 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilderBase &B) {
2021   Module *M = CI->getModule();
2022   Function *Callee = CI->getCalledFunction();
2023   AttributeList Attrs; // Attributes are only meaningful on the original call
2024   StringRef Name = Callee->getName();
2025   Value *Ret = nullptr;
2026   if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
2027       hasFloatVersion(M, Name))
2028     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2029 
2030   Type *Ty = CI->getType();
2031   Value *Op = CI->getArgOperand(0);
2032 
2033   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= IntSize
2034   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < IntSize
2035   if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
2036       hasFloatFn(M, TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
2037     if (Value *Exp = getIntToFPVal(Op, B, TLI->getIntSize()))
2038       return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
2039                                    LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
2040                                    B, Attrs);
2041   }
2042 
2043   return Ret;
2044 }
2045 
2046 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilderBase &B) {
2047   Module *M = CI->getModule();
2048 
2049   // If we can shrink the call to a float function rather than a double
2050   // function, do that first.
2051   Function *Callee = CI->getCalledFunction();
2052   StringRef Name = Callee->getName();
2053   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(M, Name))
2054     if (Value *Ret = optimizeBinaryDoubleFP(CI, B, TLI))
2055       return Ret;
2056 
2057   // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
2058   // the intrinsics for improved optimization (for example, vectorization).
2059   // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
2060   // From the C standard draft WG14/N1256:
2061   // "Ideally, fmax would be sensitive to the sign of zero, for example
2062   // fmax(-0.0, +0.0) would return +0; however, implementation in software
2063   // might be impractical."
2064   IRBuilderBase::FastMathFlagGuard Guard(B);
2065   FastMathFlags FMF = CI->getFastMathFlags();
2066   FMF.setNoSignedZeros();
2067   B.setFastMathFlags(FMF);
2068 
2069   Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
2070                                                            : Intrinsic::maxnum;
2071   Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
2072   return copyFlags(
2073       *CI, B.CreateCall(F, {CI->getArgOperand(0), CI->getArgOperand(1)}));
2074 }
2075 
2076 Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilderBase &B) {
2077   Function *LogFn = Log->getCalledFunction();
2078   AttributeList Attrs; // Attributes are only meaningful on the original call
2079   StringRef LogNm = LogFn->getName();
2080   Intrinsic::ID LogID = LogFn->getIntrinsicID();
2081   Module *Mod = Log->getModule();
2082   Type *Ty = Log->getType();
2083   Value *Ret = nullptr;
2084 
2085   if (UnsafeFPShrink && hasFloatVersion(Mod, LogNm))
2086     Ret = optimizeUnaryDoubleFP(Log, B, TLI, true);
2087 
2088   // The earlier call must also be 'fast' in order to do these transforms.
2089   CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
2090   if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
2091     return Ret;
2092 
2093   LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
2094 
2095   // This is only applicable to log(), log2(), log10().
2096   if (TLI->getLibFunc(LogNm, LogLb))
2097     switch (LogLb) {
2098     case LibFunc_logf:
2099       LogID = Intrinsic::log;
2100       ExpLb = LibFunc_expf;
2101       Exp2Lb = LibFunc_exp2f;
2102       Exp10Lb = LibFunc_exp10f;
2103       PowLb = LibFunc_powf;
2104       break;
2105     case LibFunc_log:
2106       LogID = Intrinsic::log;
2107       ExpLb = LibFunc_exp;
2108       Exp2Lb = LibFunc_exp2;
2109       Exp10Lb = LibFunc_exp10;
2110       PowLb = LibFunc_pow;
2111       break;
2112     case LibFunc_logl:
2113       LogID = Intrinsic::log;
2114       ExpLb = LibFunc_expl;
2115       Exp2Lb = LibFunc_exp2l;
2116       Exp10Lb = LibFunc_exp10l;
2117       PowLb = LibFunc_powl;
2118       break;
2119     case LibFunc_log2f:
2120       LogID = Intrinsic::log2;
2121       ExpLb = LibFunc_expf;
2122       Exp2Lb = LibFunc_exp2f;
2123       Exp10Lb = LibFunc_exp10f;
2124       PowLb = LibFunc_powf;
2125       break;
2126     case LibFunc_log2:
2127       LogID = Intrinsic::log2;
2128       ExpLb = LibFunc_exp;
2129       Exp2Lb = LibFunc_exp2;
2130       Exp10Lb = LibFunc_exp10;
2131       PowLb = LibFunc_pow;
2132       break;
2133     case LibFunc_log2l:
2134       LogID = Intrinsic::log2;
2135       ExpLb = LibFunc_expl;
2136       Exp2Lb = LibFunc_exp2l;
2137       Exp10Lb = LibFunc_exp10l;
2138       PowLb = LibFunc_powl;
2139       break;
2140     case LibFunc_log10f:
2141       LogID = Intrinsic::log10;
2142       ExpLb = LibFunc_expf;
2143       Exp2Lb = LibFunc_exp2f;
2144       Exp10Lb = LibFunc_exp10f;
2145       PowLb = LibFunc_powf;
2146       break;
2147     case LibFunc_log10:
2148       LogID = Intrinsic::log10;
2149       ExpLb = LibFunc_exp;
2150       Exp2Lb = LibFunc_exp2;
2151       Exp10Lb = LibFunc_exp10;
2152       PowLb = LibFunc_pow;
2153       break;
2154     case LibFunc_log10l:
2155       LogID = Intrinsic::log10;
2156       ExpLb = LibFunc_expl;
2157       Exp2Lb = LibFunc_exp2l;
2158       Exp10Lb = LibFunc_exp10l;
2159       PowLb = LibFunc_powl;
2160       break;
2161     default:
2162       return Ret;
2163     }
2164   else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
2165            LogID == Intrinsic::log10) {
2166     if (Ty->getScalarType()->isFloatTy()) {
2167       ExpLb = LibFunc_expf;
2168       Exp2Lb = LibFunc_exp2f;
2169       Exp10Lb = LibFunc_exp10f;
2170       PowLb = LibFunc_powf;
2171     } else if (Ty->getScalarType()->isDoubleTy()) {
2172       ExpLb = LibFunc_exp;
2173       Exp2Lb = LibFunc_exp2;
2174       Exp10Lb = LibFunc_exp10;
2175       PowLb = LibFunc_pow;
2176     } else
2177       return Ret;
2178   } else
2179     return Ret;
2180 
2181   IRBuilderBase::FastMathFlagGuard Guard(B);
2182   B.setFastMathFlags(FastMathFlags::getFast());
2183 
2184   Intrinsic::ID ArgID = Arg->getIntrinsicID();
2185   LibFunc ArgLb = NotLibFunc;
2186   TLI->getLibFunc(*Arg, ArgLb);
2187 
2188   // log(pow(x,y)) -> y*log(x)
2189   if (ArgLb == PowLb || ArgID == Intrinsic::pow) {
2190     Value *LogX =
2191         Log->doesNotAccessMemory()
2192             ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
2193                            Arg->getOperand(0), "log")
2194             : emitUnaryFloatFnCall(Arg->getOperand(0), TLI, LogNm, B, Attrs);
2195     Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul");
2196     // Since pow() may have side effects, e.g. errno,
2197     // dead code elimination may not be trusted to remove it.
2198     substituteInParent(Arg, MulY);
2199     return MulY;
2200   }
2201 
2202   // log(exp{,2,10}(y)) -> y*log({e,2,10})
2203   // TODO: There is no exp10() intrinsic yet.
2204   if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
2205            ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
2206     Constant *Eul;
2207     if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
2208       // FIXME: Add more precise value of e for long double.
2209       Eul = ConstantFP::get(Log->getType(), numbers::e);
2210     else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
2211       Eul = ConstantFP::get(Log->getType(), 2.0);
2212     else
2213       Eul = ConstantFP::get(Log->getType(), 10.0);
2214     Value *LogE = Log->doesNotAccessMemory()
2215                       ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
2216                                      Eul, "log")
2217                       : emitUnaryFloatFnCall(Eul, TLI, LogNm, B, Attrs);
2218     Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
2219     // Since exp() may have side effects, e.g. errno,
2220     // dead code elimination may not be trusted to remove it.
2221     substituteInParent(Arg, MulY);
2222     return MulY;
2223   }
2224 
2225   return Ret;
2226 }
2227 
2228 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilderBase &B) {
2229   Module *M = CI->getModule();
2230   Function *Callee = CI->getCalledFunction();
2231   Value *Ret = nullptr;
2232   // TODO: Once we have a way (other than checking for the existince of the
2233   // libcall) to tell whether our target can lower @llvm.sqrt, relax the
2234   // condition below.
2235   if (isLibFuncEmittable(M, TLI, LibFunc_sqrtf) &&
2236       (Callee->getName() == "sqrt" ||
2237        Callee->getIntrinsicID() == Intrinsic::sqrt))
2238     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2239 
2240   if (!CI->isFast())
2241     return Ret;
2242 
2243   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
2244   if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
2245     return Ret;
2246 
2247   // We're looking for a repeated factor in a multiplication tree,
2248   // so we can do this fold: sqrt(x * x) -> fabs(x);
2249   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
2250   Value *Op0 = I->getOperand(0);
2251   Value *Op1 = I->getOperand(1);
2252   Value *RepeatOp = nullptr;
2253   Value *OtherOp = nullptr;
2254   if (Op0 == Op1) {
2255     // Simple match: the operands of the multiply are identical.
2256     RepeatOp = Op0;
2257   } else {
2258     // Look for a more complicated pattern: one of the operands is itself
2259     // a multiply, so search for a common factor in that multiply.
2260     // Note: We don't bother looking any deeper than this first level or for
2261     // variations of this pattern because instcombine's visitFMUL and/or the
2262     // reassociation pass should give us this form.
2263     Value *OtherMul0, *OtherMul1;
2264     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
2265       // Pattern: sqrt((x * y) * z)
2266       if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
2267         // Matched: sqrt((x * x) * z)
2268         RepeatOp = OtherMul0;
2269         OtherOp = Op1;
2270       }
2271     }
2272   }
2273   if (!RepeatOp)
2274     return Ret;
2275 
2276   // Fast math flags for any created instructions should match the sqrt
2277   // and multiply.
2278   IRBuilderBase::FastMathFlagGuard Guard(B);
2279   B.setFastMathFlags(I->getFastMathFlags());
2280 
2281   // If we found a repeated factor, hoist it out of the square root and
2282   // replace it with the fabs of that factor.
2283   Type *ArgType = I->getType();
2284   Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
2285   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
2286   if (OtherOp) {
2287     // If we found a non-repeated factor, we still need to get its square
2288     // root. We then multiply that by the value that was simplified out
2289     // of the square root calculation.
2290     Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
2291     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
2292     return copyFlags(*CI, B.CreateFMul(FabsCall, SqrtCall));
2293   }
2294   return copyFlags(*CI, FabsCall);
2295 }
2296 
2297 // TODO: Generalize to handle any trig function and its inverse.
2298 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilderBase &B) {
2299   Module *M = CI->getModule();
2300   Function *Callee = CI->getCalledFunction();
2301   Value *Ret = nullptr;
2302   StringRef Name = Callee->getName();
2303   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(M, Name))
2304     Ret = optimizeUnaryDoubleFP(CI, B, TLI, true);
2305 
2306   Value *Op1 = CI->getArgOperand(0);
2307   auto *OpC = dyn_cast<CallInst>(Op1);
2308   if (!OpC)
2309     return Ret;
2310 
2311   // Both calls must be 'fast' in order to remove them.
2312   if (!CI->isFast() || !OpC->isFast())
2313     return Ret;
2314 
2315   // tan(atan(x)) -> x
2316   // tanf(atanf(x)) -> x
2317   // tanl(atanl(x)) -> x
2318   LibFunc Func;
2319   Function *F = OpC->getCalledFunction();
2320   if (F && TLI->getLibFunc(F->getName(), Func) &&
2321       isLibFuncEmittable(M, TLI, Func) &&
2322       ((Func == LibFunc_atan && Callee->getName() == "tan") ||
2323        (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
2324        (Func == LibFunc_atanl && Callee->getName() == "tanl")))
2325     Ret = OpC->getArgOperand(0);
2326   return Ret;
2327 }
2328 
2329 static bool isTrigLibCall(CallInst *CI) {
2330   // We can only hope to do anything useful if we can ignore things like errno
2331   // and floating-point exceptions.
2332   // We already checked the prototype.
2333   return CI->hasFnAttr(Attribute::NoUnwind) &&
2334          CI->hasFnAttr(Attribute::ReadNone);
2335 }
2336 
2337 static bool insertSinCosCall(IRBuilderBase &B, Function *OrigCallee, Value *Arg,
2338                              bool UseFloat, Value *&Sin, Value *&Cos,
2339                              Value *&SinCos, const TargetLibraryInfo *TLI) {
2340   Module *M = OrigCallee->getParent();
2341   Type *ArgTy = Arg->getType();
2342   Type *ResTy;
2343   StringRef Name;
2344 
2345   Triple T(OrigCallee->getParent()->getTargetTriple());
2346   if (UseFloat) {
2347     Name = "__sincospif_stret";
2348 
2349     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
2350     // x86_64 can't use {float, float} since that would be returned in both
2351     // xmm0 and xmm1, which isn't what a real struct would do.
2352     ResTy = T.getArch() == Triple::x86_64
2353                 ? static_cast<Type *>(FixedVectorType::get(ArgTy, 2))
2354                 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
2355   } else {
2356     Name = "__sincospi_stret";
2357     ResTy = StructType::get(ArgTy, ArgTy);
2358   }
2359 
2360   if (!isLibFuncEmittable(M, TLI, Name))
2361     return false;
2362   LibFunc TheLibFunc;
2363   TLI->getLibFunc(Name, TheLibFunc);
2364   FunctionCallee Callee = getOrInsertLibFunc(
2365       M, *TLI, TheLibFunc, OrigCallee->getAttributes(), ResTy, ArgTy);
2366 
2367   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
2368     // If the argument is an instruction, it must dominate all uses so put our
2369     // sincos call there.
2370     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
2371   } else {
2372     // Otherwise (e.g. for a constant) the beginning of the function is as
2373     // good a place as any.
2374     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
2375     B.SetInsertPoint(&EntryBB, EntryBB.begin());
2376   }
2377 
2378   SinCos = B.CreateCall(Callee, Arg, "sincospi");
2379 
2380   if (SinCos->getType()->isStructTy()) {
2381     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
2382     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
2383   } else {
2384     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
2385                                  "sinpi");
2386     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
2387                                  "cospi");
2388   }
2389 
2390   return true;
2391 }
2392 
2393 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilderBase &B) {
2394   // Make sure the prototype is as expected, otherwise the rest of the
2395   // function is probably invalid and likely to abort.
2396   if (!isTrigLibCall(CI))
2397     return nullptr;
2398 
2399   Value *Arg = CI->getArgOperand(0);
2400   SmallVector<CallInst *, 1> SinCalls;
2401   SmallVector<CallInst *, 1> CosCalls;
2402   SmallVector<CallInst *, 1> SinCosCalls;
2403 
2404   bool IsFloat = Arg->getType()->isFloatTy();
2405 
2406   // Look for all compatible sinpi, cospi and sincospi calls with the same
2407   // argument. If there are enough (in some sense) we can make the
2408   // substitution.
2409   Function *F = CI->getFunction();
2410   for (User *U : Arg->users())
2411     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
2412 
2413   // It's only worthwhile if both sinpi and cospi are actually used.
2414   if (SinCalls.empty() || CosCalls.empty())
2415     return nullptr;
2416 
2417   Value *Sin, *Cos, *SinCos;
2418   if (!insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
2419                         SinCos, TLI))
2420     return nullptr;
2421 
2422   auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
2423                                  Value *Res) {
2424     for (CallInst *C : Calls)
2425       replaceAllUsesWith(C, Res);
2426   };
2427 
2428   replaceTrigInsts(SinCalls, Sin);
2429   replaceTrigInsts(CosCalls, Cos);
2430   replaceTrigInsts(SinCosCalls, SinCos);
2431 
2432   return nullptr;
2433 }
2434 
2435 void LibCallSimplifier::classifyArgUse(
2436     Value *Val, Function *F, bool IsFloat,
2437     SmallVectorImpl<CallInst *> &SinCalls,
2438     SmallVectorImpl<CallInst *> &CosCalls,
2439     SmallVectorImpl<CallInst *> &SinCosCalls) {
2440   CallInst *CI = dyn_cast<CallInst>(Val);
2441   Module *M = CI->getModule();
2442 
2443   if (!CI || CI->use_empty())
2444     return;
2445 
2446   // Don't consider calls in other functions.
2447   if (CI->getFunction() != F)
2448     return;
2449 
2450   Function *Callee = CI->getCalledFunction();
2451   LibFunc Func;
2452   if (!Callee || !TLI->getLibFunc(*Callee, Func) ||
2453       !isLibFuncEmittable(M, TLI, Func) ||
2454       !isTrigLibCall(CI))
2455     return;
2456 
2457   if (IsFloat) {
2458     if (Func == LibFunc_sinpif)
2459       SinCalls.push_back(CI);
2460     else if (Func == LibFunc_cospif)
2461       CosCalls.push_back(CI);
2462     else if (Func == LibFunc_sincospif_stret)
2463       SinCosCalls.push_back(CI);
2464   } else {
2465     if (Func == LibFunc_sinpi)
2466       SinCalls.push_back(CI);
2467     else if (Func == LibFunc_cospi)
2468       CosCalls.push_back(CI);
2469     else if (Func == LibFunc_sincospi_stret)
2470       SinCosCalls.push_back(CI);
2471   }
2472 }
2473 
2474 //===----------------------------------------------------------------------===//
2475 // Integer Library Call Optimizations
2476 //===----------------------------------------------------------------------===//
2477 
2478 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilderBase &B) {
2479   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
2480   Value *Op = CI->getArgOperand(0);
2481   Type *ArgType = Op->getType();
2482   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2483                                           Intrinsic::cttz, ArgType);
2484   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
2485   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
2486   V = B.CreateIntCast(V, B.getInt32Ty(), false);
2487 
2488   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
2489   return B.CreateSelect(Cond, V, B.getInt32(0));
2490 }
2491 
2492 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilderBase &B) {
2493   // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
2494   Value *Op = CI->getArgOperand(0);
2495   Type *ArgType = Op->getType();
2496   Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2497                                           Intrinsic::ctlz, ArgType);
2498   Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
2499   V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
2500                   V);
2501   return B.CreateIntCast(V, CI->getType(), false);
2502 }
2503 
2504 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilderBase &B) {
2505   // abs(x) -> x <s 0 ? -x : x
2506   // The negation has 'nsw' because abs of INT_MIN is undefined.
2507   Value *X = CI->getArgOperand(0);
2508   Value *IsNeg = B.CreateIsNeg(X);
2509   Value *NegX = B.CreateNSWNeg(X, "neg");
2510   return B.CreateSelect(IsNeg, NegX, X);
2511 }
2512 
2513 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilderBase &B) {
2514   // isdigit(c) -> (c-'0') <u 10
2515   Value *Op = CI->getArgOperand(0);
2516   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
2517   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
2518   return B.CreateZExt(Op, CI->getType());
2519 }
2520 
2521 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilderBase &B) {
2522   // isascii(c) -> c <u 128
2523   Value *Op = CI->getArgOperand(0);
2524   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
2525   return B.CreateZExt(Op, CI->getType());
2526 }
2527 
2528 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilderBase &B) {
2529   // toascii(c) -> c & 0x7f
2530   return B.CreateAnd(CI->getArgOperand(0),
2531                      ConstantInt::get(CI->getType(), 0x7F));
2532 }
2533 
2534 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilderBase &B) {
2535   StringRef Str;
2536   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2537     return nullptr;
2538 
2539   return convertStrToNumber(CI, Str, nullptr, 10, B);
2540 }
2541 
2542 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilderBase &B) {
2543   StringRef Str;
2544   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2545     return nullptr;
2546 
2547   Value *EndPtr = CI->getArgOperand(1);
2548   if (isa<ConstantPointerNull>(EndPtr))
2549     EndPtr = nullptr;
2550   else if (!isKnownNonZero(EndPtr, DL))
2551     return nullptr;
2552 
2553   if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
2554     return convertStrToNumber(CI, Str, EndPtr, CInt->getSExtValue(), B);
2555   }
2556 
2557   return nullptr;
2558 }
2559 
2560 //===----------------------------------------------------------------------===//
2561 // Formatting and IO Library Call Optimizations
2562 //===----------------------------------------------------------------------===//
2563 
2564 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
2565 
2566 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilderBase &B,
2567                                                  int StreamArg) {
2568   Function *Callee = CI->getCalledFunction();
2569   // Error reporting calls should be cold, mark them as such.
2570   // This applies even to non-builtin calls: it is only a hint and applies to
2571   // functions that the frontend might not understand as builtins.
2572 
2573   // This heuristic was suggested in:
2574   // Improving Static Branch Prediction in a Compiler
2575   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2576   // Proceedings of PACT'98, Oct. 1998, IEEE
2577   if (!CI->hasFnAttr(Attribute::Cold) &&
2578       isReportingError(Callee, CI, StreamArg)) {
2579     CI->addFnAttr(Attribute::Cold);
2580   }
2581 
2582   return nullptr;
2583 }
2584 
2585 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
2586   if (!Callee || !Callee->isDeclaration())
2587     return false;
2588 
2589   if (StreamArg < 0)
2590     return true;
2591 
2592   // These functions might be considered cold, but only if their stream
2593   // argument is stderr.
2594 
2595   if (StreamArg >= (int)CI->arg_size())
2596     return false;
2597   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2598   if (!LI)
2599     return false;
2600   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2601   if (!GV || !GV->isDeclaration())
2602     return false;
2603   return GV->getName() == "stderr";
2604 }
2605 
2606 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilderBase &B) {
2607   // Check for a fixed format string.
2608   StringRef FormatStr;
2609   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
2610     return nullptr;
2611 
2612   // Empty format string -> noop.
2613   if (FormatStr.empty()) // Tolerate printf's declared void.
2614     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
2615 
2616   // Do not do any of the following transformations if the printf return value
2617   // is used, in general the printf return value is not compatible with either
2618   // putchar() or puts().
2619   if (!CI->use_empty())
2620     return nullptr;
2621 
2622   // printf("x") -> putchar('x'), even for "%" and "%%".
2623   if (FormatStr.size() == 1 || FormatStr == "%%")
2624     return copyFlags(*CI, emitPutChar(B.getInt32(FormatStr[0]), B, TLI));
2625 
2626   // Try to remove call or emit putchar/puts.
2627   if (FormatStr == "%s" && CI->arg_size() > 1) {
2628     StringRef OperandStr;
2629     if (!getConstantStringInfo(CI->getOperand(1), OperandStr))
2630       return nullptr;
2631     // printf("%s", "") --> NOP
2632     if (OperandStr.empty())
2633       return (Value *)CI;
2634     // printf("%s", "a") --> putchar('a')
2635     if (OperandStr.size() == 1)
2636       return copyFlags(*CI, emitPutChar(B.getInt32(OperandStr[0]), B, TLI));
2637     // printf("%s", str"\n") --> puts(str)
2638     if (OperandStr.back() == '\n') {
2639       OperandStr = OperandStr.drop_back();
2640       Value *GV = B.CreateGlobalString(OperandStr, "str");
2641       return copyFlags(*CI, emitPutS(GV, B, TLI));
2642     }
2643     return nullptr;
2644   }
2645 
2646   // printf("foo\n") --> puts("foo")
2647   if (FormatStr.back() == '\n' &&
2648       !FormatStr.contains('%')) { // No format characters.
2649     // Create a string literal with no \n on it.  We expect the constant merge
2650     // pass to be run after this pass, to merge duplicate strings.
2651     FormatStr = FormatStr.drop_back();
2652     Value *GV = B.CreateGlobalString(FormatStr, "str");
2653     return copyFlags(*CI, emitPutS(GV, B, TLI));
2654   }
2655 
2656   // Optimize specific format strings.
2657   // printf("%c", chr) --> putchar(chr)
2658   if (FormatStr == "%c" && CI->arg_size() > 1 &&
2659       CI->getArgOperand(1)->getType()->isIntegerTy())
2660     return copyFlags(*CI, emitPutChar(CI->getArgOperand(1), B, TLI));
2661 
2662   // printf("%s\n", str) --> puts(str)
2663   if (FormatStr == "%s\n" && CI->arg_size() > 1 &&
2664       CI->getArgOperand(1)->getType()->isPointerTy())
2665     return copyFlags(*CI, emitPutS(CI->getArgOperand(1), B, TLI));
2666   return nullptr;
2667 }
2668 
2669 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilderBase &B) {
2670 
2671   Module *M = CI->getModule();
2672   Function *Callee = CI->getCalledFunction();
2673   FunctionType *FT = Callee->getFunctionType();
2674   if (Value *V = optimizePrintFString(CI, B)) {
2675     return V;
2676   }
2677 
2678   // printf(format, ...) -> iprintf(format, ...) if no floating point
2679   // arguments.
2680   if (isLibFuncEmittable(M, TLI, LibFunc_iprintf) &&
2681       !callHasFloatingPointArgument(CI)) {
2682     FunctionCallee IPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_iprintf, FT,
2683                                                   Callee->getAttributes());
2684     CallInst *New = cast<CallInst>(CI->clone());
2685     New->setCalledFunction(IPrintFFn);
2686     B.Insert(New);
2687     return New;
2688   }
2689 
2690   // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2691   // arguments.
2692   if (isLibFuncEmittable(M, TLI, LibFunc_small_printf) &&
2693       !callHasFP128Argument(CI)) {
2694     auto SmallPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_printf, FT,
2695                                             Callee->getAttributes());
2696     CallInst *New = cast<CallInst>(CI->clone());
2697     New->setCalledFunction(SmallPrintFFn);
2698     B.Insert(New);
2699     return New;
2700   }
2701 
2702   annotateNonNullNoUndefBasedOnAccess(CI, 0);
2703   return nullptr;
2704 }
2705 
2706 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI,
2707                                                 IRBuilderBase &B) {
2708   // Check for a fixed format string.
2709   StringRef FormatStr;
2710   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2711     return nullptr;
2712 
2713   // If we just have a format string (nothing else crazy) transform it.
2714   Value *Dest = CI->getArgOperand(0);
2715   if (CI->arg_size() == 2) {
2716     // Make sure there's no % in the constant array.  We could try to handle
2717     // %% -> % in the future if we cared.
2718     if (FormatStr.contains('%'))
2719       return nullptr; // we found a format specifier, bail out.
2720 
2721     // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2722     B.CreateMemCpy(
2723         Dest, Align(1), CI->getArgOperand(1), Align(1),
2724         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2725                          FormatStr.size() + 1)); // Copy the null byte.
2726     return ConstantInt::get(CI->getType(), FormatStr.size());
2727   }
2728 
2729   // The remaining optimizations require the format string to be "%s" or "%c"
2730   // and have an extra operand.
2731   if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
2732     return nullptr;
2733 
2734   // Decode the second character of the format string.
2735   if (FormatStr[1] == 'c') {
2736     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2737     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2738       return nullptr;
2739     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2740     Value *Ptr = castToCStr(Dest, B);
2741     B.CreateStore(V, Ptr);
2742     Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2743     B.CreateStore(B.getInt8(0), Ptr);
2744 
2745     return ConstantInt::get(CI->getType(), 1);
2746   }
2747 
2748   if (FormatStr[1] == 's') {
2749     // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2750     // strlen(str)+1)
2751     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2752       return nullptr;
2753 
2754     if (CI->use_empty())
2755       // sprintf(dest, "%s", str) -> strcpy(dest, str)
2756       return copyFlags(*CI, emitStrCpy(Dest, CI->getArgOperand(2), B, TLI));
2757 
2758     uint64_t SrcLen = GetStringLength(CI->getArgOperand(2));
2759     if (SrcLen) {
2760       B.CreateMemCpy(
2761           Dest, Align(1), CI->getArgOperand(2), Align(1),
2762           ConstantInt::get(DL.getIntPtrType(CI->getContext()), SrcLen));
2763       // Returns total number of characters written without null-character.
2764       return ConstantInt::get(CI->getType(), SrcLen - 1);
2765     } else if (Value *V = emitStpCpy(Dest, CI->getArgOperand(2), B, TLI)) {
2766       // sprintf(dest, "%s", str) -> stpcpy(dest, str) - dest
2767       // Handle mismatched pointer types (goes away with typeless pointers?).
2768       V = B.CreatePointerCast(V, B.getInt8PtrTy());
2769       Dest = B.CreatePointerCast(Dest, B.getInt8PtrTy());
2770       Value *PtrDiff = B.CreatePtrDiff(B.getInt8Ty(), V, Dest);
2771       return B.CreateIntCast(PtrDiff, CI->getType(), false);
2772     }
2773 
2774     bool OptForSize = CI->getFunction()->hasOptSize() ||
2775                       llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
2776                                                   PGSOQueryType::IRPass);
2777     if (OptForSize)
2778       return nullptr;
2779 
2780     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
2781     if (!Len)
2782       return nullptr;
2783     Value *IncLen =
2784         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2785     B.CreateMemCpy(Dest, Align(1), CI->getArgOperand(2), Align(1), IncLen);
2786 
2787     // The sprintf result is the unincremented number of bytes in the string.
2788     return B.CreateIntCast(Len, CI->getType(), false);
2789   }
2790   return nullptr;
2791 }
2792 
2793 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilderBase &B) {
2794   Module *M = CI->getModule();
2795   Function *Callee = CI->getCalledFunction();
2796   FunctionType *FT = Callee->getFunctionType();
2797   if (Value *V = optimizeSPrintFString(CI, B)) {
2798     return V;
2799   }
2800 
2801   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2802   // point arguments.
2803   if (isLibFuncEmittable(M, TLI, LibFunc_siprintf) &&
2804       !callHasFloatingPointArgument(CI)) {
2805     FunctionCallee SIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_siprintf,
2806                                                    FT, Callee->getAttributes());
2807     CallInst *New = cast<CallInst>(CI->clone());
2808     New->setCalledFunction(SIPrintFFn);
2809     B.Insert(New);
2810     return New;
2811   }
2812 
2813   // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2814   // floating point arguments.
2815   if (isLibFuncEmittable(M, TLI, LibFunc_small_sprintf) &&
2816       !callHasFP128Argument(CI)) {
2817     auto SmallSPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_small_sprintf, FT,
2818                                              Callee->getAttributes());
2819     CallInst *New = cast<CallInst>(CI->clone());
2820     New->setCalledFunction(SmallSPrintFFn);
2821     B.Insert(New);
2822     return New;
2823   }
2824 
2825   annotateNonNullNoUndefBasedOnAccess(CI, {0, 1});
2826   return nullptr;
2827 }
2828 
2829 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI,
2830                                                  IRBuilderBase &B) {
2831   // Check for size
2832   ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2833   if (!Size)
2834     return nullptr;
2835 
2836   uint64_t N = Size->getZExtValue();
2837   // Check for a fixed format string.
2838   StringRef FormatStr;
2839   if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2840     return nullptr;
2841 
2842   // If we just have a format string (nothing else crazy) transform it.
2843   if (CI->arg_size() == 3) {
2844     // Make sure there's no % in the constant array.  We could try to handle
2845     // %% -> % in the future if we cared.
2846     if (FormatStr.contains('%'))
2847       return nullptr; // we found a format specifier, bail out.
2848 
2849     if (N == 0)
2850       return ConstantInt::get(CI->getType(), FormatStr.size());
2851     else if (N < FormatStr.size() + 1)
2852       return nullptr;
2853 
2854     // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
2855     // strlen(fmt)+1)
2856     copyFlags(
2857         *CI,
2858         B.CreateMemCpy(
2859             CI->getArgOperand(0), Align(1), CI->getArgOperand(2), Align(1),
2860             ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2861                              FormatStr.size() + 1))); // Copy the null byte.
2862     return ConstantInt::get(CI->getType(), FormatStr.size());
2863   }
2864 
2865   // The remaining optimizations require the format string to be "%s" or "%c"
2866   // and have an extra operand.
2867   if (FormatStr.size() == 2 && FormatStr[0] == '%' && CI->arg_size() == 4) {
2868 
2869     // Decode the second character of the format string.
2870     if (FormatStr[1] == 'c') {
2871       if (N == 0)
2872         return ConstantInt::get(CI->getType(), 1);
2873       else if (N == 1)
2874         return nullptr;
2875 
2876       // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2877       if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2878         return nullptr;
2879       Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2880       Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2881       B.CreateStore(V, Ptr);
2882       Ptr = B.CreateInBoundsGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2883       B.CreateStore(B.getInt8(0), Ptr);
2884 
2885       return ConstantInt::get(CI->getType(), 1);
2886     }
2887 
2888     if (FormatStr[1] == 's') {
2889       // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2890       StringRef Str;
2891       if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2892         return nullptr;
2893 
2894       if (N == 0)
2895         return ConstantInt::get(CI->getType(), Str.size());
2896       else if (N < Str.size() + 1)
2897         return nullptr;
2898 
2899       copyFlags(
2900           *CI, B.CreateMemCpy(CI->getArgOperand(0), Align(1),
2901                               CI->getArgOperand(3), Align(1),
2902                               ConstantInt::get(CI->getType(), Str.size() + 1)));
2903 
2904       // The snprintf result is the unincremented number of bytes in the string.
2905       return ConstantInt::get(CI->getType(), Str.size());
2906     }
2907   }
2908   return nullptr;
2909 }
2910 
2911 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilderBase &B) {
2912   if (Value *V = optimizeSnPrintFString(CI, B)) {
2913     return V;
2914   }
2915 
2916   if (isKnownNonZero(CI->getOperand(1), DL))
2917     annotateNonNullNoUndefBasedOnAccess(CI, 0);
2918   return nullptr;
2919 }
2920 
2921 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI,
2922                                                 IRBuilderBase &B) {
2923   optimizeErrorReporting(CI, B, 0);
2924 
2925   // All the optimizations depend on the format string.
2926   StringRef FormatStr;
2927   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2928     return nullptr;
2929 
2930   // Do not do any of the following transformations if the fprintf return
2931   // value is used, in general the fprintf return value is not compatible
2932   // with fwrite(), fputc() or fputs().
2933   if (!CI->use_empty())
2934     return nullptr;
2935 
2936   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2937   if (CI->arg_size() == 2) {
2938     // Could handle %% -> % if we cared.
2939     if (FormatStr.contains('%'))
2940       return nullptr; // We found a format specifier.
2941 
2942     return copyFlags(
2943         *CI, emitFWrite(CI->getArgOperand(1),
2944                         ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2945                                          FormatStr.size()),
2946                         CI->getArgOperand(0), B, DL, TLI));
2947   }
2948 
2949   // The remaining optimizations require the format string to be "%s" or "%c"
2950   // and have an extra operand.
2951   if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->arg_size() < 3)
2952     return nullptr;
2953 
2954   // Decode the second character of the format string.
2955   if (FormatStr[1] == 'c') {
2956     // fprintf(F, "%c", chr) --> fputc(chr, F)
2957     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2958       return nullptr;
2959     return copyFlags(
2960         *CI, emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
2961   }
2962 
2963   if (FormatStr[1] == 's') {
2964     // fprintf(F, "%s", str) --> fputs(str, F)
2965     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2966       return nullptr;
2967     return copyFlags(
2968         *CI, emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI));
2969   }
2970   return nullptr;
2971 }
2972 
2973 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilderBase &B) {
2974   Module *M = CI->getModule();
2975   Function *Callee = CI->getCalledFunction();
2976   FunctionType *FT = Callee->getFunctionType();
2977   if (Value *V = optimizeFPrintFString(CI, B)) {
2978     return V;
2979   }
2980 
2981   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2982   // floating point arguments.
2983   if (isLibFuncEmittable(M, TLI, LibFunc_fiprintf) &&
2984       !callHasFloatingPointArgument(CI)) {
2985     FunctionCallee FIPrintFFn = getOrInsertLibFunc(M, *TLI, LibFunc_fiprintf,
2986                                                    FT, Callee->getAttributes());
2987     CallInst *New = cast<CallInst>(CI->clone());
2988     New->setCalledFunction(FIPrintFFn);
2989     B.Insert(New);
2990     return New;
2991   }
2992 
2993   // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2994   // 128-bit floating point arguments.
2995   if (isLibFuncEmittable(M, TLI, LibFunc_small_fprintf) &&
2996       !callHasFP128Argument(CI)) {
2997     auto SmallFPrintFFn =
2998         getOrInsertLibFunc(M, *TLI, LibFunc_small_fprintf, FT,
2999                            Callee->getAttributes());
3000     CallInst *New = cast<CallInst>(CI->clone());
3001     New->setCalledFunction(SmallFPrintFFn);
3002     B.Insert(New);
3003     return New;
3004   }
3005 
3006   return nullptr;
3007 }
3008 
3009 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilderBase &B) {
3010   optimizeErrorReporting(CI, B, 3);
3011 
3012   // Get the element size and count.
3013   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
3014   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
3015   if (SizeC && CountC) {
3016     uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
3017 
3018     // If this is writing zero records, remove the call (it's a noop).
3019     if (Bytes == 0)
3020       return ConstantInt::get(CI->getType(), 0);
3021 
3022     // If this is writing one byte, turn it into fputc.
3023     // This optimisation is only valid, if the return value is unused.
3024     if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
3025       Value *Char = B.CreateLoad(B.getInt8Ty(),
3026                                  castToCStr(CI->getArgOperand(0), B), "char");
3027       Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
3028       return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
3029     }
3030   }
3031 
3032   return nullptr;
3033 }
3034 
3035 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilderBase &B) {
3036   optimizeErrorReporting(CI, B, 1);
3037 
3038   // Don't rewrite fputs to fwrite when optimising for size because fwrite
3039   // requires more arguments and thus extra MOVs are required.
3040   bool OptForSize = CI->getFunction()->hasOptSize() ||
3041                     llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI,
3042                                                 PGSOQueryType::IRPass);
3043   if (OptForSize)
3044     return nullptr;
3045 
3046   // We can't optimize if return value is used.
3047   if (!CI->use_empty())
3048     return nullptr;
3049 
3050   // fputs(s,F) --> fwrite(s,strlen(s),1,F)
3051   uint64_t Len = GetStringLength(CI->getArgOperand(0));
3052   if (!Len)
3053     return nullptr;
3054 
3055   // Known to have no uses (see above).
3056   return copyFlags(
3057       *CI,
3058       emitFWrite(CI->getArgOperand(0),
3059                  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
3060                  CI->getArgOperand(1), B, DL, TLI));
3061 }
3062 
3063 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilderBase &B) {
3064   annotateNonNullNoUndefBasedOnAccess(CI, 0);
3065   if (!CI->use_empty())
3066     return nullptr;
3067 
3068   // Check for a constant string.
3069   // puts("") -> putchar('\n')
3070   StringRef Str;
3071   if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
3072     return copyFlags(*CI, emitPutChar(B.getInt32('\n'), B, TLI));
3073 
3074   return nullptr;
3075 }
3076 
3077 Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) {
3078   // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
3079   return copyFlags(*CI, B.CreateMemMove(CI->getArgOperand(1), Align(1),
3080                                         CI->getArgOperand(0), Align(1),
3081                                         CI->getArgOperand(2)));
3082 }
3083 
3084 bool LibCallSimplifier::hasFloatVersion(const Module *M, StringRef FuncName) {
3085   SmallString<20> FloatFuncName = FuncName;
3086   FloatFuncName += 'f';
3087   return isLibFuncEmittable(M, TLI, FloatFuncName);
3088 }
3089 
3090 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
3091                                                       IRBuilderBase &Builder) {
3092   Module *M = CI->getModule();
3093   LibFunc Func;
3094   Function *Callee = CI->getCalledFunction();
3095   // Check for string/memory library functions.
3096   if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3097     // Make sure we never change the calling convention.
3098     assert(
3099         (ignoreCallingConv(Func) ||
3100          TargetLibraryInfoImpl::isCallingConvCCompatible(CI)) &&
3101         "Optimizing string/memory libcall would change the calling convention");
3102     switch (Func) {
3103     case LibFunc_strcat:
3104       return optimizeStrCat(CI, Builder);
3105     case LibFunc_strncat:
3106       return optimizeStrNCat(CI, Builder);
3107     case LibFunc_strchr:
3108       return optimizeStrChr(CI, Builder);
3109     case LibFunc_strrchr:
3110       return optimizeStrRChr(CI, Builder);
3111     case LibFunc_strcmp:
3112       return optimizeStrCmp(CI, Builder);
3113     case LibFunc_strncmp:
3114       return optimizeStrNCmp(CI, Builder);
3115     case LibFunc_strcpy:
3116       return optimizeStrCpy(CI, Builder);
3117     case LibFunc_stpcpy:
3118       return optimizeStpCpy(CI, Builder);
3119     case LibFunc_strncpy:
3120       return optimizeStrNCpy(CI, Builder);
3121     case LibFunc_strlen:
3122       return optimizeStrLen(CI, Builder);
3123     case LibFunc_strnlen:
3124       return optimizeStrNLen(CI, Builder);
3125     case LibFunc_strpbrk:
3126       return optimizeStrPBrk(CI, Builder);
3127     case LibFunc_strndup:
3128       return optimizeStrNDup(CI, Builder);
3129     case LibFunc_strtol:
3130     case LibFunc_strtod:
3131     case LibFunc_strtof:
3132     case LibFunc_strtoul:
3133     case LibFunc_strtoll:
3134     case LibFunc_strtold:
3135     case LibFunc_strtoull:
3136       return optimizeStrTo(CI, Builder);
3137     case LibFunc_strspn:
3138       return optimizeStrSpn(CI, Builder);
3139     case LibFunc_strcspn:
3140       return optimizeStrCSpn(CI, Builder);
3141     case LibFunc_strstr:
3142       return optimizeStrStr(CI, Builder);
3143     case LibFunc_memchr:
3144       return optimizeMemChr(CI, Builder);
3145     case LibFunc_memrchr:
3146       return optimizeMemRChr(CI, Builder);
3147     case LibFunc_bcmp:
3148       return optimizeBCmp(CI, Builder);
3149     case LibFunc_memcmp:
3150       return optimizeMemCmp(CI, Builder);
3151     case LibFunc_memcpy:
3152       return optimizeMemCpy(CI, Builder);
3153     case LibFunc_memccpy:
3154       return optimizeMemCCpy(CI, Builder);
3155     case LibFunc_mempcpy:
3156       return optimizeMemPCpy(CI, Builder);
3157     case LibFunc_memmove:
3158       return optimizeMemMove(CI, Builder);
3159     case LibFunc_memset:
3160       return optimizeMemSet(CI, Builder);
3161     case LibFunc_realloc:
3162       return optimizeRealloc(CI, Builder);
3163     case LibFunc_wcslen:
3164       return optimizeWcslen(CI, Builder);
3165     case LibFunc_bcopy:
3166       return optimizeBCopy(CI, Builder);
3167     default:
3168       break;
3169     }
3170   }
3171   return nullptr;
3172 }
3173 
3174 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
3175                                                        LibFunc Func,
3176                                                        IRBuilderBase &Builder) {
3177   const Module *M = CI->getModule();
3178 
3179   // Don't optimize calls that require strict floating point semantics.
3180   if (CI->isStrictFP())
3181     return nullptr;
3182 
3183   if (Value *V = optimizeTrigReflections(CI, Func, Builder))
3184     return V;
3185 
3186   switch (Func) {
3187   case LibFunc_sinpif:
3188   case LibFunc_sinpi:
3189   case LibFunc_cospif:
3190   case LibFunc_cospi:
3191     return optimizeSinCosPi(CI, Builder);
3192   case LibFunc_powf:
3193   case LibFunc_pow:
3194   case LibFunc_powl:
3195     return optimizePow(CI, Builder);
3196   case LibFunc_exp2l:
3197   case LibFunc_exp2:
3198   case LibFunc_exp2f:
3199     return optimizeExp2(CI, Builder);
3200   case LibFunc_fabsf:
3201   case LibFunc_fabs:
3202   case LibFunc_fabsl:
3203     return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
3204   case LibFunc_sqrtf:
3205   case LibFunc_sqrt:
3206   case LibFunc_sqrtl:
3207     return optimizeSqrt(CI, Builder);
3208   case LibFunc_logf:
3209   case LibFunc_log:
3210   case LibFunc_logl:
3211   case LibFunc_log10f:
3212   case LibFunc_log10:
3213   case LibFunc_log10l:
3214   case LibFunc_log1pf:
3215   case LibFunc_log1p:
3216   case LibFunc_log1pl:
3217   case LibFunc_log2f:
3218   case LibFunc_log2:
3219   case LibFunc_log2l:
3220   case LibFunc_logbf:
3221   case LibFunc_logb:
3222   case LibFunc_logbl:
3223     return optimizeLog(CI, Builder);
3224   case LibFunc_tan:
3225   case LibFunc_tanf:
3226   case LibFunc_tanl:
3227     return optimizeTan(CI, Builder);
3228   case LibFunc_ceil:
3229     return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
3230   case LibFunc_floor:
3231     return replaceUnaryCall(CI, Builder, Intrinsic::floor);
3232   case LibFunc_round:
3233     return replaceUnaryCall(CI, Builder, Intrinsic::round);
3234   case LibFunc_roundeven:
3235     return replaceUnaryCall(CI, Builder, Intrinsic::roundeven);
3236   case LibFunc_nearbyint:
3237     return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
3238   case LibFunc_rint:
3239     return replaceUnaryCall(CI, Builder, Intrinsic::rint);
3240   case LibFunc_trunc:
3241     return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
3242   case LibFunc_acos:
3243   case LibFunc_acosh:
3244   case LibFunc_asin:
3245   case LibFunc_asinh:
3246   case LibFunc_atan:
3247   case LibFunc_atanh:
3248   case LibFunc_cbrt:
3249   case LibFunc_cosh:
3250   case LibFunc_exp:
3251   case LibFunc_exp10:
3252   case LibFunc_expm1:
3253   case LibFunc_cos:
3254   case LibFunc_sin:
3255   case LibFunc_sinh:
3256   case LibFunc_tanh:
3257     if (UnsafeFPShrink && hasFloatVersion(M, CI->getCalledFunction()->getName()))
3258       return optimizeUnaryDoubleFP(CI, Builder, TLI, true);
3259     return nullptr;
3260   case LibFunc_copysign:
3261     if (hasFloatVersion(M, CI->getCalledFunction()->getName()))
3262       return optimizeBinaryDoubleFP(CI, Builder, TLI);
3263     return nullptr;
3264   case LibFunc_fminf:
3265   case LibFunc_fmin:
3266   case LibFunc_fminl:
3267   case LibFunc_fmaxf:
3268   case LibFunc_fmax:
3269   case LibFunc_fmaxl:
3270     return optimizeFMinFMax(CI, Builder);
3271   case LibFunc_cabs:
3272   case LibFunc_cabsf:
3273   case LibFunc_cabsl:
3274     return optimizeCAbs(CI, Builder);
3275   default:
3276     return nullptr;
3277   }
3278 }
3279 
3280 Value *LibCallSimplifier::optimizeCall(CallInst *CI, IRBuilderBase &Builder) {
3281   Module *M = CI->getModule();
3282   assert(!CI->isMustTailCall() && "These transforms aren't musttail safe.");
3283 
3284   // TODO: Split out the code below that operates on FP calls so that
3285   //       we can all non-FP calls with the StrictFP attribute to be
3286   //       optimized.
3287   if (CI->isNoBuiltin())
3288     return nullptr;
3289 
3290   LibFunc Func;
3291   Function *Callee = CI->getCalledFunction();
3292   bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
3293 
3294   SmallVector<OperandBundleDef, 2> OpBundles;
3295   CI->getOperandBundlesAsDefs(OpBundles);
3296 
3297   IRBuilderBase::OperandBundlesGuard Guard(Builder);
3298   Builder.setDefaultOperandBundles(OpBundles);
3299 
3300   // Command-line parameter overrides instruction attribute.
3301   // This can't be moved to optimizeFloatingPointLibCall() because it may be
3302   // used by the intrinsic optimizations.
3303   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
3304     UnsafeFPShrink = EnableUnsafeFPShrink;
3305   else if (isa<FPMathOperator>(CI) && CI->isFast())
3306     UnsafeFPShrink = true;
3307 
3308   // First, check for intrinsics.
3309   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
3310     if (!IsCallingConvC)
3311       return nullptr;
3312     // The FP intrinsics have corresponding constrained versions so we don't
3313     // need to check for the StrictFP attribute here.
3314     switch (II->getIntrinsicID()) {
3315     case Intrinsic::pow:
3316       return optimizePow(CI, Builder);
3317     case Intrinsic::exp2:
3318       return optimizeExp2(CI, Builder);
3319     case Intrinsic::log:
3320     case Intrinsic::log2:
3321     case Intrinsic::log10:
3322       return optimizeLog(CI, Builder);
3323     case Intrinsic::sqrt:
3324       return optimizeSqrt(CI, Builder);
3325     case Intrinsic::memset:
3326       return optimizeMemSet(CI, Builder);
3327     case Intrinsic::memcpy:
3328       return optimizeMemCpy(CI, Builder);
3329     case Intrinsic::memmove:
3330       return optimizeMemMove(CI, Builder);
3331     default:
3332       return nullptr;
3333     }
3334   }
3335 
3336   // Also try to simplify calls to fortified library functions.
3337   if (Value *SimplifiedFortifiedCI =
3338           FortifiedSimplifier.optimizeCall(CI, Builder)) {
3339     // Try to further simplify the result.
3340     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
3341     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
3342       // Ensure that SimplifiedCI's uses are complete, since some calls have
3343       // their uses analyzed.
3344       replaceAllUsesWith(CI, SimplifiedCI);
3345 
3346       // Set insertion point to SimplifiedCI to guarantee we reach all uses
3347       // we might replace later on.
3348       IRBuilderBase::InsertPointGuard Guard(Builder);
3349       Builder.SetInsertPoint(SimplifiedCI);
3350       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
3351         // If we were able to further simplify, remove the now redundant call.
3352         substituteInParent(SimplifiedCI, V);
3353         return V;
3354       }
3355     }
3356     return SimplifiedFortifiedCI;
3357   }
3358 
3359   // Then check for known library functions.
3360   if (TLI->getLibFunc(*Callee, Func) && isLibFuncEmittable(M, TLI, Func)) {
3361     // We never change the calling convention.
3362     if (!ignoreCallingConv(Func) && !IsCallingConvC)
3363       return nullptr;
3364     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
3365       return V;
3366     if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
3367       return V;
3368     switch (Func) {
3369     case LibFunc_ffs:
3370     case LibFunc_ffsl:
3371     case LibFunc_ffsll:
3372       return optimizeFFS(CI, Builder);
3373     case LibFunc_fls:
3374     case LibFunc_flsl:
3375     case LibFunc_flsll:
3376       return optimizeFls(CI, Builder);
3377     case LibFunc_abs:
3378     case LibFunc_labs:
3379     case LibFunc_llabs:
3380       return optimizeAbs(CI, Builder);
3381     case LibFunc_isdigit:
3382       return optimizeIsDigit(CI, Builder);
3383     case LibFunc_isascii:
3384       return optimizeIsAscii(CI, Builder);
3385     case LibFunc_toascii:
3386       return optimizeToAscii(CI, Builder);
3387     case LibFunc_atoi:
3388     case LibFunc_atol:
3389     case LibFunc_atoll:
3390       return optimizeAtoi(CI, Builder);
3391     case LibFunc_strtol:
3392     case LibFunc_strtoll:
3393       return optimizeStrtol(CI, Builder);
3394     case LibFunc_printf:
3395       return optimizePrintF(CI, Builder);
3396     case LibFunc_sprintf:
3397       return optimizeSPrintF(CI, Builder);
3398     case LibFunc_snprintf:
3399       return optimizeSnPrintF(CI, Builder);
3400     case LibFunc_fprintf:
3401       return optimizeFPrintF(CI, Builder);
3402     case LibFunc_fwrite:
3403       return optimizeFWrite(CI, Builder);
3404     case LibFunc_fputs:
3405       return optimizeFPuts(CI, Builder);
3406     case LibFunc_puts:
3407       return optimizePuts(CI, Builder);
3408     case LibFunc_perror:
3409       return optimizeErrorReporting(CI, Builder);
3410     case LibFunc_vfprintf:
3411     case LibFunc_fiprintf:
3412       return optimizeErrorReporting(CI, Builder, 0);
3413     default:
3414       return nullptr;
3415     }
3416   }
3417   return nullptr;
3418 }
3419 
3420 LibCallSimplifier::LibCallSimplifier(
3421     const DataLayout &DL, const TargetLibraryInfo *TLI,
3422     OptimizationRemarkEmitter &ORE,
3423     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
3424     function_ref<void(Instruction *, Value *)> Replacer,
3425     function_ref<void(Instruction *)> Eraser)
3426     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
3427       Replacer(Replacer), Eraser(Eraser) {}
3428 
3429 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
3430   // Indirect through the replacer used in this instance.
3431   Replacer(I, With);
3432 }
3433 
3434 void LibCallSimplifier::eraseFromParent(Instruction *I) {
3435   Eraser(I);
3436 }
3437 
3438 // TODO:
3439 //   Additional cases that we need to add to this file:
3440 //
3441 // cbrt:
3442 //   * cbrt(expN(X))  -> expN(x/3)
3443 //   * cbrt(sqrt(x))  -> pow(x,1/6)
3444 //   * cbrt(cbrt(x))  -> pow(x,1/9)
3445 //
3446 // exp, expf, expl:
3447 //   * exp(log(x))  -> x
3448 //
3449 // log, logf, logl:
3450 //   * log(exp(x))   -> x
3451 //   * log(exp(y))   -> y*log(e)
3452 //   * log(exp10(y)) -> y*log(10)
3453 //   * log(sqrt(x))  -> 0.5*log(x)
3454 //
3455 // pow, powf, powl:
3456 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
3457 //   * pow(pow(x,y),z)-> pow(x,y*z)
3458 //
3459 // signbit:
3460 //   * signbit(cnst) -> cnst'
3461 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
3462 //
3463 // sqrt, sqrtf, sqrtl:
3464 //   * sqrt(expN(x))  -> expN(x*0.5)
3465 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
3466 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
3467 //
3468 
3469 //===----------------------------------------------------------------------===//
3470 // Fortified Library Call Optimizations
3471 //===----------------------------------------------------------------------===//
3472 
3473 bool
3474 FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
3475                                                     unsigned ObjSizeOp,
3476                                                     Optional<unsigned> SizeOp,
3477                                                     Optional<unsigned> StrOp,
3478                                                     Optional<unsigned> FlagOp) {
3479   // If this function takes a flag argument, the implementation may use it to
3480   // perform extra checks. Don't fold into the non-checking variant.
3481   if (FlagOp) {
3482     ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
3483     if (!Flag || !Flag->isZero())
3484       return false;
3485   }
3486 
3487   if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
3488     return true;
3489 
3490   if (ConstantInt *ObjSizeCI =
3491           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
3492     if (ObjSizeCI->isMinusOne())
3493       return true;
3494     // If the object size wasn't -1 (unknown), bail out if we were asked to.
3495     if (OnlyLowerUnknownSize)
3496       return false;
3497     if (StrOp) {
3498       uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
3499       // If the length is 0 we don't know how long it is and so we can't
3500       // remove the check.
3501       if (Len)
3502         annotateDereferenceableBytes(CI, *StrOp, Len);
3503       else
3504         return false;
3505       return ObjSizeCI->getZExtValue() >= Len;
3506     }
3507 
3508     if (SizeOp) {
3509       if (ConstantInt *SizeCI =
3510               dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
3511         return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
3512     }
3513   }
3514   return false;
3515 }
3516 
3517 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
3518                                                      IRBuilderBase &B) {
3519   if (isFortifiedCallFoldable(CI, 3, 2)) {
3520     CallInst *NewCI =
3521         B.CreateMemCpy(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
3522                        Align(1), CI->getArgOperand(2));
3523     NewCI->setAttributes(CI->getAttributes());
3524     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3525     copyFlags(*CI, NewCI);
3526     return CI->getArgOperand(0);
3527   }
3528   return nullptr;
3529 }
3530 
3531 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
3532                                                       IRBuilderBase &B) {
3533   if (isFortifiedCallFoldable(CI, 3, 2)) {
3534     CallInst *NewCI =
3535         B.CreateMemMove(CI->getArgOperand(0), Align(1), CI->getArgOperand(1),
3536                         Align(1), CI->getArgOperand(2));
3537     NewCI->setAttributes(CI->getAttributes());
3538     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3539     copyFlags(*CI, NewCI);
3540     return CI->getArgOperand(0);
3541   }
3542   return nullptr;
3543 }
3544 
3545 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
3546                                                      IRBuilderBase &B) {
3547   if (isFortifiedCallFoldable(CI, 3, 2)) {
3548     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
3549     CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val,
3550                                      CI->getArgOperand(2), Align(1));
3551     NewCI->setAttributes(CI->getAttributes());
3552     NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3553     copyFlags(*CI, NewCI);
3554     return CI->getArgOperand(0);
3555   }
3556   return nullptr;
3557 }
3558 
3559 Value *FortifiedLibCallSimplifier::optimizeMemPCpyChk(CallInst *CI,
3560                                                       IRBuilderBase &B) {
3561   const DataLayout &DL = CI->getModule()->getDataLayout();
3562   if (isFortifiedCallFoldable(CI, 3, 2))
3563     if (Value *Call = emitMemPCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3564                                   CI->getArgOperand(2), B, DL, TLI)) {
3565       CallInst *NewCI = cast<CallInst>(Call);
3566       NewCI->setAttributes(CI->getAttributes());
3567       NewCI->removeRetAttrs(AttributeFuncs::typeIncompatible(NewCI->getType()));
3568       return copyFlags(*CI, NewCI);
3569     }
3570   return nullptr;
3571 }
3572 
3573 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
3574                                                       IRBuilderBase &B,
3575                                                       LibFunc Func) {
3576   const DataLayout &DL = CI->getModule()->getDataLayout();
3577   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
3578         *ObjSize = CI->getArgOperand(2);
3579 
3580   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
3581   if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
3582     Value *StrLen = emitStrLen(Src, B, DL, TLI);
3583     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
3584   }
3585 
3586   // If a) we don't have any length information, or b) we know this will
3587   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
3588   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
3589   // TODO: It might be nice to get a maximum length out of the possible
3590   // string lengths for varying.
3591   if (isFortifiedCallFoldable(CI, 2, None, 1)) {
3592     if (Func == LibFunc_strcpy_chk)
3593       return copyFlags(*CI, emitStrCpy(Dst, Src, B, TLI));
3594     else
3595       return copyFlags(*CI, emitStpCpy(Dst, Src, B, TLI));
3596   }
3597 
3598   if (OnlyLowerUnknownSize)
3599     return nullptr;
3600 
3601   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
3602   uint64_t Len = GetStringLength(Src);
3603   if (Len)
3604     annotateDereferenceableBytes(CI, 1, Len);
3605   else
3606     return nullptr;
3607 
3608   // FIXME: There is really no guarantee that sizeof(size_t) is equal to
3609   // sizeof(int*) for every target. So the assumption used here to derive the
3610   // SizeTBits based on the size of an integer pointer in address space zero
3611   // isn't always valid.
3612   Type *SizeTTy = DL.getIntPtrType(CI->getContext(), /*AddressSpace=*/0);
3613   Value *LenV = ConstantInt::get(SizeTTy, Len);
3614   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
3615   // If the function was an __stpcpy_chk, and we were able to fold it into
3616   // a __memcpy_chk, we still need to return the correct end pointer.
3617   if (Ret && Func == LibFunc_stpcpy_chk)
3618     return B.CreateInBoundsGEP(B.getInt8Ty(), Dst,
3619                                ConstantInt::get(SizeTTy, Len - 1));
3620   return copyFlags(*CI, cast<CallInst>(Ret));
3621 }
3622 
3623 Value *FortifiedLibCallSimplifier::optimizeStrLenChk(CallInst *CI,
3624                                                      IRBuilderBase &B) {
3625   if (isFortifiedCallFoldable(CI, 1, None, 0))
3626     return copyFlags(*CI, emitStrLen(CI->getArgOperand(0), B,
3627                                      CI->getModule()->getDataLayout(), TLI));
3628   return nullptr;
3629 }
3630 
3631 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
3632                                                        IRBuilderBase &B,
3633                                                        LibFunc Func) {
3634   if (isFortifiedCallFoldable(CI, 3, 2)) {
3635     if (Func == LibFunc_strncpy_chk)
3636       return copyFlags(*CI,
3637                        emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3638                                    CI->getArgOperand(2), B, TLI));
3639     else
3640       return copyFlags(*CI,
3641                        emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3642                                    CI->getArgOperand(2), B, TLI));
3643   }
3644 
3645   return nullptr;
3646 }
3647 
3648 Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
3649                                                       IRBuilderBase &B) {
3650   if (isFortifiedCallFoldable(CI, 4, 3))
3651     return copyFlags(
3652         *CI, emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3653                          CI->getArgOperand(2), CI->getArgOperand(3), B, TLI));
3654 
3655   return nullptr;
3656 }
3657 
3658 Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3659                                                        IRBuilderBase &B) {
3660   if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3661     SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 5));
3662     return copyFlags(*CI,
3663                      emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3664                                   CI->getArgOperand(4), VariadicArgs, B, TLI));
3665   }
3666 
3667   return nullptr;
3668 }
3669 
3670 Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3671                                                       IRBuilderBase &B) {
3672   if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3673     SmallVector<Value *, 8> VariadicArgs(drop_begin(CI->args(), 4));
3674     return copyFlags(*CI,
3675                      emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3676                                  VariadicArgs, B, TLI));
3677   }
3678 
3679   return nullptr;
3680 }
3681 
3682 Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3683                                                      IRBuilderBase &B) {
3684   if (isFortifiedCallFoldable(CI, 2))
3685     return copyFlags(
3686         *CI, emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI));
3687 
3688   return nullptr;
3689 }
3690 
3691 Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3692                                                    IRBuilderBase &B) {
3693   if (isFortifiedCallFoldable(CI, 3))
3694     return copyFlags(*CI,
3695                      emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3696                                  CI->getArgOperand(2), B, TLI));
3697 
3698   return nullptr;
3699 }
3700 
3701 Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3702                                                       IRBuilderBase &B) {
3703   if (isFortifiedCallFoldable(CI, 3))
3704     return copyFlags(*CI,
3705                      emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3706                                  CI->getArgOperand(2), B, TLI));
3707 
3708   return nullptr;
3709 }
3710 
3711 Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3712                                                       IRBuilderBase &B) {
3713   if (isFortifiedCallFoldable(CI, 3))
3714     return copyFlags(*CI,
3715                      emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3716                                  CI->getArgOperand(2), B, TLI));
3717 
3718   return nullptr;
3719 }
3720 
3721 Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3722                                                         IRBuilderBase &B) {
3723   if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3724     return copyFlags(
3725         *CI, emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3726                            CI->getArgOperand(4), CI->getArgOperand(5), B, TLI));
3727 
3728   return nullptr;
3729 }
3730 
3731 Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3732                                                        IRBuilderBase &B) {
3733   if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3734     return copyFlags(*CI,
3735                      emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3736                                   CI->getArgOperand(4), B, TLI));
3737 
3738   return nullptr;
3739 }
3740 
3741 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI,
3742                                                 IRBuilderBase &Builder) {
3743   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3744   // Some clang users checked for _chk libcall availability using:
3745   //   __has_builtin(__builtin___memcpy_chk)
3746   // When compiling with -fno-builtin, this is always true.
3747   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3748   // end up with fortified libcalls, which isn't acceptable in a freestanding
3749   // environment which only provides their non-fortified counterparts.
3750   //
3751   // Until we change clang and/or teach external users to check for availability
3752   // differently, disregard the "nobuiltin" attribute and TLI::has.
3753   //
3754   // PR23093.
3755 
3756   LibFunc Func;
3757   Function *Callee = CI->getCalledFunction();
3758   bool IsCallingConvC = TargetLibraryInfoImpl::isCallingConvCCompatible(CI);
3759 
3760   SmallVector<OperandBundleDef, 2> OpBundles;
3761   CI->getOperandBundlesAsDefs(OpBundles);
3762 
3763   IRBuilderBase::OperandBundlesGuard Guard(Builder);
3764   Builder.setDefaultOperandBundles(OpBundles);
3765 
3766   // First, check that this is a known library functions and that the prototype
3767   // is correct.
3768   if (!TLI->getLibFunc(*Callee, Func))
3769     return nullptr;
3770 
3771   // We never change the calling convention.
3772   if (!ignoreCallingConv(Func) && !IsCallingConvC)
3773     return nullptr;
3774 
3775   switch (Func) {
3776   case LibFunc_memcpy_chk:
3777     return optimizeMemCpyChk(CI, Builder);
3778   case LibFunc_mempcpy_chk:
3779     return optimizeMemPCpyChk(CI, Builder);
3780   case LibFunc_memmove_chk:
3781     return optimizeMemMoveChk(CI, Builder);
3782   case LibFunc_memset_chk:
3783     return optimizeMemSetChk(CI, Builder);
3784   case LibFunc_stpcpy_chk:
3785   case LibFunc_strcpy_chk:
3786     return optimizeStrpCpyChk(CI, Builder, Func);
3787   case LibFunc_strlen_chk:
3788     return optimizeStrLenChk(CI, Builder);
3789   case LibFunc_stpncpy_chk:
3790   case LibFunc_strncpy_chk:
3791     return optimizeStrpNCpyChk(CI, Builder, Func);
3792   case LibFunc_memccpy_chk:
3793     return optimizeMemCCpyChk(CI, Builder);
3794   case LibFunc_snprintf_chk:
3795     return optimizeSNPrintfChk(CI, Builder);
3796   case LibFunc_sprintf_chk:
3797     return optimizeSPrintfChk(CI, Builder);
3798   case LibFunc_strcat_chk:
3799     return optimizeStrCatChk(CI, Builder);
3800   case LibFunc_strlcat_chk:
3801     return optimizeStrLCat(CI, Builder);
3802   case LibFunc_strncat_chk:
3803     return optimizeStrNCatChk(CI, Builder);
3804   case LibFunc_strlcpy_chk:
3805     return optimizeStrLCpyChk(CI, Builder);
3806   case LibFunc_vsnprintf_chk:
3807     return optimizeVSNPrintfChk(CI, Builder);
3808   case LibFunc_vsprintf_chk:
3809     return optimizeVSPrintfChk(CI, Builder);
3810   default:
3811     break;
3812   }
3813   return nullptr;
3814 }
3815 
3816 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3817     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
3818     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
3819