1 //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is a utility pass used for testing the InstructionSimplify analysis.
11 // The analysis is applied to every instruction, and if it simplifies then the
12 // instruction is replaced by the simplification.  If you are looking for a pass
13 // that performs serious instruction folding, use the instcombine pass instead.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 
37 using namespace llvm;
38 using namespace PatternMatch;
39 
40 static cl::opt<bool>
41     ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42                    cl::desc("Treat error-reporting calls as cold"));
43 
44 static cl::opt<bool>
45     EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46                          cl::init(false),
47                          cl::desc("Enable unsafe double to float "
48                                   "shrinking for math lib calls"));
49 
50 
51 //===----------------------------------------------------------------------===//
52 // Helper Functions
53 //===----------------------------------------------------------------------===//
54 
55 static bool ignoreCallingConv(LibFunc::Func Func) {
56   return Func == LibFunc::abs || Func == LibFunc::labs ||
57          Func == LibFunc::llabs || Func == LibFunc::strlen;
58 }
59 
60 /// Return true if it only matters that the value is equal or not-equal to zero.
61 static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
62   for (User *U : V->users()) {
63     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
64       if (IC->isEquality())
65         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
66           if (C->isNullValue())
67             continue;
68     // Unknown instruction.
69     return false;
70   }
71   return true;
72 }
73 
74 /// Return true if it is only used in equality comparisons with With.
75 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
76   for (User *U : V->users()) {
77     if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
78       if (IC->isEquality() && IC->getOperand(1) == With)
79         continue;
80     // Unknown instruction.
81     return false;
82   }
83   return true;
84 }
85 
86 static bool callHasFloatingPointArgument(const CallInst *CI) {
87   return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
88     return OI->getType()->isFloatingPointTy();
89   });
90 }
91 
92 /// \brief Check whether the overloaded unary floating point function
93 /// corresponding to \a Ty is available.
94 static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
95                             LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
96                             LibFunc::Func LongDoubleFn) {
97   switch (Ty->getTypeID()) {
98   case Type::FloatTyID:
99     return TLI->has(FloatFn);
100   case Type::DoubleTyID:
101     return TLI->has(DoubleFn);
102   default:
103     return TLI->has(LongDoubleFn);
104   }
105 }
106 
107 /// \brief Returns whether \p F matches the signature expected for the
108 /// string/memory copying library function \p Func.
109 /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
110 /// Their fortified (_chk) counterparts are also accepted.
111 static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
112   const DataLayout &DL = F->getParent()->getDataLayout();
113   FunctionType *FT = F->getFunctionType();
114   LLVMContext &Context = F->getContext();
115   Type *PCharTy = Type::getInt8PtrTy(Context);
116   Type *SizeTTy = DL.getIntPtrType(Context);
117   unsigned NumParams = FT->getNumParams();
118 
119   // All string libfuncs return the same type as the first parameter.
120   if (FT->getReturnType() != FT->getParamType(0))
121     return false;
122 
123   switch (Func) {
124   default:
125     llvm_unreachable("Can't check signature for non-string-copy libfunc.");
126   case LibFunc::stpncpy_chk:
127   case LibFunc::strncpy_chk:
128     --NumParams; // fallthrough
129   case LibFunc::stpncpy:
130   case LibFunc::strncpy: {
131     if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
132         FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
133       return false;
134     break;
135   }
136   case LibFunc::strcpy_chk:
137   case LibFunc::stpcpy_chk:
138     --NumParams; // fallthrough
139   case LibFunc::stpcpy:
140   case LibFunc::strcpy: {
141     if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
142         FT->getParamType(0) != PCharTy)
143       return false;
144     break;
145   }
146   case LibFunc::memmove_chk:
147   case LibFunc::memcpy_chk:
148     --NumParams; // fallthrough
149   case LibFunc::memmove:
150   case LibFunc::memcpy: {
151     if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
152         !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
153       return false;
154     break;
155   }
156   case LibFunc::memset_chk:
157     --NumParams; // fallthrough
158   case LibFunc::memset: {
159     if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
160         !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
161       return false;
162     break;
163   }
164   }
165   // If this is a fortified libcall, the last parameter is a size_t.
166   if (NumParams == FT->getNumParams() - 1)
167     return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
168   return true;
169 }
170 
171 //===----------------------------------------------------------------------===//
172 // String and Memory Library Call Optimizations
173 //===----------------------------------------------------------------------===//
174 
175 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
176   Function *Callee = CI->getCalledFunction();
177   // Verify the "strcat" function prototype.
178   FunctionType *FT = Callee->getFunctionType();
179   if (FT->getNumParams() != 2||
180       FT->getReturnType() != B.getInt8PtrTy() ||
181       FT->getParamType(0) != FT->getReturnType() ||
182       FT->getParamType(1) != FT->getReturnType())
183     return nullptr;
184 
185   // Extract some information from the instruction
186   Value *Dst = CI->getArgOperand(0);
187   Value *Src = CI->getArgOperand(1);
188 
189   // See if we can get the length of the input string.
190   uint64_t Len = GetStringLength(Src);
191   if (Len == 0)
192     return nullptr;
193   --Len; // Unbias length.
194 
195   // Handle the simple, do-nothing case: strcat(x, "") -> x
196   if (Len == 0)
197     return Dst;
198 
199   return emitStrLenMemCpy(Src, Dst, Len, B);
200 }
201 
202 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
203                                            IRBuilder<> &B) {
204   // We need to find the end of the destination string.  That's where the
205   // memory is to be moved to. We just generate a call to strlen.
206   Value *DstLen = emitStrLen(Dst, B, DL, TLI);
207   if (!DstLen)
208     return nullptr;
209 
210   // Now that we have the destination's length, we must index into the
211   // destination's pointer to get the actual memcpy destination (end of
212   // the string .. we're concatenating).
213   Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
214 
215   // We have enough information to now generate the memcpy call to do the
216   // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
217   B.CreateMemCpy(CpyDst, Src,
218                  ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
219                  1);
220   return Dst;
221 }
222 
223 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
224   Function *Callee = CI->getCalledFunction();
225   // Verify the "strncat" function prototype.
226   FunctionType *FT = Callee->getFunctionType();
227   if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
228       FT->getParamType(0) != FT->getReturnType() ||
229       FT->getParamType(1) != FT->getReturnType() ||
230       !FT->getParamType(2)->isIntegerTy())
231     return nullptr;
232 
233   // Extract some information from the instruction.
234   Value *Dst = CI->getArgOperand(0);
235   Value *Src = CI->getArgOperand(1);
236   uint64_t Len;
237 
238   // We don't do anything if length is not constant.
239   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
240     Len = LengthArg->getZExtValue();
241   else
242     return nullptr;
243 
244   // See if we can get the length of the input string.
245   uint64_t SrcLen = GetStringLength(Src);
246   if (SrcLen == 0)
247     return nullptr;
248   --SrcLen; // Unbias length.
249 
250   // Handle the simple, do-nothing cases:
251   // strncat(x, "", c) -> x
252   // strncat(x,  c, 0) -> x
253   if (SrcLen == 0 || Len == 0)
254     return Dst;
255 
256   // We don't optimize this case.
257   if (Len < SrcLen)
258     return nullptr;
259 
260   // strncat(x, s, c) -> strcat(x, s)
261   // s is constant so the strcat can be optimized further.
262   return emitStrLenMemCpy(Src, Dst, SrcLen, B);
263 }
264 
265 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
266   Function *Callee = CI->getCalledFunction();
267   // Verify the "strchr" function prototype.
268   FunctionType *FT = Callee->getFunctionType();
269   if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
270       FT->getParamType(0) != FT->getReturnType() ||
271       !FT->getParamType(1)->isIntegerTy(32))
272     return nullptr;
273 
274   Value *SrcStr = CI->getArgOperand(0);
275 
276   // If the second operand is non-constant, see if we can compute the length
277   // of the input string and turn this into memchr.
278   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
279   if (!CharC) {
280     uint64_t Len = GetStringLength(SrcStr);
281     if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
282       return nullptr;
283 
284     return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
285                       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
286                       B, DL, TLI);
287   }
288 
289   // Otherwise, the character is a constant, see if the first argument is
290   // a string literal.  If so, we can constant fold.
291   StringRef Str;
292   if (!getConstantStringInfo(SrcStr, Str)) {
293     if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
294       return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
295                          "strchr");
296     return nullptr;
297   }
298 
299   // Compute the offset, make sure to handle the case when we're searching for
300   // zero (a weird way to spell strlen).
301   size_t I = (0xFF & CharC->getSExtValue()) == 0
302                  ? Str.size()
303                  : Str.find(CharC->getSExtValue());
304   if (I == StringRef::npos) // Didn't find the char.  strchr returns null.
305     return Constant::getNullValue(CI->getType());
306 
307   // strchr(s+n,c)  -> gep(s+n+i,c)
308   return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
309 }
310 
311 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
312   Function *Callee = CI->getCalledFunction();
313   // Verify the "strrchr" function prototype.
314   FunctionType *FT = Callee->getFunctionType();
315   if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
316       FT->getParamType(0) != FT->getReturnType() ||
317       !FT->getParamType(1)->isIntegerTy(32))
318     return nullptr;
319 
320   Value *SrcStr = CI->getArgOperand(0);
321   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
322 
323   // Cannot fold anything if we're not looking for a constant.
324   if (!CharC)
325     return nullptr;
326 
327   StringRef Str;
328   if (!getConstantStringInfo(SrcStr, Str)) {
329     // strrchr(s, 0) -> strchr(s, 0)
330     if (CharC->isZero())
331       return emitStrChr(SrcStr, '\0', B, TLI);
332     return nullptr;
333   }
334 
335   // Compute the offset.
336   size_t I = (0xFF & CharC->getSExtValue()) == 0
337                  ? Str.size()
338                  : Str.rfind(CharC->getSExtValue());
339   if (I == StringRef::npos) // Didn't find the char. Return null.
340     return Constant::getNullValue(CI->getType());
341 
342   // strrchr(s+n,c) -> gep(s+n+i,c)
343   return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
344 }
345 
346 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
347   Function *Callee = CI->getCalledFunction();
348   // Verify the "strcmp" function prototype.
349   FunctionType *FT = Callee->getFunctionType();
350   if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
351       FT->getParamType(0) != FT->getParamType(1) ||
352       FT->getParamType(0) != B.getInt8PtrTy())
353     return nullptr;
354 
355   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
356   if (Str1P == Str2P) // strcmp(x,x)  -> 0
357     return ConstantInt::get(CI->getType(), 0);
358 
359   StringRef Str1, Str2;
360   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
361   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
362 
363   // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
364   if (HasStr1 && HasStr2)
365     return ConstantInt::get(CI->getType(), Str1.compare(Str2));
366 
367   if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
368     return B.CreateNeg(
369         B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
370 
371   if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
372     return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
373 
374   // strcmp(P, "x") -> memcmp(P, "x", 2)
375   uint64_t Len1 = GetStringLength(Str1P);
376   uint64_t Len2 = GetStringLength(Str2P);
377   if (Len1 && Len2) {
378     return emitMemCmp(Str1P, Str2P,
379                       ConstantInt::get(DL.getIntPtrType(CI->getContext()),
380                                        std::min(Len1, Len2)),
381                       B, DL, TLI);
382   }
383 
384   return nullptr;
385 }
386 
387 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
388   Function *Callee = CI->getCalledFunction();
389   // Verify the "strncmp" function prototype.
390   FunctionType *FT = Callee->getFunctionType();
391   if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
392       FT->getParamType(0) != FT->getParamType(1) ||
393       FT->getParamType(0) != B.getInt8PtrTy() ||
394       !FT->getParamType(2)->isIntegerTy())
395     return nullptr;
396 
397   Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
398   if (Str1P == Str2P) // strncmp(x,x,n)  -> 0
399     return ConstantInt::get(CI->getType(), 0);
400 
401   // Get the length argument if it is constant.
402   uint64_t Length;
403   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
404     Length = LengthArg->getZExtValue();
405   else
406     return nullptr;
407 
408   if (Length == 0) // strncmp(x,y,0)   -> 0
409     return ConstantInt::get(CI->getType(), 0);
410 
411   if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
412     return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
413 
414   StringRef Str1, Str2;
415   bool HasStr1 = getConstantStringInfo(Str1P, Str1);
416   bool HasStr2 = getConstantStringInfo(Str2P, Str2);
417 
418   // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
419   if (HasStr1 && HasStr2) {
420     StringRef SubStr1 = Str1.substr(0, Length);
421     StringRef SubStr2 = Str2.substr(0, Length);
422     return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
423   }
424 
425   if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
426     return B.CreateNeg(
427         B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
428 
429   if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
430     return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
431 
432   return nullptr;
433 }
434 
435 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
436   Function *Callee = CI->getCalledFunction();
437 
438   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
439     return nullptr;
440 
441   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442   if (Dst == Src) // strcpy(x,x)  -> x
443     return Src;
444 
445   // See if we can get the length of the input string.
446   uint64_t Len = GetStringLength(Src);
447   if (Len == 0)
448     return nullptr;
449 
450   // We have enough information to now generate the memcpy call to do the
451   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
452   B.CreateMemCpy(Dst, Src,
453                  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
454   return Dst;
455 }
456 
457 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
458   Function *Callee = CI->getCalledFunction();
459   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
460     return nullptr;
461 
462   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
463   if (Dst == Src) { // stpcpy(x,x)  -> x+strlen(x)
464     Value *StrLen = emitStrLen(Src, B, DL, TLI);
465     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
466   }
467 
468   // See if we can get the length of the input string.
469   uint64_t Len = GetStringLength(Src);
470   if (Len == 0)
471     return nullptr;
472 
473   Type *PT = Callee->getFunctionType()->getParamType(0);
474   Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
475   Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
476                               ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
477 
478   // We have enough information to now generate the memcpy call to do the
479   // copy for us.  Make a memcpy to copy the nul byte with align = 1.
480   B.CreateMemCpy(Dst, Src, LenV, 1);
481   return DstEnd;
482 }
483 
484 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
485   Function *Callee = CI->getCalledFunction();
486   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
487     return nullptr;
488 
489   Value *Dst = CI->getArgOperand(0);
490   Value *Src = CI->getArgOperand(1);
491   Value *LenOp = CI->getArgOperand(2);
492 
493   // See if we can get the length of the input string.
494   uint64_t SrcLen = GetStringLength(Src);
495   if (SrcLen == 0)
496     return nullptr;
497   --SrcLen;
498 
499   if (SrcLen == 0) {
500     // strncpy(x, "", y) -> memset(x, '\0', y, 1)
501     B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
502     return Dst;
503   }
504 
505   uint64_t Len;
506   if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
507     Len = LengthArg->getZExtValue();
508   else
509     return nullptr;
510 
511   if (Len == 0)
512     return Dst; // strncpy(x, y, 0) -> x
513 
514   // Let strncpy handle the zero padding
515   if (Len > SrcLen + 1)
516     return nullptr;
517 
518   Type *PT = Callee->getFunctionType()->getParamType(0);
519   // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
520   B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
521 
522   return Dst;
523 }
524 
525 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
526   Function *Callee = CI->getCalledFunction();
527   FunctionType *FT = Callee->getFunctionType();
528   if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
529       !FT->getReturnType()->isIntegerTy())
530     return nullptr;
531 
532   Value *Src = CI->getArgOperand(0);
533 
534   // Constant folding: strlen("xyz") -> 3
535   if (uint64_t Len = GetStringLength(Src))
536     return ConstantInt::get(CI->getType(), Len - 1);
537 
538   // strlen(x?"foo":"bars") --> x ? 3 : 4
539   if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
540     uint64_t LenTrue = GetStringLength(SI->getTrueValue());
541     uint64_t LenFalse = GetStringLength(SI->getFalseValue());
542     if (LenTrue && LenFalse) {
543       Function *Caller = CI->getParent()->getParent();
544       emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
545                              SI->getDebugLoc(),
546                              "folded strlen(select) to select of constants");
547       return B.CreateSelect(SI->getCondition(),
548                             ConstantInt::get(CI->getType(), LenTrue - 1),
549                             ConstantInt::get(CI->getType(), LenFalse - 1));
550     }
551   }
552 
553   // strlen(x) != 0 --> *x != 0
554   // strlen(x) == 0 --> *x == 0
555   if (isOnlyUsedInZeroEqualityComparison(CI))
556     return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
557 
558   return nullptr;
559 }
560 
561 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
562   Function *Callee = CI->getCalledFunction();
563   FunctionType *FT = Callee->getFunctionType();
564   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
565       FT->getParamType(1) != FT->getParamType(0) ||
566       FT->getReturnType() != FT->getParamType(0))
567     return nullptr;
568 
569   StringRef S1, S2;
570   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
571   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
572 
573   // strpbrk(s, "") -> nullptr
574   // strpbrk("", s) -> nullptr
575   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
576     return Constant::getNullValue(CI->getType());
577 
578   // Constant folding.
579   if (HasS1 && HasS2) {
580     size_t I = S1.find_first_of(S2);
581     if (I == StringRef::npos) // No match.
582       return Constant::getNullValue(CI->getType());
583 
584     return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
585                        "strpbrk");
586   }
587 
588   // strpbrk(s, "a") -> strchr(s, 'a')
589   if (HasS2 && S2.size() == 1)
590     return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
591 
592   return nullptr;
593 }
594 
595 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
596   Function *Callee = CI->getCalledFunction();
597   FunctionType *FT = Callee->getFunctionType();
598   if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
599       !FT->getParamType(0)->isPointerTy() ||
600       !FT->getParamType(1)->isPointerTy())
601     return nullptr;
602 
603   Value *EndPtr = CI->getArgOperand(1);
604   if (isa<ConstantPointerNull>(EndPtr)) {
605     // With a null EndPtr, this function won't capture the main argument.
606     // It would be readonly too, except that it still may write to errno.
607     CI->addAttribute(1, Attribute::NoCapture);
608   }
609 
610   return nullptr;
611 }
612 
613 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
614   Function *Callee = CI->getCalledFunction();
615   FunctionType *FT = Callee->getFunctionType();
616   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
617       FT->getParamType(1) != FT->getParamType(0) ||
618       !FT->getReturnType()->isIntegerTy())
619     return nullptr;
620 
621   StringRef S1, S2;
622   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
623   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
624 
625   // strspn(s, "") -> 0
626   // strspn("", s) -> 0
627   if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
628     return Constant::getNullValue(CI->getType());
629 
630   // Constant folding.
631   if (HasS1 && HasS2) {
632     size_t Pos = S1.find_first_not_of(S2);
633     if (Pos == StringRef::npos)
634       Pos = S1.size();
635     return ConstantInt::get(CI->getType(), Pos);
636   }
637 
638   return nullptr;
639 }
640 
641 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
642   Function *Callee = CI->getCalledFunction();
643   FunctionType *FT = Callee->getFunctionType();
644   if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
645       FT->getParamType(1) != FT->getParamType(0) ||
646       !FT->getReturnType()->isIntegerTy())
647     return nullptr;
648 
649   StringRef S1, S2;
650   bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
651   bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
652 
653   // strcspn("", s) -> 0
654   if (HasS1 && S1.empty())
655     return Constant::getNullValue(CI->getType());
656 
657   // Constant folding.
658   if (HasS1 && HasS2) {
659     size_t Pos = S1.find_first_of(S2);
660     if (Pos == StringRef::npos)
661       Pos = S1.size();
662     return ConstantInt::get(CI->getType(), Pos);
663   }
664 
665   // strcspn(s, "") -> strlen(s)
666   if (HasS2 && S2.empty())
667     return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
668 
669   return nullptr;
670 }
671 
672 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
673   Function *Callee = CI->getCalledFunction();
674   FunctionType *FT = Callee->getFunctionType();
675   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
676       !FT->getParamType(1)->isPointerTy() ||
677       !FT->getReturnType()->isPointerTy())
678     return nullptr;
679 
680   // fold strstr(x, x) -> x.
681   if (CI->getArgOperand(0) == CI->getArgOperand(1))
682     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
683 
684   // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
685   if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
686     Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
687     if (!StrLen)
688       return nullptr;
689     Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
690                                  StrLen, B, DL, TLI);
691     if (!StrNCmp)
692       return nullptr;
693     for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
694       ICmpInst *Old = cast<ICmpInst>(*UI++);
695       Value *Cmp =
696           B.CreateICmp(Old->getPredicate(), StrNCmp,
697                        ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
698       replaceAllUsesWith(Old, Cmp);
699     }
700     return CI;
701   }
702 
703   // See if either input string is a constant string.
704   StringRef SearchStr, ToFindStr;
705   bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
706   bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
707 
708   // fold strstr(x, "") -> x.
709   if (HasStr2 && ToFindStr.empty())
710     return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
711 
712   // If both strings are known, constant fold it.
713   if (HasStr1 && HasStr2) {
714     size_t Offset = SearchStr.find(ToFindStr);
715 
716     if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
717       return Constant::getNullValue(CI->getType());
718 
719     // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
720     Value *Result = castToCStr(CI->getArgOperand(0), B);
721     Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
722     return B.CreateBitCast(Result, CI->getType());
723   }
724 
725   // fold strstr(x, "y") -> strchr(x, 'y').
726   if (HasStr2 && ToFindStr.size() == 1) {
727     Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
728     return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
729   }
730   return nullptr;
731 }
732 
733 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
734   Function *Callee = CI->getCalledFunction();
735   FunctionType *FT = Callee->getFunctionType();
736   if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
737       !FT->getParamType(1)->isIntegerTy(32) ||
738       !FT->getParamType(2)->isIntegerTy() ||
739       !FT->getReturnType()->isPointerTy())
740     return nullptr;
741 
742   Value *SrcStr = CI->getArgOperand(0);
743   ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
744   ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
745 
746   // memchr(x, y, 0) -> null
747   if (LenC && LenC->isNullValue())
748     return Constant::getNullValue(CI->getType());
749 
750   // From now on we need at least constant length and string.
751   StringRef Str;
752   if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
753     return nullptr;
754 
755   // Truncate the string to LenC. If Str is smaller than LenC we will still only
756   // scan the string, as reading past the end of it is undefined and we can just
757   // return null if we don't find the char.
758   Str = Str.substr(0, LenC->getZExtValue());
759 
760   // If the char is variable but the input str and length are not we can turn
761   // this memchr call into a simple bit field test. Of course this only works
762   // when the return value is only checked against null.
763   //
764   // It would be really nice to reuse switch lowering here but we can't change
765   // the CFG at this point.
766   //
767   // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
768   //   after bounds check.
769   if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
770     unsigned char Max =
771         *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
772                           reinterpret_cast<const unsigned char *>(Str.end()));
773 
774     // Make sure the bit field we're about to create fits in a register on the
775     // target.
776     // FIXME: On a 64 bit architecture this prevents us from using the
777     // interesting range of alpha ascii chars. We could do better by emitting
778     // two bitfields or shifting the range by 64 if no lower chars are used.
779     if (!DL.fitsInLegalInteger(Max + 1))
780       return nullptr;
781 
782     // For the bit field use a power-of-2 type with at least 8 bits to avoid
783     // creating unnecessary illegal types.
784     unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
785 
786     // Now build the bit field.
787     APInt Bitfield(Width, 0);
788     for (char C : Str)
789       Bitfield.setBit((unsigned char)C);
790     Value *BitfieldC = B.getInt(Bitfield);
791 
792     // First check that the bit field access is within bounds.
793     Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
794     Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
795                                  "memchr.bounds");
796 
797     // Create code that checks if the given bit is set in the field.
798     Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
799     Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
800 
801     // Finally merge both checks and cast to pointer type. The inttoptr
802     // implicitly zexts the i1 to intptr type.
803     return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
804   }
805 
806   // Check if all arguments are constants.  If so, we can constant fold.
807   if (!CharC)
808     return nullptr;
809 
810   // Compute the offset.
811   size_t I = Str.find(CharC->getSExtValue() & 0xFF);
812   if (I == StringRef::npos) // Didn't find the char.  memchr returns null.
813     return Constant::getNullValue(CI->getType());
814 
815   // memchr(s+n,c,l) -> gep(s+n+i,c)
816   return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
817 }
818 
819 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
820   Function *Callee = CI->getCalledFunction();
821   FunctionType *FT = Callee->getFunctionType();
822   if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
823       !FT->getParamType(1)->isPointerTy() ||
824       !FT->getReturnType()->isIntegerTy(32))
825     return nullptr;
826 
827   Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
828 
829   if (LHS == RHS) // memcmp(s,s,x) -> 0
830     return Constant::getNullValue(CI->getType());
831 
832   // Make sure we have a constant length.
833   ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
834   if (!LenC)
835     return nullptr;
836   uint64_t Len = LenC->getZExtValue();
837 
838   if (Len == 0) // memcmp(s1,s2,0) -> 0
839     return Constant::getNullValue(CI->getType());
840 
841   // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
842   if (Len == 1) {
843     Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
844                                CI->getType(), "lhsv");
845     Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
846                                CI->getType(), "rhsv");
847     return B.CreateSub(LHSV, RHSV, "chardiff");
848   }
849 
850   // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
851   if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
852 
853     IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
854     unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
855 
856     if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
857         getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
858 
859       Type *LHSPtrTy =
860           IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
861       Type *RHSPtrTy =
862           IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
863 
864       Value *LHSV =
865           B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
866       Value *RHSV =
867           B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
868 
869       return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
870     }
871   }
872 
873   // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
874   StringRef LHSStr, RHSStr;
875   if (getConstantStringInfo(LHS, LHSStr) &&
876       getConstantStringInfo(RHS, RHSStr)) {
877     // Make sure we're not reading out-of-bounds memory.
878     if (Len > LHSStr.size() || Len > RHSStr.size())
879       return nullptr;
880     // Fold the memcmp and normalize the result.  This way we get consistent
881     // results across multiple platforms.
882     uint64_t Ret = 0;
883     int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
884     if (Cmp < 0)
885       Ret = -1;
886     else if (Cmp > 0)
887       Ret = 1;
888     return ConstantInt::get(CI->getType(), Ret);
889   }
890 
891   return nullptr;
892 }
893 
894 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
895   Function *Callee = CI->getCalledFunction();
896 
897   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
898     return nullptr;
899 
900   // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
901   B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
902                  CI->getArgOperand(2), 1);
903   return CI->getArgOperand(0);
904 }
905 
906 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
907   Function *Callee = CI->getCalledFunction();
908 
909   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
910     return nullptr;
911 
912   // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
913   B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
914                   CI->getArgOperand(2), 1);
915   return CI->getArgOperand(0);
916 }
917 
918 // TODO: Does this belong in BuildLibCalls or should all of those similar
919 // functions be moved here?
920 static Value *emitCalloc(Value *Num, Value *Size, const AttributeSet &Attrs,
921                          IRBuilder<> &B, const TargetLibraryInfo &TLI) {
922   LibFunc::Func Func;
923   if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
924     return nullptr;
925 
926   Module *M = B.GetInsertBlock()->getModule();
927   const DataLayout &DL = M->getDataLayout();
928   IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
929   Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
930                                          PtrType, PtrType, nullptr);
931   CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
932 
933   if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
934     CI->setCallingConv(F->getCallingConv());
935 
936   return CI;
937 }
938 
939 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
940 static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
941                                const TargetLibraryInfo &TLI) {
942   // This has to be a memset of zeros (bzero).
943   auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
944   if (!FillValue || FillValue->getZExtValue() != 0)
945     return nullptr;
946 
947   // TODO: We should handle the case where the malloc has more than one use.
948   // This is necessary to optimize common patterns such as when the result of
949   // the malloc is checked against null or when a memset intrinsic is used in
950   // place of a memset library call.
951   auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
952   if (!Malloc || !Malloc->hasOneUse())
953     return nullptr;
954 
955   // Is the inner call really malloc()?
956   Function *InnerCallee = Malloc->getCalledFunction();
957   LibFunc::Func Func;
958   if (!TLI.getLibFunc(InnerCallee->getName(), Func) || !TLI.has(Func) ||
959       Func != LibFunc::malloc)
960     return nullptr;
961 
962   // Matching the name is not good enough. Make sure the parameter and return
963   // type match the standard library signature.
964   FunctionType *FT = InnerCallee->getFunctionType();
965   if (FT->getNumParams() != 1 || !FT->getParamType(0)->isIntegerTy())
966     return nullptr;
967 
968   auto *RetType = dyn_cast<PointerType>(FT->getReturnType());
969   if (!RetType || !RetType->getPointerElementType()->isIntegerTy(8))
970     return nullptr;
971 
972   // The memset must cover the same number of bytes that are malloc'd.
973   if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
974     return nullptr;
975 
976   // Replace the malloc with a calloc. We need the data layout to know what the
977   // actual size of a 'size_t' parameter is.
978   B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
979   const DataLayout &DL = Malloc->getModule()->getDataLayout();
980   IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
981   Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
982                              Malloc->getArgOperand(0), Malloc->getAttributes(),
983                              B, TLI);
984   if (!Calloc)
985     return nullptr;
986 
987   Malloc->replaceAllUsesWith(Calloc);
988   Malloc->eraseFromParent();
989 
990   return Calloc;
991 }
992 
993 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
994   Function *Callee = CI->getCalledFunction();
995 
996   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
997     return nullptr;
998 
999   if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
1000     return Calloc;
1001 
1002   // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1003   Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1004   B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1005   return CI->getArgOperand(0);
1006 }
1007 
1008 //===----------------------------------------------------------------------===//
1009 // Math Library Optimizations
1010 //===----------------------------------------------------------------------===//
1011 
1012 /// Return a variant of Val with float type.
1013 /// Currently this works in two cases: If Val is an FPExtension of a float
1014 /// value to something bigger, simply return the operand.
1015 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1016 /// loss of precision do so.
1017 static Value *valueHasFloatPrecision(Value *Val) {
1018   if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1019     Value *Op = Cast->getOperand(0);
1020     if (Op->getType()->isFloatTy())
1021       return Op;
1022   }
1023   if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1024     APFloat F = Const->getValueAPF();
1025     bool losesInfo;
1026     (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1027                     &losesInfo);
1028     if (!losesInfo)
1029       return ConstantFP::get(Const->getContext(), F);
1030   }
1031   return nullptr;
1032 }
1033 
1034 /// Any floating-point library function that we're trying to simplify will have
1035 /// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
1036 /// CheckDoubleTy indicates that 'fptype' must be 'double'.
1037 static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
1038                                           bool CheckDoubleTy) {
1039   FunctionType *FT = F->getFunctionType();
1040   if (FT->getNumParams() != NumParams)
1041     return false;
1042 
1043   // The return type must match what we're looking for.
1044   Type *RetTy = FT->getReturnType();
1045   if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
1046     return false;
1047 
1048   // Each parameter must match the return type, and therefore, match every other
1049   // parameter too.
1050   for (const Type *ParamTy : FT->params())
1051     if (ParamTy != RetTy)
1052       return false;
1053 
1054   return true;
1055 }
1056 
1057 /// Shrink double -> float for unary functions like 'floor'.
1058 static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1059                                     bool CheckRetType) {
1060   Function *Callee = CI->getCalledFunction();
1061   if (!matchesFPLibFunctionSignature(Callee, 1, true))
1062     return nullptr;
1063 
1064   if (CheckRetType) {
1065     // Check if all the uses for function like 'sin' are converted to float.
1066     for (User *U : CI->users()) {
1067       FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1068       if (!Cast || !Cast->getType()->isFloatTy())
1069         return nullptr;
1070     }
1071   }
1072 
1073   // If this is something like 'floor((double)floatval)', convert to floorf.
1074   Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1075   if (V == nullptr)
1076     return nullptr;
1077 
1078   // Propagate fast-math flags from the existing call to the new call.
1079   IRBuilder<>::FastMathFlagGuard Guard(B);
1080   B.setFastMathFlags(CI->getFastMathFlags());
1081 
1082   // floor((double)floatval) -> (double)floorf(floatval)
1083   if (Callee->isIntrinsic()) {
1084     Module *M = CI->getModule();
1085     Intrinsic::ID IID = Callee->getIntrinsicID();
1086     Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1087     V = B.CreateCall(F, V);
1088   } else {
1089     // The call is a library call rather than an intrinsic.
1090     V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1091   }
1092 
1093   return B.CreateFPExt(V, B.getDoubleTy());
1094 }
1095 
1096 /// Shrink double -> float for binary functions like 'fmin/fmax'.
1097 static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1098   Function *Callee = CI->getCalledFunction();
1099   if (!matchesFPLibFunctionSignature(Callee, 2, true))
1100     return nullptr;
1101 
1102   // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1103   // or fmin(1.0, (double)floatval), then we convert it to fminf.
1104   Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1105   if (V1 == nullptr)
1106     return nullptr;
1107   Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1108   if (V2 == nullptr)
1109     return nullptr;
1110 
1111   // Propagate fast-math flags from the existing call to the new call.
1112   IRBuilder<>::FastMathFlagGuard Guard(B);
1113   B.setFastMathFlags(CI->getFastMathFlags());
1114 
1115   // fmin((double)floatval1, (double)floatval2)
1116   //                      -> (double)fminf(floatval1, floatval2)
1117   // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
1118   Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1119                                    Callee->getAttributes());
1120   return B.CreateFPExt(V, B.getDoubleTy());
1121 }
1122 
1123 Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1124   Function *Callee = CI->getCalledFunction();
1125   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1126     return nullptr;
1127 
1128   Value *Ret = nullptr;
1129   StringRef Name = Callee->getName();
1130   if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
1131     Ret = optimizeUnaryDoubleFP(CI, B, true);
1132 
1133   // cos(-x) -> cos(x)
1134   Value *Op1 = CI->getArgOperand(0);
1135   if (BinaryOperator::isFNeg(Op1)) {
1136     BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1137     return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1138   }
1139   return Ret;
1140 }
1141 
1142 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1143   // Multiplications calculated using Addition Chains.
1144   // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1145 
1146   assert(Exp != 0 && "Incorrect exponent 0 not handled");
1147 
1148   if (InnerChain[Exp])
1149     return InnerChain[Exp];
1150 
1151   static const unsigned AddChain[33][2] = {
1152       {0, 0}, // Unused.
1153       {0, 0}, // Unused (base case = pow1).
1154       {1, 1}, // Unused (pre-computed).
1155       {1, 2},  {2, 2},   {2, 3},  {3, 3},   {2, 5},  {4, 4},
1156       {1, 8},  {5, 5},   {1, 10}, {6, 6},   {4, 9},  {7, 7},
1157       {3, 12}, {8, 8},   {8, 9},  {2, 16},  {1, 18}, {10, 10},
1158       {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1159       {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1160   };
1161 
1162   InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1163                                  getPow(InnerChain, AddChain[Exp][1], B));
1164   return InnerChain[Exp];
1165 }
1166 
1167 Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1168   Function *Callee = CI->getCalledFunction();
1169   if (!matchesFPLibFunctionSignature(Callee, 2, false))
1170     return nullptr;
1171 
1172   Value *Ret = nullptr;
1173   StringRef Name = Callee->getName();
1174   if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
1175     Ret = optimizeUnaryDoubleFP(CI, B, true);
1176 
1177   Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1178   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1179     // pow(1.0, x) -> 1.0
1180     if (Op1C->isExactlyValue(1.0))
1181       return Op1C;
1182     // pow(2.0, x) -> exp2(x)
1183     if (Op1C->isExactlyValue(2.0) &&
1184         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1185                         LibFunc::exp2l))
1186       return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1187                                   Callee->getAttributes());
1188     // pow(10.0, x) -> exp10(x)
1189     if (Op1C->isExactlyValue(10.0) &&
1190         hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1191                         LibFunc::exp10l))
1192       return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1193                                   Callee->getAttributes());
1194   }
1195 
1196   // pow(exp(x), y) -> exp(x * y)
1197   // pow(exp2(x), y) -> exp2(x * y)
1198   // We enable these only with fast-math. Besides rounding differences, the
1199   // transformation changes overflow and underflow behavior quite dramatically.
1200   // Example: x = 1000, y = 0.001.
1201   // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1202   auto *OpC = dyn_cast<CallInst>(Op1);
1203   if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1204     LibFunc::Func Func;
1205     Function *OpCCallee = OpC->getCalledFunction();
1206     if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1207         TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
1208       IRBuilder<>::FastMathFlagGuard Guard(B);
1209       B.setFastMathFlags(CI->getFastMathFlags());
1210       Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
1211       return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
1212                                   OpCCallee->getAttributes());
1213     }
1214   }
1215 
1216   ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1217   if (!Op2C)
1218     return Ret;
1219 
1220   if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1221     return ConstantFP::get(CI->getType(), 1.0);
1222 
1223   if (Op2C->isExactlyValue(0.5) &&
1224       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1225                       LibFunc::sqrtl) &&
1226       hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1227                       LibFunc::fabsl)) {
1228 
1229     // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1230     if (CI->hasUnsafeAlgebra()) {
1231       IRBuilder<>::FastMathFlagGuard Guard(B);
1232       B.setFastMathFlags(CI->getFastMathFlags());
1233       return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1234                                   Callee->getAttributes());
1235     }
1236 
1237     // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1238     // This is faster than calling pow, and still handles negative zero
1239     // and negative infinity correctly.
1240     // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1241     Value *Inf = ConstantFP::getInfinity(CI->getType());
1242     Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1243     Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1244     Value *FAbs =
1245         emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1246     Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1247     Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1248     return Sel;
1249   }
1250 
1251   if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1252     return Op1;
1253   if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1254     return B.CreateFMul(Op1, Op1, "pow2");
1255   if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1256     return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1257 
1258   // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
1259   if (CI->hasUnsafeAlgebra()) {
1260     APFloat V = abs(Op2C->getValueAPF());
1261     // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1262     // This transformation applies to integer exponents only.
1263     if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1264         !V.isInteger())
1265       return nullptr;
1266 
1267     // We will memoize intermediate products of the Addition Chain.
1268     Value *InnerChain[33] = {nullptr};
1269     InnerChain[1] = Op1;
1270     InnerChain[2] = B.CreateFMul(Op1, Op1);
1271 
1272     // We cannot readily convert a non-double type (like float) to a double.
1273     // So we first convert V to something which could be converted to double.
1274     bool ignored;
1275     V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
1276 
1277     // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
1278     Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1279     // For negative exponents simply compute the reciprocal.
1280     if (Op2C->isNegative())
1281       FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1282     return FMul;
1283   }
1284 
1285   return nullptr;
1286 }
1287 
1288 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1289   Function *Callee = CI->getCalledFunction();
1290   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1291     return nullptr;
1292 
1293   Value *Ret = nullptr;
1294   StringRef Name = Callee->getName();
1295   if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1296     Ret = optimizeUnaryDoubleFP(CI, B, true);
1297 
1298   Value *Op = CI->getArgOperand(0);
1299   // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1300   // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1301   LibFunc::Func LdExp = LibFunc::ldexpl;
1302   if (Op->getType()->isFloatTy())
1303     LdExp = LibFunc::ldexpf;
1304   else if (Op->getType()->isDoubleTy())
1305     LdExp = LibFunc::ldexp;
1306 
1307   if (TLI->has(LdExp)) {
1308     Value *LdExpArg = nullptr;
1309     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1310       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1311         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1312     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1313       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1314         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1315     }
1316 
1317     if (LdExpArg) {
1318       Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1319       if (!Op->getType()->isFloatTy())
1320         One = ConstantExpr::getFPExtend(One, Op->getType());
1321 
1322       Module *M = CI->getModule();
1323       Value *NewCallee =
1324           M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1325                                  Op->getType(), B.getInt32Ty(), nullptr);
1326       CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1327       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1328         CI->setCallingConv(F->getCallingConv());
1329 
1330       return CI;
1331     }
1332   }
1333   return Ret;
1334 }
1335 
1336 Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1337   Function *Callee = CI->getCalledFunction();
1338   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1339     return nullptr;
1340 
1341   Value *Ret = nullptr;
1342   StringRef Name = Callee->getName();
1343   if (Name == "fabs" && hasFloatVersion(Name))
1344     Ret = optimizeUnaryDoubleFP(CI, B, false);
1345 
1346   Value *Op = CI->getArgOperand(0);
1347   if (Instruction *I = dyn_cast<Instruction>(Op)) {
1348     // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1349     if (I->getOpcode() == Instruction::FMul)
1350       if (I->getOperand(0) == I->getOperand(1))
1351         return Op;
1352   }
1353   return Ret;
1354 }
1355 
1356 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1357   Function *Callee = CI->getCalledFunction();
1358   if (!matchesFPLibFunctionSignature(Callee, 2, false))
1359     return nullptr;
1360 
1361   // If we can shrink the call to a float function rather than a double
1362   // function, do that first.
1363   StringRef Name = Callee->getName();
1364   if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1365     if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1366       return Ret;
1367 
1368   IRBuilder<>::FastMathFlagGuard Guard(B);
1369   FastMathFlags FMF;
1370   if (CI->hasUnsafeAlgebra()) {
1371     // Unsafe algebra sets all fast-math-flags to true.
1372     FMF.setUnsafeAlgebra();
1373   } else {
1374     // At a minimum, no-nans-fp-math must be true.
1375     if (!CI->hasNoNaNs())
1376       return nullptr;
1377     // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1378     // "Ideally, fmax would be sensitive to the sign of zero, for example
1379     // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1380     // might be impractical."
1381     FMF.setNoSignedZeros();
1382     FMF.setNoNaNs();
1383   }
1384   B.setFastMathFlags(FMF);
1385 
1386   // We have a relaxed floating-point environment. We can ignore NaN-handling
1387   // and transform to a compare and select. We do not have to consider errno or
1388   // exceptions, because fmin/fmax do not have those.
1389   Value *Op0 = CI->getArgOperand(0);
1390   Value *Op1 = CI->getArgOperand(1);
1391   Value *Cmp = Callee->getName().startswith("fmin") ?
1392     B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1393   return B.CreateSelect(Cmp, Op0, Op1);
1394 }
1395 
1396 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1397   Function *Callee = CI->getCalledFunction();
1398   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1399     return nullptr;
1400 
1401   Value *Ret = nullptr;
1402   StringRef Name = Callee->getName();
1403   if (UnsafeFPShrink && hasFloatVersion(Name))
1404     Ret = optimizeUnaryDoubleFP(CI, B, true);
1405 
1406   if (!CI->hasUnsafeAlgebra())
1407     return Ret;
1408   Value *Op1 = CI->getArgOperand(0);
1409   auto *OpC = dyn_cast<CallInst>(Op1);
1410 
1411   // The earlier call must also be unsafe in order to do these transforms.
1412   if (!OpC || !OpC->hasUnsafeAlgebra())
1413     return Ret;
1414 
1415   // log(pow(x,y)) -> y*log(x)
1416   // This is only applicable to log, log2, log10.
1417   if (Name != "log" && Name != "log2" && Name != "log10")
1418     return Ret;
1419 
1420   IRBuilder<>::FastMathFlagGuard Guard(B);
1421   FastMathFlags FMF;
1422   FMF.setUnsafeAlgebra();
1423   B.setFastMathFlags(FMF);
1424 
1425   LibFunc::Func Func;
1426   Function *F = OpC->getCalledFunction();
1427   if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1428       Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
1429     return B.CreateFMul(OpC->getArgOperand(1),
1430       emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1431                            Callee->getAttributes()), "mul");
1432 
1433   // log(exp2(y)) -> y*log(2)
1434   if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1435       TLI->has(Func) && Func == LibFunc::exp2)
1436     return B.CreateFMul(
1437         OpC->getArgOperand(0),
1438         emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
1439                              Callee->getName(), B, Callee->getAttributes()),
1440         "logmul");
1441   return Ret;
1442 }
1443 
1444 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1445   Function *Callee = CI->getCalledFunction();
1446   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1447     return nullptr;
1448 
1449   Value *Ret = nullptr;
1450   if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1451                                    Callee->getIntrinsicID() == Intrinsic::sqrt))
1452     Ret = optimizeUnaryDoubleFP(CI, B, true);
1453 
1454   if (!CI->hasUnsafeAlgebra())
1455     return Ret;
1456 
1457   Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1458   if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1459     return Ret;
1460 
1461   // We're looking for a repeated factor in a multiplication tree,
1462   // so we can do this fold: sqrt(x * x) -> fabs(x);
1463   // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1464   Value *Op0 = I->getOperand(0);
1465   Value *Op1 = I->getOperand(1);
1466   Value *RepeatOp = nullptr;
1467   Value *OtherOp = nullptr;
1468   if (Op0 == Op1) {
1469     // Simple match: the operands of the multiply are identical.
1470     RepeatOp = Op0;
1471   } else {
1472     // Look for a more complicated pattern: one of the operands is itself
1473     // a multiply, so search for a common factor in that multiply.
1474     // Note: We don't bother looking any deeper than this first level or for
1475     // variations of this pattern because instcombine's visitFMUL and/or the
1476     // reassociation pass should give us this form.
1477     Value *OtherMul0, *OtherMul1;
1478     if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1479       // Pattern: sqrt((x * y) * z)
1480       if (OtherMul0 == OtherMul1 &&
1481           cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
1482         // Matched: sqrt((x * x) * z)
1483         RepeatOp = OtherMul0;
1484         OtherOp = Op1;
1485       }
1486     }
1487   }
1488   if (!RepeatOp)
1489     return Ret;
1490 
1491   // Fast math flags for any created instructions should match the sqrt
1492   // and multiply.
1493   IRBuilder<>::FastMathFlagGuard Guard(B);
1494   B.setFastMathFlags(I->getFastMathFlags());
1495 
1496   // If we found a repeated factor, hoist it out of the square root and
1497   // replace it with the fabs of that factor.
1498   Module *M = Callee->getParent();
1499   Type *ArgType = I->getType();
1500   Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1501   Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1502   if (OtherOp) {
1503     // If we found a non-repeated factor, we still need to get its square
1504     // root. We then multiply that by the value that was simplified out
1505     // of the square root calculation.
1506     Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1507     Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1508     return B.CreateFMul(FabsCall, SqrtCall);
1509   }
1510   return FabsCall;
1511 }
1512 
1513 // TODO: Generalize to handle any trig function and its inverse.
1514 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1515   Function *Callee = CI->getCalledFunction();
1516   if (!matchesFPLibFunctionSignature(Callee, 1, false))
1517     return nullptr;
1518 
1519   Value *Ret = nullptr;
1520   StringRef Name = Callee->getName();
1521   if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1522     Ret = optimizeUnaryDoubleFP(CI, B, true);
1523 
1524   Value *Op1 = CI->getArgOperand(0);
1525   auto *OpC = dyn_cast<CallInst>(Op1);
1526   if (!OpC)
1527     return Ret;
1528 
1529   // Both calls must allow unsafe optimizations in order to remove them.
1530   if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1531     return Ret;
1532 
1533   // tan(atan(x)) -> x
1534   // tanf(atanf(x)) -> x
1535   // tanl(atanl(x)) -> x
1536   LibFunc::Func Func;
1537   Function *F = OpC->getCalledFunction();
1538   if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1539       ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1540        (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1541        (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1542     Ret = OpC->getArgOperand(0);
1543   return Ret;
1544 }
1545 
1546 static bool isTrigLibCall(CallInst *CI) {
1547   Function *Callee = CI->getCalledFunction();
1548   FunctionType *FT = Callee->getFunctionType();
1549 
1550   // We can only hope to do anything useful if we can ignore things like errno
1551   // and floating-point exceptions.
1552   bool AttributesSafe =
1553   CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1554 
1555   // Other than that we need float(float) or double(double)
1556   return AttributesSafe && FT->getNumParams() == 1 &&
1557   FT->getReturnType() == FT->getParamType(0) &&
1558   (FT->getParamType(0)->isFloatTy() ||
1559    FT->getParamType(0)->isDoubleTy());
1560 }
1561 
1562 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1563                              bool UseFloat, Value *&Sin, Value *&Cos,
1564                              Value *&SinCos) {
1565   Type *ArgTy = Arg->getType();
1566   Type *ResTy;
1567   StringRef Name;
1568 
1569   Triple T(OrigCallee->getParent()->getTargetTriple());
1570   if (UseFloat) {
1571     Name = "__sincospif_stret";
1572 
1573     assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1574     // x86_64 can't use {float, float} since that would be returned in both
1575     // xmm0 and xmm1, which isn't what a real struct would do.
1576     ResTy = T.getArch() == Triple::x86_64
1577     ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1578     : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1579   } else {
1580     Name = "__sincospi_stret";
1581     ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1582   }
1583 
1584   Module *M = OrigCallee->getParent();
1585   Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1586                                          ResTy, ArgTy, nullptr);
1587 
1588   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1589     // If the argument is an instruction, it must dominate all uses so put our
1590     // sincos call there.
1591     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1592   } else {
1593     // Otherwise (e.g. for a constant) the beginning of the function is as
1594     // good a place as any.
1595     BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1596     B.SetInsertPoint(&EntryBB, EntryBB.begin());
1597   }
1598 
1599   SinCos = B.CreateCall(Callee, Arg, "sincospi");
1600 
1601   if (SinCos->getType()->isStructTy()) {
1602     Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1603     Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1604   } else {
1605     Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1606                                  "sinpi");
1607     Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1608                                  "cospi");
1609   }
1610 }
1611 
1612 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1613   // Make sure the prototype is as expected, otherwise the rest of the
1614   // function is probably invalid and likely to abort.
1615   if (!isTrigLibCall(CI))
1616     return nullptr;
1617 
1618   Value *Arg = CI->getArgOperand(0);
1619   SmallVector<CallInst *, 1> SinCalls;
1620   SmallVector<CallInst *, 1> CosCalls;
1621   SmallVector<CallInst *, 1> SinCosCalls;
1622 
1623   bool IsFloat = Arg->getType()->isFloatTy();
1624 
1625   // Look for all compatible sinpi, cospi and sincospi calls with the same
1626   // argument. If there are enough (in some sense) we can make the
1627   // substitution.
1628   Function *F = CI->getFunction();
1629   for (User *U : Arg->users())
1630     classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1631 
1632   // It's only worthwhile if both sinpi and cospi are actually used.
1633   if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1634     return nullptr;
1635 
1636   Value *Sin, *Cos, *SinCos;
1637   insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1638 
1639   replaceTrigInsts(SinCalls, Sin);
1640   replaceTrigInsts(CosCalls, Cos);
1641   replaceTrigInsts(SinCosCalls, SinCos);
1642 
1643   return nullptr;
1644 }
1645 
1646 void LibCallSimplifier::classifyArgUse(
1647     Value *Val, Function *F, bool IsFloat,
1648     SmallVectorImpl<CallInst *> &SinCalls,
1649     SmallVectorImpl<CallInst *> &CosCalls,
1650     SmallVectorImpl<CallInst *> &SinCosCalls) {
1651   CallInst *CI = dyn_cast<CallInst>(Val);
1652 
1653   if (!CI)
1654     return;
1655 
1656   // Don't consider calls in other functions.
1657   if (CI->getFunction() != F)
1658     return;
1659 
1660   Function *Callee = CI->getCalledFunction();
1661   LibFunc::Func Func;
1662   if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1663       !isTrigLibCall(CI))
1664     return;
1665 
1666   if (IsFloat) {
1667     if (Func == LibFunc::sinpif)
1668       SinCalls.push_back(CI);
1669     else if (Func == LibFunc::cospif)
1670       CosCalls.push_back(CI);
1671     else if (Func == LibFunc::sincospif_stret)
1672       SinCosCalls.push_back(CI);
1673   } else {
1674     if (Func == LibFunc::sinpi)
1675       SinCalls.push_back(CI);
1676     else if (Func == LibFunc::cospi)
1677       CosCalls.push_back(CI);
1678     else if (Func == LibFunc::sincospi_stret)
1679       SinCosCalls.push_back(CI);
1680   }
1681 }
1682 
1683 void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1684                                          Value *Res) {
1685   for (CallInst *C : Calls)
1686     replaceAllUsesWith(C, Res);
1687 }
1688 
1689 //===----------------------------------------------------------------------===//
1690 // Integer Library Call Optimizations
1691 //===----------------------------------------------------------------------===//
1692 
1693 static bool checkIntUnaryReturnAndParam(Function *Callee) {
1694   FunctionType *FT = Callee->getFunctionType();
1695   return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1696     FT->getParamType(0)->isIntegerTy();
1697 }
1698 
1699 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1700   Function *Callee = CI->getCalledFunction();
1701   if (!checkIntUnaryReturnAndParam(Callee))
1702     return nullptr;
1703   Value *Op = CI->getArgOperand(0);
1704 
1705   // Constant fold.
1706   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1707     if (CI->isZero()) // ffs(0) -> 0.
1708       return B.getInt32(0);
1709     // ffs(c) -> cttz(c)+1
1710     return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1711   }
1712 
1713   // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1714   Type *ArgType = Op->getType();
1715   Value *F =
1716       Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1717   Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1718   V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1719   V = B.CreateIntCast(V, B.getInt32Ty(), false);
1720 
1721   Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1722   return B.CreateSelect(Cond, V, B.getInt32(0));
1723 }
1724 
1725 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1726   Function *Callee = CI->getCalledFunction();
1727   FunctionType *FT = Callee->getFunctionType();
1728   // We require integer(integer) where the types agree.
1729   if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1730       FT->getParamType(0) != FT->getReturnType())
1731     return nullptr;
1732 
1733   // abs(x) -> x >s -1 ? x : -x
1734   Value *Op = CI->getArgOperand(0);
1735   Value *Pos =
1736       B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1737   Value *Neg = B.CreateNeg(Op, "neg");
1738   return B.CreateSelect(Pos, Op, Neg);
1739 }
1740 
1741 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1742   if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1743     return nullptr;
1744 
1745   // isdigit(c) -> (c-'0') <u 10
1746   Value *Op = CI->getArgOperand(0);
1747   Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1748   Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1749   return B.CreateZExt(Op, CI->getType());
1750 }
1751 
1752 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1753   if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1754     return nullptr;
1755 
1756   // isascii(c) -> c <u 128
1757   Value *Op = CI->getArgOperand(0);
1758   Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1759   return B.CreateZExt(Op, CI->getType());
1760 }
1761 
1762 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1763   if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
1764     return nullptr;
1765 
1766   // toascii(c) -> c & 0x7f
1767   return B.CreateAnd(CI->getArgOperand(0),
1768                      ConstantInt::get(CI->getType(), 0x7F));
1769 }
1770 
1771 //===----------------------------------------------------------------------===//
1772 // Formatting and IO Library Call Optimizations
1773 //===----------------------------------------------------------------------===//
1774 
1775 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1776 
1777 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1778                                                  int StreamArg) {
1779   // Error reporting calls should be cold, mark them as such.
1780   // This applies even to non-builtin calls: it is only a hint and applies to
1781   // functions that the frontend might not understand as builtins.
1782 
1783   // This heuristic was suggested in:
1784   // Improving Static Branch Prediction in a Compiler
1785   // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1786   // Proceedings of PACT'98, Oct. 1998, IEEE
1787   Function *Callee = CI->getCalledFunction();
1788 
1789   if (!CI->hasFnAttr(Attribute::Cold) &&
1790       isReportingError(Callee, CI, StreamArg)) {
1791     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1792   }
1793 
1794   return nullptr;
1795 }
1796 
1797 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1798   if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
1799     return false;
1800 
1801   if (StreamArg < 0)
1802     return true;
1803 
1804   // These functions might be considered cold, but only if their stream
1805   // argument is stderr.
1806 
1807   if (StreamArg >= (int)CI->getNumArgOperands())
1808     return false;
1809   LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1810   if (!LI)
1811     return false;
1812   GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1813   if (!GV || !GV->isDeclaration())
1814     return false;
1815   return GV->getName() == "stderr";
1816 }
1817 
1818 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1819   // Check for a fixed format string.
1820   StringRef FormatStr;
1821   if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1822     return nullptr;
1823 
1824   // Empty format string -> noop.
1825   if (FormatStr.empty()) // Tolerate printf's declared void.
1826     return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1827 
1828   // Do not do any of the following transformations if the printf return value
1829   // is used, in general the printf return value is not compatible with either
1830   // putchar() or puts().
1831   if (!CI->use_empty())
1832     return nullptr;
1833 
1834   // printf("x") -> putchar('x'), even for '%'.
1835   if (FormatStr.size() == 1)
1836     return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1837 
1838   // printf("%s", "a") --> putchar('a')
1839   if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1840     StringRef ChrStr;
1841     if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1842       return nullptr;
1843     if (ChrStr.size() != 1)
1844       return nullptr;
1845     return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1846   }
1847 
1848   // printf("foo\n") --> puts("foo")
1849   if (FormatStr[FormatStr.size() - 1] == '\n' &&
1850       FormatStr.find('%') == StringRef::npos) { // No format characters.
1851     // Create a string literal with no \n on it.  We expect the constant merge
1852     // pass to be run after this pass, to merge duplicate strings.
1853     FormatStr = FormatStr.drop_back();
1854     Value *GV = B.CreateGlobalString(FormatStr, "str");
1855     return emitPutS(GV, B, TLI);
1856   }
1857 
1858   // Optimize specific format strings.
1859   // printf("%c", chr) --> putchar(chr)
1860   if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1861       CI->getArgOperand(1)->getType()->isIntegerTy())
1862     return emitPutChar(CI->getArgOperand(1), B, TLI);
1863 
1864   // printf("%s\n", str) --> puts(str)
1865   if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1866       CI->getArgOperand(1)->getType()->isPointerTy())
1867     return emitPutS(CI->getArgOperand(1), B, TLI);
1868   return nullptr;
1869 }
1870 
1871 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1872 
1873   Function *Callee = CI->getCalledFunction();
1874   // Require one fixed pointer argument and an integer/void result.
1875   FunctionType *FT = Callee->getFunctionType();
1876   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1877       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1878     return nullptr;
1879 
1880   if (Value *V = optimizePrintFString(CI, B)) {
1881     return V;
1882   }
1883 
1884   // printf(format, ...) -> iprintf(format, ...) if no floating point
1885   // arguments.
1886   if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1887     Module *M = B.GetInsertBlock()->getParent()->getParent();
1888     Constant *IPrintFFn =
1889         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1890     CallInst *New = cast<CallInst>(CI->clone());
1891     New->setCalledFunction(IPrintFFn);
1892     B.Insert(New);
1893     return New;
1894   }
1895   return nullptr;
1896 }
1897 
1898 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1899   // Check for a fixed format string.
1900   StringRef FormatStr;
1901   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1902     return nullptr;
1903 
1904   // If we just have a format string (nothing else crazy) transform it.
1905   if (CI->getNumArgOperands() == 2) {
1906     // Make sure there's no % in the constant array.  We could try to handle
1907     // %% -> % in the future if we cared.
1908     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1909       if (FormatStr[i] == '%')
1910         return nullptr; // we found a format specifier, bail out.
1911 
1912     // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1913     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1914                    ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1915                                     FormatStr.size() + 1),
1916                    1); // Copy the null byte.
1917     return ConstantInt::get(CI->getType(), FormatStr.size());
1918   }
1919 
1920   // The remaining optimizations require the format string to be "%s" or "%c"
1921   // and have an extra operand.
1922   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1923       CI->getNumArgOperands() < 3)
1924     return nullptr;
1925 
1926   // Decode the second character of the format string.
1927   if (FormatStr[1] == 'c') {
1928     // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1929     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1930       return nullptr;
1931     Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1932     Value *Ptr = castToCStr(CI->getArgOperand(0), B);
1933     B.CreateStore(V, Ptr);
1934     Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
1935     B.CreateStore(B.getInt8(0), Ptr);
1936 
1937     return ConstantInt::get(CI->getType(), 1);
1938   }
1939 
1940   if (FormatStr[1] == 's') {
1941     // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1942     if (!CI->getArgOperand(2)->getType()->isPointerTy())
1943       return nullptr;
1944 
1945     Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
1946     if (!Len)
1947       return nullptr;
1948     Value *IncLen =
1949         B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1950     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1951 
1952     // The sprintf result is the unincremented number of bytes in the string.
1953     return B.CreateIntCast(Len, CI->getType(), false);
1954   }
1955   return nullptr;
1956 }
1957 
1958 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1959   Function *Callee = CI->getCalledFunction();
1960   // Require two fixed pointer arguments and an integer result.
1961   FunctionType *FT = Callee->getFunctionType();
1962   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1963       !FT->getParamType(1)->isPointerTy() ||
1964       !FT->getReturnType()->isIntegerTy())
1965     return nullptr;
1966 
1967   if (Value *V = optimizeSPrintFString(CI, B)) {
1968     return V;
1969   }
1970 
1971   // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1972   // point arguments.
1973   if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1974     Module *M = B.GetInsertBlock()->getParent()->getParent();
1975     Constant *SIPrintFFn =
1976         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1977     CallInst *New = cast<CallInst>(CI->clone());
1978     New->setCalledFunction(SIPrintFFn);
1979     B.Insert(New);
1980     return New;
1981   }
1982   return nullptr;
1983 }
1984 
1985 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1986   optimizeErrorReporting(CI, B, 0);
1987 
1988   // All the optimizations depend on the format string.
1989   StringRef FormatStr;
1990   if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1991     return nullptr;
1992 
1993   // Do not do any of the following transformations if the fprintf return
1994   // value is used, in general the fprintf return value is not compatible
1995   // with fwrite(), fputc() or fputs().
1996   if (!CI->use_empty())
1997     return nullptr;
1998 
1999   // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2000   if (CI->getNumArgOperands() == 2) {
2001     for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
2002       if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
2003         return nullptr;        // We found a format specifier.
2004 
2005     return emitFWrite(
2006         CI->getArgOperand(1),
2007         ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
2008         CI->getArgOperand(0), B, DL, TLI);
2009   }
2010 
2011   // The remaining optimizations require the format string to be "%s" or "%c"
2012   // and have an extra operand.
2013   if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2014       CI->getNumArgOperands() < 3)
2015     return nullptr;
2016 
2017   // Decode the second character of the format string.
2018   if (FormatStr[1] == 'c') {
2019     // fprintf(F, "%c", chr) --> fputc(chr, F)
2020     if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2021       return nullptr;
2022     return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2023   }
2024 
2025   if (FormatStr[1] == 's') {
2026     // fprintf(F, "%s", str) --> fputs(str, F)
2027     if (!CI->getArgOperand(2)->getType()->isPointerTy())
2028       return nullptr;
2029     return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2030   }
2031   return nullptr;
2032 }
2033 
2034 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2035   Function *Callee = CI->getCalledFunction();
2036   // Require two fixed paramters as pointers and integer result.
2037   FunctionType *FT = Callee->getFunctionType();
2038   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2039       !FT->getParamType(1)->isPointerTy() ||
2040       !FT->getReturnType()->isIntegerTy())
2041     return nullptr;
2042 
2043   if (Value *V = optimizeFPrintFString(CI, B)) {
2044     return V;
2045   }
2046 
2047   // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2048   // floating point arguments.
2049   if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2050     Module *M = B.GetInsertBlock()->getParent()->getParent();
2051     Constant *FIPrintFFn =
2052         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2053     CallInst *New = cast<CallInst>(CI->clone());
2054     New->setCalledFunction(FIPrintFFn);
2055     B.Insert(New);
2056     return New;
2057   }
2058   return nullptr;
2059 }
2060 
2061 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2062   optimizeErrorReporting(CI, B, 3);
2063 
2064   Function *Callee = CI->getCalledFunction();
2065   // Require a pointer, an integer, an integer, a pointer, returning integer.
2066   FunctionType *FT = Callee->getFunctionType();
2067   if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2068       !FT->getParamType(1)->isIntegerTy() ||
2069       !FT->getParamType(2)->isIntegerTy() ||
2070       !FT->getParamType(3)->isPointerTy() ||
2071       !FT->getReturnType()->isIntegerTy())
2072     return nullptr;
2073 
2074   // Get the element size and count.
2075   ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2076   ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2077   if (!SizeC || !CountC)
2078     return nullptr;
2079   uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2080 
2081   // If this is writing zero records, remove the call (it's a noop).
2082   if (Bytes == 0)
2083     return ConstantInt::get(CI->getType(), 0);
2084 
2085   // If this is writing one byte, turn it into fputc.
2086   // This optimisation is only valid, if the return value is unused.
2087   if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2088     Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2089     Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2090     return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2091   }
2092 
2093   return nullptr;
2094 }
2095 
2096 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2097   optimizeErrorReporting(CI, B, 1);
2098 
2099   Function *Callee = CI->getCalledFunction();
2100 
2101   // Require two pointers.  Also, we can't optimize if return value is used.
2102   FunctionType *FT = Callee->getFunctionType();
2103   if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2104       !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2105     return nullptr;
2106 
2107   // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2108   uint64_t Len = GetStringLength(CI->getArgOperand(0));
2109   if (!Len)
2110     return nullptr;
2111 
2112   // Known to have no uses (see above).
2113   return emitFWrite(
2114       CI->getArgOperand(0),
2115       ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2116       CI->getArgOperand(1), B, DL, TLI);
2117 }
2118 
2119 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2120   Function *Callee = CI->getCalledFunction();
2121   // Require one fixed pointer argument and an integer/void result.
2122   FunctionType *FT = Callee->getFunctionType();
2123   if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2124       !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2125     return nullptr;
2126 
2127   // Check for a constant string.
2128   StringRef Str;
2129   if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2130     return nullptr;
2131 
2132   if (Str.empty() && CI->use_empty()) {
2133     // puts("") -> putchar('\n')
2134     Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
2135     if (CI->use_empty() || !Res)
2136       return Res;
2137     return B.CreateIntCast(Res, CI->getType(), true);
2138   }
2139 
2140   return nullptr;
2141 }
2142 
2143 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2144   LibFunc::Func Func;
2145   SmallString<20> FloatFuncName = FuncName;
2146   FloatFuncName += 'f';
2147   if (TLI->getLibFunc(FloatFuncName, Func))
2148     return TLI->has(Func);
2149   return false;
2150 }
2151 
2152 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2153                                                       IRBuilder<> &Builder) {
2154   LibFunc::Func Func;
2155   Function *Callee = CI->getCalledFunction();
2156   StringRef FuncName = Callee->getName();
2157 
2158   // Check for string/memory library functions.
2159   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2160     // Make sure we never change the calling convention.
2161     assert((ignoreCallingConv(Func) ||
2162             CI->getCallingConv() == llvm::CallingConv::C) &&
2163       "Optimizing string/memory libcall would change the calling convention");
2164     switch (Func) {
2165     case LibFunc::strcat:
2166       return optimizeStrCat(CI, Builder);
2167     case LibFunc::strncat:
2168       return optimizeStrNCat(CI, Builder);
2169     case LibFunc::strchr:
2170       return optimizeStrChr(CI, Builder);
2171     case LibFunc::strrchr:
2172       return optimizeStrRChr(CI, Builder);
2173     case LibFunc::strcmp:
2174       return optimizeStrCmp(CI, Builder);
2175     case LibFunc::strncmp:
2176       return optimizeStrNCmp(CI, Builder);
2177     case LibFunc::strcpy:
2178       return optimizeStrCpy(CI, Builder);
2179     case LibFunc::stpcpy:
2180       return optimizeStpCpy(CI, Builder);
2181     case LibFunc::strncpy:
2182       return optimizeStrNCpy(CI, Builder);
2183     case LibFunc::strlen:
2184       return optimizeStrLen(CI, Builder);
2185     case LibFunc::strpbrk:
2186       return optimizeStrPBrk(CI, Builder);
2187     case LibFunc::strtol:
2188     case LibFunc::strtod:
2189     case LibFunc::strtof:
2190     case LibFunc::strtoul:
2191     case LibFunc::strtoll:
2192     case LibFunc::strtold:
2193     case LibFunc::strtoull:
2194       return optimizeStrTo(CI, Builder);
2195     case LibFunc::strspn:
2196       return optimizeStrSpn(CI, Builder);
2197     case LibFunc::strcspn:
2198       return optimizeStrCSpn(CI, Builder);
2199     case LibFunc::strstr:
2200       return optimizeStrStr(CI, Builder);
2201     case LibFunc::memchr:
2202       return optimizeMemChr(CI, Builder);
2203     case LibFunc::memcmp:
2204       return optimizeMemCmp(CI, Builder);
2205     case LibFunc::memcpy:
2206       return optimizeMemCpy(CI, Builder);
2207     case LibFunc::memmove:
2208       return optimizeMemMove(CI, Builder);
2209     case LibFunc::memset:
2210       return optimizeMemSet(CI, Builder);
2211     default:
2212       break;
2213     }
2214   }
2215   return nullptr;
2216 }
2217 
2218 Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2219   if (CI->isNoBuiltin())
2220     return nullptr;
2221 
2222   LibFunc::Func Func;
2223   Function *Callee = CI->getCalledFunction();
2224   StringRef FuncName = Callee->getName();
2225 
2226   SmallVector<OperandBundleDef, 2> OpBundles;
2227   CI->getOperandBundlesAsDefs(OpBundles);
2228   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2229   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2230 
2231   // Command-line parameter overrides instruction attribute.
2232   if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2233     UnsafeFPShrink = EnableUnsafeFPShrink;
2234   else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
2235     UnsafeFPShrink = true;
2236 
2237   // First, check for intrinsics.
2238   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2239     if (!isCallingConvC)
2240       return nullptr;
2241     switch (II->getIntrinsicID()) {
2242     case Intrinsic::pow:
2243       return optimizePow(CI, Builder);
2244     case Intrinsic::exp2:
2245       return optimizeExp2(CI, Builder);
2246     case Intrinsic::fabs:
2247       return optimizeFabs(CI, Builder);
2248     case Intrinsic::log:
2249       return optimizeLog(CI, Builder);
2250     case Intrinsic::sqrt:
2251       return optimizeSqrt(CI, Builder);
2252     // TODO: Use foldMallocMemset() with memset intrinsic.
2253     default:
2254       return nullptr;
2255     }
2256   }
2257 
2258   // Also try to simplify calls to fortified library functions.
2259   if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2260     // Try to further simplify the result.
2261     CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2262     if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2263       // Use an IR Builder from SimplifiedCI if available instead of CI
2264       // to guarantee we reach all uses we might replace later on.
2265       IRBuilder<> TmpBuilder(SimplifiedCI);
2266       if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2267         // If we were able to further simplify, remove the now redundant call.
2268         SimplifiedCI->replaceAllUsesWith(V);
2269         SimplifiedCI->eraseFromParent();
2270         return V;
2271       }
2272     }
2273     return SimplifiedFortifiedCI;
2274   }
2275 
2276   // Then check for known library functions.
2277   if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2278     // We never change the calling convention.
2279     if (!ignoreCallingConv(Func) && !isCallingConvC)
2280       return nullptr;
2281     if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2282       return V;
2283     switch (Func) {
2284     case LibFunc::cosf:
2285     case LibFunc::cos:
2286     case LibFunc::cosl:
2287       return optimizeCos(CI, Builder);
2288     case LibFunc::sinpif:
2289     case LibFunc::sinpi:
2290     case LibFunc::cospif:
2291     case LibFunc::cospi:
2292       return optimizeSinCosPi(CI, Builder);
2293     case LibFunc::powf:
2294     case LibFunc::pow:
2295     case LibFunc::powl:
2296       return optimizePow(CI, Builder);
2297     case LibFunc::exp2l:
2298     case LibFunc::exp2:
2299     case LibFunc::exp2f:
2300       return optimizeExp2(CI, Builder);
2301     case LibFunc::fabsf:
2302     case LibFunc::fabs:
2303     case LibFunc::fabsl:
2304       return optimizeFabs(CI, Builder);
2305     case LibFunc::sqrtf:
2306     case LibFunc::sqrt:
2307     case LibFunc::sqrtl:
2308       return optimizeSqrt(CI, Builder);
2309     case LibFunc::ffs:
2310     case LibFunc::ffsl:
2311     case LibFunc::ffsll:
2312       return optimizeFFS(CI, Builder);
2313     case LibFunc::abs:
2314     case LibFunc::labs:
2315     case LibFunc::llabs:
2316       return optimizeAbs(CI, Builder);
2317     case LibFunc::isdigit:
2318       return optimizeIsDigit(CI, Builder);
2319     case LibFunc::isascii:
2320       return optimizeIsAscii(CI, Builder);
2321     case LibFunc::toascii:
2322       return optimizeToAscii(CI, Builder);
2323     case LibFunc::printf:
2324       return optimizePrintF(CI, Builder);
2325     case LibFunc::sprintf:
2326       return optimizeSPrintF(CI, Builder);
2327     case LibFunc::fprintf:
2328       return optimizeFPrintF(CI, Builder);
2329     case LibFunc::fwrite:
2330       return optimizeFWrite(CI, Builder);
2331     case LibFunc::fputs:
2332       return optimizeFPuts(CI, Builder);
2333     case LibFunc::log:
2334     case LibFunc::log10:
2335     case LibFunc::log1p:
2336     case LibFunc::log2:
2337     case LibFunc::logb:
2338       return optimizeLog(CI, Builder);
2339     case LibFunc::puts:
2340       return optimizePuts(CI, Builder);
2341     case LibFunc::tan:
2342     case LibFunc::tanf:
2343     case LibFunc::tanl:
2344       return optimizeTan(CI, Builder);
2345     case LibFunc::perror:
2346       return optimizeErrorReporting(CI, Builder);
2347     case LibFunc::vfprintf:
2348     case LibFunc::fiprintf:
2349       return optimizeErrorReporting(CI, Builder, 0);
2350     case LibFunc::fputc:
2351       return optimizeErrorReporting(CI, Builder, 1);
2352     case LibFunc::ceil:
2353     case LibFunc::floor:
2354     case LibFunc::rint:
2355     case LibFunc::round:
2356     case LibFunc::nearbyint:
2357     case LibFunc::trunc:
2358       if (hasFloatVersion(FuncName))
2359         return optimizeUnaryDoubleFP(CI, Builder, false);
2360       return nullptr;
2361     case LibFunc::acos:
2362     case LibFunc::acosh:
2363     case LibFunc::asin:
2364     case LibFunc::asinh:
2365     case LibFunc::atan:
2366     case LibFunc::atanh:
2367     case LibFunc::cbrt:
2368     case LibFunc::cosh:
2369     case LibFunc::exp:
2370     case LibFunc::exp10:
2371     case LibFunc::expm1:
2372     case LibFunc::sin:
2373     case LibFunc::sinh:
2374     case LibFunc::tanh:
2375       if (UnsafeFPShrink && hasFloatVersion(FuncName))
2376         return optimizeUnaryDoubleFP(CI, Builder, true);
2377       return nullptr;
2378     case LibFunc::copysign:
2379       if (hasFloatVersion(FuncName))
2380         return optimizeBinaryDoubleFP(CI, Builder);
2381       return nullptr;
2382     case LibFunc::fminf:
2383     case LibFunc::fmin:
2384     case LibFunc::fminl:
2385     case LibFunc::fmaxf:
2386     case LibFunc::fmax:
2387     case LibFunc::fmaxl:
2388       return optimizeFMinFMax(CI, Builder);
2389     default:
2390       return nullptr;
2391     }
2392   }
2393   return nullptr;
2394 }
2395 
2396 LibCallSimplifier::LibCallSimplifier(
2397     const DataLayout &DL, const TargetLibraryInfo *TLI,
2398     function_ref<void(Instruction *, Value *)> Replacer)
2399     : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
2400       Replacer(Replacer) {}
2401 
2402 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2403   // Indirect through the replacer used in this instance.
2404   Replacer(I, With);
2405 }
2406 
2407 // TODO:
2408 //   Additional cases that we need to add to this file:
2409 //
2410 // cbrt:
2411 //   * cbrt(expN(X))  -> expN(x/3)
2412 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2413 //   * cbrt(cbrt(x))  -> pow(x,1/9)
2414 //
2415 // exp, expf, expl:
2416 //   * exp(log(x))  -> x
2417 //
2418 // log, logf, logl:
2419 //   * log(exp(x))   -> x
2420 //   * log(exp(y))   -> y*log(e)
2421 //   * log(exp10(y)) -> y*log(10)
2422 //   * log(sqrt(x))  -> 0.5*log(x)
2423 //
2424 // lround, lroundf, lroundl:
2425 //   * lround(cnst) -> cnst'
2426 //
2427 // pow, powf, powl:
2428 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2429 //   * pow(pow(x,y),z)-> pow(x,y*z)
2430 //
2431 // round, roundf, roundl:
2432 //   * round(cnst) -> cnst'
2433 //
2434 // signbit:
2435 //   * signbit(cnst) -> cnst'
2436 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2437 //
2438 // sqrt, sqrtf, sqrtl:
2439 //   * sqrt(expN(x))  -> expN(x*0.5)
2440 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2441 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2442 //
2443 // trunc, truncf, truncl:
2444 //   * trunc(cnst) -> cnst'
2445 //
2446 //
2447 
2448 //===----------------------------------------------------------------------===//
2449 // Fortified Library Call Optimizations
2450 //===----------------------------------------------------------------------===//
2451 
2452 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2453                                                          unsigned ObjSizeOp,
2454                                                          unsigned SizeOp,
2455                                                          bool isString) {
2456   if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2457     return true;
2458   if (ConstantInt *ObjSizeCI =
2459           dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2460     if (ObjSizeCI->isAllOnesValue())
2461       return true;
2462     // If the object size wasn't -1 (unknown), bail out if we were asked to.
2463     if (OnlyLowerUnknownSize)
2464       return false;
2465     if (isString) {
2466       uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2467       // If the length is 0 we don't know how long it is and so we can't
2468       // remove the check.
2469       if (Len == 0)
2470         return false;
2471       return ObjSizeCI->getZExtValue() >= Len;
2472     }
2473     if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2474       return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2475   }
2476   return false;
2477 }
2478 
2479 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2480                                                      IRBuilder<> &B) {
2481   Function *Callee = CI->getCalledFunction();
2482 
2483   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
2484     return nullptr;
2485 
2486   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2487     B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2488                    CI->getArgOperand(2), 1);
2489     return CI->getArgOperand(0);
2490   }
2491   return nullptr;
2492 }
2493 
2494 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2495                                                       IRBuilder<> &B) {
2496   Function *Callee = CI->getCalledFunction();
2497 
2498   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
2499     return nullptr;
2500 
2501   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2502     B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2503                     CI->getArgOperand(2), 1);
2504     return CI->getArgOperand(0);
2505   }
2506   return nullptr;
2507 }
2508 
2509 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2510                                                      IRBuilder<> &B) {
2511   Function *Callee = CI->getCalledFunction();
2512 
2513   if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
2514     return nullptr;
2515 
2516   // TODO: Try foldMallocMemset() here.
2517 
2518   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2519     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2520     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2521     return CI->getArgOperand(0);
2522   }
2523   return nullptr;
2524 }
2525 
2526 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2527                                                       IRBuilder<> &B,
2528                                                       LibFunc::Func Func) {
2529   Function *Callee = CI->getCalledFunction();
2530   StringRef Name = Callee->getName();
2531   const DataLayout &DL = CI->getModule()->getDataLayout();
2532 
2533   if (!checkStringCopyLibFuncSignature(Callee, Func))
2534     return nullptr;
2535 
2536   Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2537         *ObjSize = CI->getArgOperand(2);
2538 
2539   // __stpcpy_chk(x,x,...)  -> x+strlen(x)
2540   if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2541     Value *StrLen = emitStrLen(Src, B, DL, TLI);
2542     return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2543   }
2544 
2545   // If a) we don't have any length information, or b) we know this will
2546   // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2547   // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2548   // TODO: It might be nice to get a maximum length out of the possible
2549   // string lengths for varying.
2550   if (isFortifiedCallFoldable(CI, 2, 1, true))
2551     return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2552 
2553   if (OnlyLowerUnknownSize)
2554     return nullptr;
2555 
2556   // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2557   uint64_t Len = GetStringLength(Src);
2558   if (Len == 0)
2559     return nullptr;
2560 
2561   Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2562   Value *LenV = ConstantInt::get(SizeTTy, Len);
2563   Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2564   // If the function was an __stpcpy_chk, and we were able to fold it into
2565   // a __memcpy_chk, we still need to return the correct end pointer.
2566   if (Ret && Func == LibFunc::stpcpy_chk)
2567     return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2568   return Ret;
2569 }
2570 
2571 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2572                                                        IRBuilder<> &B,
2573                                                        LibFunc::Func Func) {
2574   Function *Callee = CI->getCalledFunction();
2575   StringRef Name = Callee->getName();
2576 
2577   if (!checkStringCopyLibFuncSignature(Callee, Func))
2578     return nullptr;
2579   if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2580     Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2581                              CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2582     return Ret;
2583   }
2584   return nullptr;
2585 }
2586 
2587 Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2588   // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2589   // Some clang users checked for _chk libcall availability using:
2590   //   __has_builtin(__builtin___memcpy_chk)
2591   // When compiling with -fno-builtin, this is always true.
2592   // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2593   // end up with fortified libcalls, which isn't acceptable in a freestanding
2594   // environment which only provides their non-fortified counterparts.
2595   //
2596   // Until we change clang and/or teach external users to check for availability
2597   // differently, disregard the "nobuiltin" attribute and TLI::has.
2598   //
2599   // PR23093.
2600 
2601   LibFunc::Func Func;
2602   Function *Callee = CI->getCalledFunction();
2603   StringRef FuncName = Callee->getName();
2604 
2605   SmallVector<OperandBundleDef, 2> OpBundles;
2606   CI->getOperandBundlesAsDefs(OpBundles);
2607   IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2608   bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2609 
2610   // First, check that this is a known library functions.
2611   if (!TLI->getLibFunc(FuncName, Func))
2612     return nullptr;
2613 
2614   // We never change the calling convention.
2615   if (!ignoreCallingConv(Func) && !isCallingConvC)
2616     return nullptr;
2617 
2618   switch (Func) {
2619   case LibFunc::memcpy_chk:
2620     return optimizeMemCpyChk(CI, Builder);
2621   case LibFunc::memmove_chk:
2622     return optimizeMemMoveChk(CI, Builder);
2623   case LibFunc::memset_chk:
2624     return optimizeMemSetChk(CI, Builder);
2625   case LibFunc::stpcpy_chk:
2626   case LibFunc::strcpy_chk:
2627     return optimizeStrpCpyChk(CI, Builder, Func);
2628   case LibFunc::stpncpy_chk:
2629   case LibFunc::strncpy_chk:
2630     return optimizeStrpNCpyChk(CI, Builder, Func);
2631   default:
2632     break;
2633   }
2634   return nullptr;
2635 }
2636 
2637 FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2638     const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2639     : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
2640