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