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