LLVM API Documentation

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