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