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