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