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