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