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