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