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