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