LLVM  8.0.1
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 file implements the library calls simplifier. It does not implement
11 // any pass, but can't be used by other passes to do simplifications.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/Triple.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/KnownBits.h"
38 
39 using namespace llvm;
40 using namespace PatternMatch;
41 
42 static cl::opt<bool>
43  EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
44  cl::init(false),
45  cl::desc("Enable unsafe double to float "
46  "shrinking for math lib calls"));
47 
48 
49 //===----------------------------------------------------------------------===//
50 // Helper Functions
51 //===----------------------------------------------------------------------===//
52 
53 static bool ignoreCallingConv(LibFunc Func) {
54  return Func == LibFunc_abs || Func == LibFunc_labs ||
55  Func == LibFunc_llabs || Func == LibFunc_strlen;
56 }
57 
59  switch(CI->getCallingConv()) {
60  default:
61  return false;
63  return true;
67 
68  // The iOS ABI diverges from the standard in some cases, so for now don't
69  // try to simplify those calls.
70  if (Triple(CI->getModule()->getTargetTriple()).isiOS())
71  return false;
72 
73  auto *FuncTy = CI->getFunctionType();
74 
75  if (!FuncTy->getReturnType()->isPointerTy() &&
76  !FuncTy->getReturnType()->isIntegerTy() &&
77  !FuncTy->getReturnType()->isVoidTy())
78  return false;
79 
80  for (auto Param : FuncTy->params()) {
81  if (!Param->isPointerTy() && !Param->isIntegerTy())
82  return false;
83  }
84  return true;
85  }
86  }
87  return false;
88 }
89 
90 /// Return true if it is only used in equality comparisons with With.
91 static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
92  for (User *U : V->users()) {
93  if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
94  if (IC->isEquality() && IC->getOperand(1) == With)
95  continue;
96  // Unknown instruction.
97  return false;
98  }
99  return true;
100 }
101 
102 static bool callHasFloatingPointArgument(const CallInst *CI) {
103  return any_of(CI->operands(), [](const Use &OI) {
104  return OI->getType()->isFloatingPointTy();
105  });
106 }
107 
108 static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
109  if (Base < 2 || Base > 36)
110  // handle special zero base
111  if (Base != 0)
112  return nullptr;
113 
114  char *End;
115  std::string nptr = Str.str();
116  errno = 0;
117  long long int Result = strtoll(nptr.c_str(), &End, Base);
118  if (errno)
119  return nullptr;
120 
121  // if we assume all possible target locales are ASCII supersets,
122  // then if strtoll successfully parses a number on the host,
123  // it will also successfully parse the same way on the target
124  if (*End != '\0')
125  return nullptr;
126 
127  if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
128  return nullptr;
129 
130  return ConstantInt::get(CI->getType(), Result);
131 }
132 
134  const TargetLibraryInfo *TLI) {
135  CallInst *FOpen = dyn_cast<CallInst>(File);
136  if (!FOpen)
137  return false;
138 
139  Function *InnerCallee = FOpen->getCalledFunction();
140  if (!InnerCallee)
141  return false;
142 
143  LibFunc Func;
144  if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
145  Func != LibFunc_fopen)
146  return false;
147 
149  if (PointerMayBeCaptured(File, true, true))
150  return false;
151 
152  return true;
153 }
154 
156  for (User *U : V->users()) {
157  if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
158  if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
159  if (C->isNullValue())
160  continue;
161  // Unknown instruction.
162  return false;
163  }
164  return true;
165 }
166 
167 static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
168  const DataLayout &DL) {
170  return false;
171 
172  if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
173  return false;
174 
176  return false;
177 
178  return true;
179 }
180 
181 //===----------------------------------------------------------------------===//
182 // String and Memory Library Call Optimizations
183 //===----------------------------------------------------------------------===//
184 
185 Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
186  // Extract some information from the instruction
187  Value *Dst = CI->getArgOperand(0);
188  Value *Src = CI->getArgOperand(1);
189 
190  // See if we can get the length of the input string.
191  uint64_t Len = GetStringLength(Src);
192  if (Len == 0)
193  return nullptr;
194  --Len; // Unbias length.
195 
196  // Handle the simple, do-nothing case: strcat(x, "") -> x
197  if (Len == 0)
198  return Dst;
199 
200  return emitStrLenMemCpy(Src, Dst, Len, B);
201 }
202 
203 Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
204  IRBuilder<> &B) {
205  // We need to find the end of the destination string. That's where the
206  // memory is to be moved to. We just generate a call to strlen.
207  Value *DstLen = emitStrLen(Dst, B, DL, TLI);
208  if (!DstLen)
209  return nullptr;
210 
211  // Now that we have the destination's length, we must index into the
212  // destination's pointer to get the actual memcpy destination (end of
213  // the string .. we're concatenating).
214  Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
215 
216  // We have enough information to now generate the memcpy call to do the
217  // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
218  B.CreateMemCpy(CpyDst, 1, Src, 1,
219  ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
220  return Dst;
221 }
222 
223 Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
224  // Extract some information from the instruction.
225  Value *Dst = CI->getArgOperand(0);
226  Value *Src = CI->getArgOperand(1);
227  uint64_t Len;
228 
229  // We don't do anything if length is not constant.
230  if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
231  Len = LengthArg->getZExtValue();
232  else
233  return nullptr;
234 
235  // See if we can get the length of the input string.
236  uint64_t SrcLen = GetStringLength(Src);
237  if (SrcLen == 0)
238  return nullptr;
239  --SrcLen; // Unbias length.
240 
241  // Handle the simple, do-nothing cases:
242  // strncat(x, "", c) -> x
243  // strncat(x, c, 0) -> x
244  if (SrcLen == 0 || Len == 0)
245  return Dst;
246 
247  // We don't optimize this case.
248  if (Len < SrcLen)
249  return nullptr;
250 
251  // strncat(x, s, c) -> strcat(x, s)
252  // s is constant so the strcat can be optimized further.
253  return emitStrLenMemCpy(Src, Dst, SrcLen, B);
254 }
255 
256 Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
258  FunctionType *FT = Callee->getFunctionType();
259  Value *SrcStr = CI->getArgOperand(0);
260 
261  // If the second operand is non-constant, see if we can compute the length
262  // of the input string and turn this into memchr.
263  ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
264  if (!CharC) {
265  uint64_t Len = GetStringLength(SrcStr);
266  if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
267  return nullptr;
268 
269  return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
270  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
271  B, DL, TLI);
272  }
273 
274  // Otherwise, the character is a constant, see if the first argument is
275  // a string literal. If so, we can constant fold.
276  StringRef Str;
277  if (!getConstantStringInfo(SrcStr, Str)) {
278  if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
279  return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
280  "strchr");
281  return nullptr;
282  }
283 
284  // Compute the offset, make sure to handle the case when we're searching for
285  // zero (a weird way to spell strlen).
286  size_t I = (0xFF & CharC->getSExtValue()) == 0
287  ? Str.size()
288  : Str.find(CharC->getSExtValue());
289  if (I == StringRef::npos) // Didn't find the char. strchr returns null.
290  return Constant::getNullValue(CI->getType());
291 
292  // strchr(s+n,c) -> gep(s+n+i,c)
293  return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
294 }
295 
296 Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
297  Value *SrcStr = CI->getArgOperand(0);
298  ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
299 
300  // Cannot fold anything if we're not looking for a constant.
301  if (!CharC)
302  return nullptr;
303 
304  StringRef Str;
305  if (!getConstantStringInfo(SrcStr, Str)) {
306  // strrchr(s, 0) -> strchr(s, 0)
307  if (CharC->isZero())
308  return emitStrChr(SrcStr, '\0', B, TLI);
309  return nullptr;
310  }
311 
312  // Compute the offset.
313  size_t I = (0xFF & CharC->getSExtValue()) == 0
314  ? Str.size()
315  : Str.rfind(CharC->getSExtValue());
316  if (I == StringRef::npos) // Didn't find the char. Return null.
317  return Constant::getNullValue(CI->getType());
318 
319  // strrchr(s+n,c) -> gep(s+n+i,c)
320  return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
321 }
322 
323 Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
324  Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
325  if (Str1P == Str2P) // strcmp(x,x) -> 0
326  return ConstantInt::get(CI->getType(), 0);
327 
328  StringRef Str1, Str2;
329  bool HasStr1 = getConstantStringInfo(Str1P, Str1);
330  bool HasStr2 = getConstantStringInfo(Str2P, Str2);
331 
332  // strcmp(x, y) -> cnst (if both x and y are constant strings)
333  if (HasStr1 && HasStr2)
334  return ConstantInt::get(CI->getType(), Str1.compare(Str2));
335 
336  if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
337  return B.CreateNeg(
338  B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
339 
340  if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
341  return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
342 
343  // strcmp(P, "x") -> memcmp(P, "x", 2)
344  uint64_t Len1 = GetStringLength(Str1P);
345  uint64_t Len2 = GetStringLength(Str2P);
346  if (Len1 && Len2) {
347  return emitMemCmp(Str1P, Str2P,
348  ConstantInt::get(DL.getIntPtrType(CI->getContext()),
349  std::min(Len1, Len2)),
350  B, DL, TLI);
351  }
352 
353  // strcmp to memcmp
354  if (!HasStr1 && HasStr2) {
355  if (canTransformToMemCmp(CI, Str1P, Len2, DL))
356  return emitMemCmp(
357  Str1P, Str2P,
358  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
359  TLI);
360  } else if (HasStr1 && !HasStr2) {
361  if (canTransformToMemCmp(CI, Str2P, Len1, DL))
362  return emitMemCmp(
363  Str1P, Str2P,
364  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
365  TLI);
366  }
367 
368  return nullptr;
369 }
370 
371 Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
372  Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
373  if (Str1P == Str2P) // strncmp(x,x,n) -> 0
374  return ConstantInt::get(CI->getType(), 0);
375 
376  // Get the length argument if it is constant.
377  uint64_t Length;
378  if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
379  Length = LengthArg->getZExtValue();
380  else
381  return nullptr;
382 
383  if (Length == 0) // strncmp(x,y,0) -> 0
384  return ConstantInt::get(CI->getType(), 0);
385 
386  if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
387  return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
388 
389  StringRef Str1, Str2;
390  bool HasStr1 = getConstantStringInfo(Str1P, Str1);
391  bool HasStr2 = getConstantStringInfo(Str2P, Str2);
392 
393  // strncmp(x, y) -> cnst (if both x and y are constant strings)
394  if (HasStr1 && HasStr2) {
395  StringRef SubStr1 = Str1.substr(0, Length);
396  StringRef SubStr2 = Str2.substr(0, Length);
397  return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
398  }
399 
400  if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
401  return B.CreateNeg(
402  B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
403 
404  if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
405  return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
406 
407  uint64_t Len1 = GetStringLength(Str1P);
408  uint64_t Len2 = GetStringLength(Str2P);
409 
410  // strncmp to memcmp
411  if (!HasStr1 && HasStr2) {
412  Len2 = std::min(Len2, Length);
413  if (canTransformToMemCmp(CI, Str1P, Len2, DL))
414  return emitMemCmp(
415  Str1P, Str2P,
416  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
417  TLI);
418  } else if (HasStr1 && !HasStr2) {
419  Len1 = std::min(Len1, Length);
420  if (canTransformToMemCmp(CI, Str2P, Len1, DL))
421  return emitMemCmp(
422  Str1P, Str2P,
423  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
424  TLI);
425  }
426 
427  return nullptr;
428 }
429 
430 Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
431  Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
432  if (Dst == Src) // strcpy(x,x) -> x
433  return Src;
434 
435  // See if we can get the length of the input string.
436  uint64_t Len = GetStringLength(Src);
437  if (Len == 0)
438  return nullptr;
439 
440  // We have enough information to now generate the memcpy call to do the
441  // copy for us. Make a memcpy to copy the nul byte with align = 1.
442  B.CreateMemCpy(Dst, 1, Src, 1,
443  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
444  return Dst;
445 }
446 
447 Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
449  Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
450  if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
451  Value *StrLen = emitStrLen(Src, B, DL, TLI);
452  return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
453  }
454 
455  // See if we can get the length of the input string.
456  uint64_t Len = GetStringLength(Src);
457  if (Len == 0)
458  return nullptr;
459 
460  Type *PT = Callee->getFunctionType()->getParamType(0);
461  Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
462  Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
463  ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
464 
465  // We have enough information to now generate the memcpy call to do the
466  // copy for us. Make a memcpy to copy the nul byte with align = 1.
467  B.CreateMemCpy(Dst, 1, Src, 1, LenV);
468  return DstEnd;
469 }
470 
471 Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
473  Value *Dst = CI->getArgOperand(0);
474  Value *Src = CI->getArgOperand(1);
475  Value *LenOp = CI->getArgOperand(2);
476 
477  // See if we can get the length of the input string.
478  uint64_t SrcLen = GetStringLength(Src);
479  if (SrcLen == 0)
480  return nullptr;
481  --SrcLen;
482 
483  if (SrcLen == 0) {
484  // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
485  B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
486  return Dst;
487  }
488 
489  uint64_t Len;
490  if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
491  Len = LengthArg->getZExtValue();
492  else
493  return nullptr;
494 
495  if (Len == 0)
496  return Dst; // strncpy(x, y, 0) -> x
497 
498  // Let strncpy handle the zero padding
499  if (Len > SrcLen + 1)
500  return nullptr;
501 
502  Type *PT = Callee->getFunctionType()->getParamType(0);
503  // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
504  B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
505 
506  return Dst;
507 }
508 
509 Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
510  unsigned CharSize) {
511  Value *Src = CI->getArgOperand(0);
512 
513  // Constant folding: strlen("xyz") -> 3
514  if (uint64_t Len = GetStringLength(Src, CharSize))
515  return ConstantInt::get(CI->getType(), Len - 1);
516 
517  // If s is a constant pointer pointing to a string literal, we can fold
518  // strlen(s + x) to strlen(s) - x, when x is known to be in the range
519  // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
520  // We only try to simplify strlen when the pointer s points to an array
521  // of i8. Otherwise, we would need to scale the offset x before doing the
522  // subtraction. This will make the optimization more complex, and it's not
523  // very useful because calling strlen for a pointer of other types is
524  // very uncommon.
525  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
526  if (!isGEPBasedOnPointerToString(GEP, CharSize))
527  return nullptr;
528 
530  if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
531  uint64_t NullTermIdx;
532  if (Slice.Array == nullptr) {
533  NullTermIdx = 0;
534  } else {
535  NullTermIdx = ~((uint64_t)0);
536  for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
537  if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
538  NullTermIdx = I;
539  break;
540  }
541  }
542  // If the string does not have '\0', leave it to strlen to compute
543  // its length.
544  if (NullTermIdx == ~((uint64_t)0))
545  return nullptr;
546  }
547 
548  Value *Offset = GEP->getOperand(2);
549  KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
550  Known.Zero.flipAllBits();
551  uint64_t ArrSize =
552  cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
553 
554  // KnownZero's bits are flipped, so zeros in KnownZero now represent
555  // bits known to be zeros in Offset, and ones in KnowZero represent
556  // bits unknown in Offset. Therefore, Offset is known to be in range
557  // [0, NullTermIdx] when the flipped KnownZero is non-negative and
558  // unsigned-less-than NullTermIdx.
559  //
560  // If Offset is not provably in the range [0, NullTermIdx], we can still
561  // optimize if we can prove that the program has undefined behavior when
562  // Offset is outside that range. That is the case when GEP->getOperand(0)
563  // is a pointer to an object whose memory extent is NullTermIdx+1.
564  if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
565  (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
566  NullTermIdx == ArrSize - 1)) {
567  Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
568  return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
569  Offset);
570  }
571  }
572 
573  return nullptr;
574  }
575 
576  // strlen(x?"foo":"bars") --> x ? 3 : 4
577  if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
578  uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
579  uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
580  if (LenTrue && LenFalse) {
581  ORE.emit([&]() {
582  return OptimizationRemark("instcombine", "simplify-libcalls", CI)
583  << "folded strlen(select) to select of constants";
584  });
585  return B.CreateSelect(SI->getCondition(),
586  ConstantInt::get(CI->getType(), LenTrue - 1),
587  ConstantInt::get(CI->getType(), LenFalse - 1));
588  }
589  }
590 
591  // strlen(x) != 0 --> *x != 0
592  // strlen(x) == 0 --> *x == 0
594  return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
595 
596  return nullptr;
597 }
598 
599 Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
600  return optimizeStringLength(CI, B, 8);
601 }
602 
603 Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
604  Module &M = *CI->getModule();
605  unsigned WCharSize = TLI->getWCharSize(M) * 8;
606  // We cannot perform this optimization without wchar_size metadata.
607  if (WCharSize == 0)
608  return nullptr;
609 
610  return optimizeStringLength(CI, B, WCharSize);
611 }
612 
613 Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
614  StringRef S1, S2;
615  bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
616  bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
617 
618  // strpbrk(s, "") -> nullptr
619  // strpbrk("", s) -> nullptr
620  if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
621  return Constant::getNullValue(CI->getType());
622 
623  // Constant folding.
624  if (HasS1 && HasS2) {
625  size_t I = S1.find_first_of(S2);
626  if (I == StringRef::npos) // No match.
627  return Constant::getNullValue(CI->getType());
628 
629  return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
630  "strpbrk");
631  }
632 
633  // strpbrk(s, "a") -> strchr(s, 'a')
634  if (HasS2 && S2.size() == 1)
635  return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
636 
637  return nullptr;
638 }
639 
640 Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
641  Value *EndPtr = CI->getArgOperand(1);
642  if (isa<ConstantPointerNull>(EndPtr)) {
643  // With a null EndPtr, this function won't capture the main argument.
644  // It would be readonly too, except that it still may write to errno.
646  }
647 
648  return nullptr;
649 }
650 
651 Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
652  StringRef S1, S2;
653  bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
654  bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
655 
656  // strspn(s, "") -> 0
657  // strspn("", s) -> 0
658  if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
659  return Constant::getNullValue(CI->getType());
660 
661  // Constant folding.
662  if (HasS1 && HasS2) {
663  size_t Pos = S1.find_first_not_of(S2);
664  if (Pos == StringRef::npos)
665  Pos = S1.size();
666  return ConstantInt::get(CI->getType(), Pos);
667  }
668 
669  return nullptr;
670 }
671 
672 Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
673  StringRef S1, S2;
674  bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
675  bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
676 
677  // strcspn("", s) -> 0
678  if (HasS1 && S1.empty())
679  return Constant::getNullValue(CI->getType());
680 
681  // Constant folding.
682  if (HasS1 && HasS2) {
683  size_t Pos = S1.find_first_of(S2);
684  if (Pos == StringRef::npos)
685  Pos = S1.size();
686  return ConstantInt::get(CI->getType(), Pos);
687  }
688 
689  // strcspn(s, "") -> strlen(s)
690  if (HasS2 && S2.empty())
691  return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
692 
693  return nullptr;
694 }
695 
696 Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
697  // fold strstr(x, x) -> x.
698  if (CI->getArgOperand(0) == CI->getArgOperand(1))
699  return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
700 
701  // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
703  Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
704  if (!StrLen)
705  return nullptr;
706  Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
707  StrLen, B, DL, TLI);
708  if (!StrNCmp)
709  return nullptr;
710  for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
711  ICmpInst *Old = cast<ICmpInst>(*UI++);
712  Value *Cmp =
713  B.CreateICmp(Old->getPredicate(), StrNCmp,
714  ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
715  replaceAllUsesWith(Old, Cmp);
716  }
717  return CI;
718  }
719 
720  // See if either input string is a constant string.
721  StringRef SearchStr, ToFindStr;
722  bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
723  bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
724 
725  // fold strstr(x, "") -> x.
726  if (HasStr2 && ToFindStr.empty())
727  return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
728 
729  // If both strings are known, constant fold it.
730  if (HasStr1 && HasStr2) {
731  size_t Offset = SearchStr.find(ToFindStr);
732 
733  if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
734  return Constant::getNullValue(CI->getType());
735 
736  // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
737  Value *Result = castToCStr(CI->getArgOperand(0), B);
738  Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
739  return B.CreateBitCast(Result, CI->getType());
740  }
741 
742  // fold strstr(x, "y") -> strchr(x, 'y').
743  if (HasStr2 && ToFindStr.size() == 1) {
744  Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
745  return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
746  }
747  return nullptr;
748 }
749 
750 Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
751  Value *SrcStr = CI->getArgOperand(0);
752  ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
754 
755  // memchr(x, y, 0) -> null
756  if (LenC && LenC->isZero())
757  return Constant::getNullValue(CI->getType());
758 
759  // From now on we need at least constant length and string.
760  StringRef Str;
761  if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
762  return nullptr;
763 
764  // Truncate the string to LenC. If Str is smaller than LenC we will still only
765  // scan the string, as reading past the end of it is undefined and we can just
766  // return null if we don't find the char.
767  Str = Str.substr(0, LenC->getZExtValue());
768 
769  // If the char is variable but the input str and length are not we can turn
770  // this memchr call into a simple bit field test. Of course this only works
771  // when the return value is only checked against null.
772  //
773  // It would be really nice to reuse switch lowering here but we can't change
774  // the CFG at this point.
775  //
776  // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
777  // after bounds check.
778  if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
779  unsigned char Max =
780  *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
781  reinterpret_cast<const unsigned char *>(Str.end()));
782 
783  // Make sure the bit field we're about to create fits in a register on the
784  // target.
785  // FIXME: On a 64 bit architecture this prevents us from using the
786  // interesting range of alpha ascii chars. We could do better by emitting
787  // two bitfields or shifting the range by 64 if no lower chars are used.
788  if (!DL.fitsInLegalInteger(Max + 1))
789  return nullptr;
790 
791  // For the bit field use a power-of-2 type with at least 8 bits to avoid
792  // creating unnecessary illegal types.
793  unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
794 
795  // Now build the bit field.
796  APInt Bitfield(Width, 0);
797  for (char C : Str)
798  Bitfield.setBit((unsigned char)C);
799  Value *BitfieldC = B.getInt(Bitfield);
800 
801  // Adjust width of "C" to the bitfield width, then mask off the high bits.
802  Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
803  C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
804 
805  // First check that the bit field access is within bounds.
806  Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
807  "memchr.bounds");
808 
809  // Create code that checks if the given bit is set in the field.
810  Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
811  Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
812 
813  // Finally merge both checks and cast to pointer type. The inttoptr
814  // implicitly zexts the i1 to intptr type.
815  return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
816  }
817 
818  // Check if all arguments are constants. If so, we can constant fold.
819  if (!CharC)
820  return nullptr;
821 
822  // Compute the offset.
823  size_t I = Str.find(CharC->getSExtValue() & 0xFF);
824  if (I == StringRef::npos) // Didn't find the char. memchr returns null.
825  return Constant::getNullValue(CI->getType());
826 
827  // memchr(s+n,c,l) -> gep(s+n+i,c)
828  return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
829 }
830 
831 Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
832  Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
833 
834  if (LHS == RHS) // memcmp(s,s,x) -> 0
835  return Constant::getNullValue(CI->getType());
836 
837  // Make sure we have a constant length.
839  if (!LenC)
840  return nullptr;
841 
842  uint64_t Len = LenC->getZExtValue();
843  if (Len == 0) // memcmp(s1,s2,0) -> 0
844  return Constant::getNullValue(CI->getType());
845 
846  // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
847  if (Len == 1) {
848  Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
849  CI->getType(), "lhsv");
850  Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
851  CI->getType(), "rhsv");
852  return B.CreateSub(LHSV, RHSV, "chardiff");
853  }
854 
855  // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
856  // TODO: The case where both inputs are constants does not need to be limited
857  // to legal integers or equality comparison. See block below this.
858  if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
859  IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
860  unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
861 
862  // First, see if we can fold either argument to a constant.
863  Value *LHSV = nullptr;
864  if (auto *LHSC = dyn_cast<Constant>(LHS)) {
865  LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
866  LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
867  }
868  Value *RHSV = nullptr;
869  if (auto *RHSC = dyn_cast<Constant>(RHS)) {
870  RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
871  RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
872  }
873 
874  // Don't generate unaligned loads. If either source is constant data,
875  // alignment doesn't matter for that source because there is no load.
876  if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
877  (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
878  if (!LHSV) {
879  Type *LHSPtrTy =
880  IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
881  LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
882  }
883  if (!RHSV) {
884  Type *RHSPtrTy =
885  IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
886  RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
887  }
888  return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
889  }
890  }
891 
892  // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
893  // TODO: This is limited to i8 arrays.
894  StringRef LHSStr, RHSStr;
895  if (getConstantStringInfo(LHS, LHSStr) &&
896  getConstantStringInfo(RHS, RHSStr)) {
897  // Make sure we're not reading out-of-bounds memory.
898  if (Len > LHSStr.size() || Len > RHSStr.size())
899  return nullptr;
900  // Fold the memcmp and normalize the result. This way we get consistent
901  // results across multiple platforms.
902  uint64_t Ret = 0;
903  int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
904  if (Cmp < 0)
905  Ret = -1;
906  else if (Cmp > 0)
907  Ret = 1;
908  return ConstantInt::get(CI->getType(), Ret);
909  }
910 
911  return nullptr;
912 }
913 
914 Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
915  // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
916  B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
917  CI->getArgOperand(2));
918  return CI->getArgOperand(0);
919 }
920 
921 Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
922  // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
923  B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
924  CI->getArgOperand(2));
925  return CI->getArgOperand(0);
926 }
927 
928 /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
929 Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
930  // This has to be a memset of zeros (bzero).
931  auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
932  if (!FillValue || FillValue->getZExtValue() != 0)
933  return nullptr;
934 
935  // TODO: We should handle the case where the malloc has more than one use.
936  // This is necessary to optimize common patterns such as when the result of
937  // the malloc is checked against null or when a memset intrinsic is used in
938  // place of a memset library call.
939  auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
940  if (!Malloc || !Malloc->hasOneUse())
941  return nullptr;
942 
943  // Is the inner call really malloc()?
944  Function *InnerCallee = Malloc->getCalledFunction();
945  if (!InnerCallee)
946  return nullptr;
947 
948  LibFunc Func;
949  if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
950  Func != LibFunc_malloc)
951  return nullptr;
952 
953  // The memset must cover the same number of bytes that are malloc'd.
954  if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
955  return nullptr;
956 
957  // Replace the malloc with a calloc. We need the data layout to know what the
958  // actual size of a 'size_t' parameter is.
959  B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
960  const DataLayout &DL = Malloc->getModule()->getDataLayout();
961  IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
962  Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
963  Malloc->getArgOperand(0), Malloc->getAttributes(),
964  B, *TLI);
965  if (!Calloc)
966  return nullptr;
967 
968  Malloc->replaceAllUsesWith(Calloc);
969  eraseFromParent(Malloc);
970 
971  return Calloc;
972 }
973 
974 Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
975  if (auto *Calloc = foldMallocMemset(CI, B))
976  return Calloc;
977 
978  // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
979  Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
980  B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
981  return CI->getArgOperand(0);
982 }
983 
984 Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
985  if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
986  return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
987 
988  return nullptr;
989 }
990 
991 //===----------------------------------------------------------------------===//
992 // Math Library Optimizations
993 //===----------------------------------------------------------------------===//
994 
995 // Replace a libcall \p CI with a call to intrinsic \p IID
997  // Propagate fast-math flags from the existing call to the new call.
1000 
1001  Module *M = CI->getModule();
1002  Value *V = CI->getArgOperand(0);
1003  Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1004  CallInst *NewCall = B.CreateCall(F, V);
1005  NewCall->takeName(CI);
1006  return NewCall;
1007 }
1008 
1009 /// Return a variant of Val with float type.
1010 /// Currently this works in two cases: If Val is an FPExtension of a float
1011 /// value to something bigger, simply return the operand.
1012 /// If Val is a ConstantFP but can be converted to a float ConstantFP without
1013 /// loss of precision do so.
1015  if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1016  Value *Op = Cast->getOperand(0);
1017  if (Op->getType()->isFloatTy())
1018  return Op;
1019  }
1020  if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1021  APFloat F = Const->getValueAPF();
1022  bool losesInfo;
1024  &losesInfo);
1025  if (!losesInfo)
1026  return ConstantFP::get(Const->getContext(), F);
1027  }
1028  return nullptr;
1029 }
1030 
1031 /// Shrink double -> float functions.
1033  bool isBinary, bool isPrecise = false) {
1034  if (!CI->getType()->isDoubleTy())
1035  return nullptr;
1036 
1037  // If not all the uses of the function are converted to float, then bail out.
1038  // This matters if the precision of the result is more important than the
1039  // precision of the arguments.
1040  if (isPrecise)
1041  for (User *U : CI->users()) {
1042  FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1043  if (!Cast || !Cast->getType()->isFloatTy())
1044  return nullptr;
1045  }
1046 
1047  // If this is something like 'g((double) float)', convert to 'gf(float)'.
1048  Value *V[2];
1049  V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1050  V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1051  if (!V[0] || (isBinary && !V[1]))
1052  return nullptr;
1053 
1054  // If call isn't an intrinsic, check that it isn't within a function with the
1055  // same name as the float version of this call, otherwise the result is an
1056  // infinite loop. For example, from MinGW-w64:
1057  //
1058  // float expf(float val) { return (float) exp((double) val); }
1059  Function *CalleeFn = CI->getCalledFunction();
1060  StringRef CalleeNm = CalleeFn->getName();
1061  AttributeList CalleeAt = CalleeFn->getAttributes();
1062  if (CalleeFn && !CalleeFn->isIntrinsic()) {
1063  const Function *Fn = CI->getFunction();
1064  StringRef FnName = Fn->getName();
1065  if (FnName.back() == 'f' &&
1066  FnName.size() == (CalleeNm.size() + 1) &&
1067  FnName.startswith(CalleeNm))
1068  return nullptr;
1069  }
1070 
1071  // Propagate the math semantics from the current function to the new function.
1074 
1075  // g((double) float) -> (double) gf(float)
1076  Value *R;
1077  if (CalleeFn->isIntrinsic()) {
1078  Module *M = CI->getModule();
1079  Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1080  Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1081  R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
1082  }
1083  else
1084  R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1085  : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
1086 
1087  return B.CreateFPExt(R, B.getDoubleTy());
1088 }
1089 
1090 /// Shrink double -> float for unary functions.
1092  bool isPrecise = false) {
1093  return optimizeDoubleFP(CI, B, false, isPrecise);
1094 }
1095 
1096 /// Shrink double -> float for binary functions.
1098  bool isPrecise = false) {
1099  return optimizeDoubleFP(CI, B, true, isPrecise);
1100 }
1101 
1102 // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1103 Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1104  if (!CI->isFast())
1105  return nullptr;
1106 
1107  // Propagate fast-math flags from the existing call to new instructions.
1110 
1111  Value *Real, *Imag;
1112  if (CI->getNumArgOperands() == 1) {
1113  Value *Op = CI->getArgOperand(0);
1114  assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1115  Real = B.CreateExtractValue(Op, 0, "real");
1116  Imag = B.CreateExtractValue(Op, 1, "imag");
1117  } else {
1118  assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1119  Real = CI->getArgOperand(0);
1120  Imag = CI->getArgOperand(1);
1121  }
1122 
1123  Value *RealReal = B.CreateFMul(Real, Real);
1124  Value *ImagImag = B.CreateFMul(Imag, Imag);
1125 
1127  CI->getType());
1128  return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1129 }
1130 
1132  IRBuilder<> &B) {
1133  if (!isa<FPMathOperator>(Call))
1134  return nullptr;
1135 
1138 
1139  // TODO: Can this be shared to also handle LLVM intrinsics?
1140  Value *X;
1141  switch (Func) {
1142  case LibFunc_sin:
1143  case LibFunc_sinf:
1144  case LibFunc_sinl:
1145  case LibFunc_tan:
1146  case LibFunc_tanf:
1147  case LibFunc_tanl:
1148  // sin(-X) --> -sin(X)
1149  // tan(-X) --> -tan(X)
1150  if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
1151  return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
1152  break;
1153  case LibFunc_cos:
1154  case LibFunc_cosf:
1155  case LibFunc_cosl:
1156  // cos(-X) --> cos(X)
1157  if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1158  return B.CreateCall(Call->getCalledFunction(), X, "cos");
1159  break;
1160  default:
1161  break;
1162  }
1163  return nullptr;
1164 }
1165 
1166 static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1167  // Multiplications calculated using Addition Chains.
1168  // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1169 
1170  assert(Exp != 0 && "Incorrect exponent 0 not handled");
1171 
1172  if (InnerChain[Exp])
1173  return InnerChain[Exp];
1174 
1175  static const unsigned AddChain[33][2] = {
1176  {0, 0}, // Unused.
1177  {0, 0}, // Unused (base case = pow1).
1178  {1, 1}, // Unused (pre-computed).
1179  {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1180  {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1181  {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1182  {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1183  {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1184  };
1185 
1186  InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1187  getPow(InnerChain, AddChain[Exp][1], B));
1188  return InnerChain[Exp];
1189 }
1190 
1191 /// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
1192 /// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x).
1193 Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1194  Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1196  Module *Mod = Pow->getModule();
1197  Type *Ty = Pow->getType();
1198  bool Ignored;
1199 
1200  // Evaluate special cases related to a nested function as the base.
1201 
1202  // pow(exp(x), y) -> exp(x * y)
1203  // pow(exp2(x), y) -> exp2(x * y)
1204  // If exp{,2}() is used only once, it is better to fold two transcendental
1205  // math functions into one. If used again, exp{,2}() would still have to be
1206  // called with the original argument, then keep both original transcendental
1207  // functions. However, this transformation is only safe with fully relaxed
1208  // math semantics, since, besides rounding differences, it changes overflow
1209  // and underflow behavior quite dramatically. For example:
1210  // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1211  // Whereas:
1212  // exp(1000 * 0.001) = exp(1)
1213  // TODO: Loosen the requirement for fully relaxed math semantics.
1214  // TODO: Handle exp10() when more targets have it available.
1215  CallInst *BaseFn = dyn_cast<CallInst>(Base);
1216  if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
1217  LibFunc LibFn;
1218 
1219  Function *CalleeFn = BaseFn->getCalledFunction();
1220  if (CalleeFn &&
1221  TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1222  StringRef ExpName;
1223  Intrinsic::ID ID;
1224  Value *ExpFn;
1225  LibFunc LibFnFloat;
1226  LibFunc LibFnDouble;
1227  LibFunc LibFnLongDouble;
1228 
1229  switch (LibFn) {
1230  default:
1231  return nullptr;
1232  case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
1233  ExpName = TLI->getName(LibFunc_exp);
1234  ID = Intrinsic::exp;
1235  LibFnFloat = LibFunc_expf;
1236  LibFnDouble = LibFunc_exp;
1237  LibFnLongDouble = LibFunc_expl;
1238  break;
1239  case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
1240  ExpName = TLI->getName(LibFunc_exp2);
1241  ID = Intrinsic::exp2;
1242  LibFnFloat = LibFunc_exp2f;
1243  LibFnDouble = LibFunc_exp2;
1244  LibFnLongDouble = LibFunc_exp2l;
1245  break;
1246  }
1247 
1248  // Create new exp{,2}() with the product as its argument.
1249  Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
1250  ExpFn = BaseFn->doesNotAccessMemory()
1251  ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1252  FMul, ExpName)
1253  : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1254  LibFnLongDouble, B,
1255  BaseFn->getAttributes());
1256 
1257  // Since the new exp{,2}() is different from the original one, dead code
1258  // elimination cannot be trusted to remove it, since it may have side
1259  // effects (e.g., errno). When the only consumer for the original
1260  // exp{,2}() is pow(), then it has to be explicitly erased.
1261  BaseFn->replaceAllUsesWith(ExpFn);
1262  eraseFromParent(BaseFn);
1263 
1264  return ExpFn;
1265  }
1266  }
1267 
1268  // Evaluate special cases related to a constant base.
1269 
1270  const APFloat *BaseF;
1271  if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1272  return nullptr;
1273 
1274  // pow(2.0 ** n, x) -> exp2(n * x)
1275  if (hasUnaryFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1276  APFloat BaseR = APFloat(1.0);
1277  BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1278  BaseR = BaseR / *BaseF;
1279  bool IsInteger = BaseF->isInteger(),
1280  IsReciprocal = BaseR.isInteger();
1281  const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1282  APSInt NI(64, false);
1283  if ((IsInteger || IsReciprocal) &&
1284  !NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) &&
1285  NI > 1 && NI.isPowerOf2()) {
1286  double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1287  Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1288  if (Pow->doesNotAccessMemory())
1290  FMul, "exp2");
1291  else
1292  return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1293  LibFunc_exp2l, B, Attrs);
1294  }
1295  }
1296 
1297  // pow(10.0, x) -> exp10(x)
1298  // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1299  if (match(Base, m_SpecificFP(10.0)) &&
1300  hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
1301  return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1302  LibFunc_exp10l, B, Attrs);
1303 
1304  return nullptr;
1305 }
1306 
1307 static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1308  Module *M, IRBuilder<> &B,
1309  const TargetLibraryInfo *TLI) {
1310  // If errno is never set, then use the intrinsic for sqrt().
1311  if (NoErrno) {
1312  Function *SqrtFn =
1314  return B.CreateCall(SqrtFn, V, "sqrt");
1315  }
1316 
1317  // Otherwise, use the libcall for sqrt().
1318  if (hasUnaryFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1319  LibFunc_sqrtl))
1320  // TODO: We also should check that the target can in fact lower the sqrt()
1321  // libcall. We currently have no way to ask this question, so we ask if
1322  // the target has a sqrt() libcall, which is not exactly the same.
1323  return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1324  LibFunc_sqrtl, B, Attrs);
1325 
1326  return nullptr;
1327 }
1328 
1329 /// Use square root in place of pow(x, +/-0.5).
1330 Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1331  Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1333  Module *Mod = Pow->getModule();
1334  Type *Ty = Pow->getType();
1335 
1336  const APFloat *ExpoF;
1337  if (!match(Expo, m_APFloat(ExpoF)) ||
1338  (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1339  return nullptr;
1340 
1341  Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1342  if (!Sqrt)
1343  return nullptr;
1344 
1345  // Handle signed zero base by expanding to fabs(sqrt(x)).
1346  if (!Pow->hasNoSignedZeros()) {
1348  Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1349  }
1350 
1351  // Handle non finite base by expanding to
1352  // (x == -infinity ? +infinity : sqrt(x)).
1353  if (!Pow->hasNoInfs()) {
1354  Value *PosInf = ConstantFP::getInfinity(Ty),
1355  *NegInf = ConstantFP::getInfinity(Ty, true);
1356  Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1357  Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1358  }
1359 
1360  // If the exponent is negative, then get the reciprocal.
1361  if (ExpoF->isNegative())
1362  Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
1363 
1364  return Sqrt;
1365 }
1366 
1367 Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1368  Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1369  Function *Callee = Pow->getCalledFunction();
1370  StringRef Name = Callee->getName();
1371  Type *Ty = Pow->getType();
1372  Value *Shrunk = nullptr;
1373  bool Ignored;
1374 
1375  // Bail out if simplifying libcalls to pow() is disabled.
1376  if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1377  return nullptr;
1378 
1379  // Propagate the math semantics from the call to any created instructions.
1382 
1383  // Shrink pow() to powf() if the arguments are single precision,
1384  // unless the result is expected to be double precision.
1385  if (UnsafeFPShrink &&
1386  Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1387  Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1388 
1389  // Evaluate special cases related to the base.
1390 
1391  // pow(1.0, x) -> 1.0
1392  if (match(Base, m_FPOne()))
1393  return Base;
1394 
1395  if (Value *Exp = replacePowWithExp(Pow, B))
1396  return Exp;
1397 
1398  // Evaluate special cases related to the exponent.
1399 
1400  // pow(x, -1.0) -> 1.0 / x
1401  if (match(Expo, m_SpecificFP(-1.0)))
1402  return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1403 
1404  // pow(x, 0.0) -> 1.0
1405  if (match(Expo, m_SpecificFP(0.0)))
1406  return ConstantFP::get(Ty, 1.0);
1407 
1408  // pow(x, 1.0) -> x
1409  if (match(Expo, m_FPOne()))
1410  return Base;
1411 
1412  // pow(x, 2.0) -> x * x
1413  if (match(Expo, m_SpecificFP(2.0)))
1414  return B.CreateFMul(Base, Base, "square");
1415 
1416  if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1417  return Sqrt;
1418 
1419  // pow(x, n) -> x * x * x * ...
1420  const APFloat *ExpoF;
1421  if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
1422  // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
1423  // If the exponent is an integer+0.5 we generate a call to sqrt and an
1424  // additional fmul.
1425  // TODO: This whole transformation should be backend specific (e.g. some
1426  // backends might prefer libcalls or the limit for the exponent might
1427  // be different) and it should also consider optimizing for size.
1428  APFloat LimF(ExpoF->getSemantics(), 33.0),
1429  ExpoA(abs(*ExpoF));
1430  if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1431  // This transformation applies to integer or integer+0.5 exponents only.
1432  // For integer+0.5, we create a sqrt(Base) call.
1433  Value *Sqrt = nullptr;
1434  if (!ExpoA.isInteger()) {
1435  APFloat Expo2 = ExpoA;
1436  // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1437  // is no floating point exception and the result is an integer, then
1438  // ExpoA == integer + 0.5
1439  if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1440  return nullptr;
1441 
1442  if (!Expo2.isInteger())
1443  return nullptr;
1444 
1445  Sqrt =
1447  Pow->doesNotAccessMemory(), Pow->getModule(), B, TLI);
1448  }
1449 
1450  // We will memoize intermediate products of the Addition Chain.
1451  Value *InnerChain[33] = {nullptr};
1452  InnerChain[1] = Base;
1453  InnerChain[2] = B.CreateFMul(Base, Base, "square");
1454 
1455  // We cannot readily convert a non-double type (like float) to a double.
1456  // So we first convert it to something which could be converted to double.
1458  Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
1459 
1460  // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1461  if (Sqrt)
1462  FMul = B.CreateFMul(FMul, Sqrt);
1463 
1464  // If the exponent is negative, then get the reciprocal.
1465  if (ExpoF->isNegative())
1466  FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
1467 
1468  return FMul;
1469  }
1470  }
1471 
1472  return Shrunk;
1473 }
1474 
1475 Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1477  Value *Ret = nullptr;
1478  StringRef Name = Callee->getName();
1479  if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
1480  Ret = optimizeUnaryDoubleFP(CI, B, true);
1481 
1482  Value *Op = CI->getArgOperand(0);
1483  // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1484  // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1485  LibFunc LdExp = LibFunc_ldexpl;
1486  if (Op->getType()->isFloatTy())
1487  LdExp = LibFunc_ldexpf;
1488  else if (Op->getType()->isDoubleTy())
1489  LdExp = LibFunc_ldexp;
1490 
1491  if (TLI->has(LdExp)) {
1492  Value *LdExpArg = nullptr;
1493  if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1494  if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1495  LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1496  } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1497  if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1498  LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1499  }
1500 
1501  if (LdExpArg) {
1502  Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1503  if (!Op->getType()->isFloatTy())
1504  One = ConstantExpr::getFPExtend(One, Op->getType());
1505 
1506  Module *M = CI->getModule();
1507  Value *NewCallee =
1508  M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1509  Op->getType(), B.getInt32Ty());
1510  CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
1511  if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1512  CI->setCallingConv(F->getCallingConv());
1513 
1514  return CI;
1515  }
1516  }
1517  return Ret;
1518 }
1519 
1520 Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1522  // If we can shrink the call to a float function rather than a double
1523  // function, do that first.
1524  StringRef Name = Callee->getName();
1525  if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1526  if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
1527  return Ret;
1528 
1530  FastMathFlags FMF;
1531  if (CI->isFast()) {
1532  // If the call is 'fast', then anything we create here will also be 'fast'.
1533  FMF.setFast();
1534  } else {
1535  // At a minimum, no-nans-fp-math must be true.
1536  if (!CI->hasNoNaNs())
1537  return nullptr;
1538  // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1539  // "Ideally, fmax would be sensitive to the sign of zero, for example
1540  // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
1541  // might be impractical."
1542  FMF.setNoSignedZeros();
1543  FMF.setNoNaNs();
1544  }
1545  B.setFastMathFlags(FMF);
1546 
1547  // We have a relaxed floating-point environment. We can ignore NaN-handling
1548  // and transform to a compare and select. We do not have to consider errno or
1549  // exceptions, because fmin/fmax do not have those.
1550  Value *Op0 = CI->getArgOperand(0);
1551  Value *Op1 = CI->getArgOperand(1);
1552  Value *Cmp = Callee->getName().startswith("fmin") ?
1553  B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1554  return B.CreateSelect(Cmp, Op0, Op1);
1555 }
1556 
1557 Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1559  Value *Ret = nullptr;
1560  StringRef Name = Callee->getName();
1561  if (UnsafeFPShrink && hasFloatVersion(Name))
1562  Ret = optimizeUnaryDoubleFP(CI, B, true);
1563 
1564  if (!CI->isFast())
1565  return Ret;
1566  Value *Op1 = CI->getArgOperand(0);
1567  auto *OpC = dyn_cast<CallInst>(Op1);
1568 
1569  // The earlier call must also be 'fast' in order to do these transforms.
1570  if (!OpC || !OpC->isFast())
1571  return Ret;
1572 
1573  // log(pow(x,y)) -> y*log(x)
1574  // This is only applicable to log, log2, log10.
1575  if (Name != "log" && Name != "log2" && Name != "log10")
1576  return Ret;
1577 
1579  FastMathFlags FMF;
1580  FMF.setFast();
1581  B.setFastMathFlags(FMF);
1582 
1583  LibFunc Func;
1584  Function *F = OpC->getCalledFunction();
1585  if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1586  Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
1587  return B.CreateFMul(OpC->getArgOperand(1),
1588  emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1589  Callee->getAttributes()), "mul");
1590 
1591  // log(exp2(y)) -> y*log(2)
1592  if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1593  TLI->has(Func) && Func == LibFunc_exp2)
1594  return B.CreateFMul(
1595  OpC->getArgOperand(0),
1597  Callee->getName(), B, Callee->getAttributes()),
1598  "logmul");
1599  return Ret;
1600 }
1601 
1602 Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1604  Value *Ret = nullptr;
1605  // TODO: Once we have a way (other than checking for the existince of the
1606  // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1607  // condition below.
1608  if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
1609  Callee->getIntrinsicID() == Intrinsic::sqrt))
1610  Ret = optimizeUnaryDoubleFP(CI, B, true);
1611 
1612  if (!CI->isFast())
1613  return Ret;
1614 
1616  if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
1617  return Ret;
1618 
1619  // We're looking for a repeated factor in a multiplication tree,
1620  // so we can do this fold: sqrt(x * x) -> fabs(x);
1621  // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
1622  Value *Op0 = I->getOperand(0);
1623  Value *Op1 = I->getOperand(1);
1624  Value *RepeatOp = nullptr;
1625  Value *OtherOp = nullptr;
1626  if (Op0 == Op1) {
1627  // Simple match: the operands of the multiply are identical.
1628  RepeatOp = Op0;
1629  } else {
1630  // Look for a more complicated pattern: one of the operands is itself
1631  // a multiply, so search for a common factor in that multiply.
1632  // Note: We don't bother looking any deeper than this first level or for
1633  // variations of this pattern because instcombine's visitFMUL and/or the
1634  // reassociation pass should give us this form.
1635  Value *OtherMul0, *OtherMul1;
1636  if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1637  // Pattern: sqrt((x * y) * z)
1638  if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
1639  // Matched: sqrt((x * x) * z)
1640  RepeatOp = OtherMul0;
1641  OtherOp = Op1;
1642  }
1643  }
1644  }
1645  if (!RepeatOp)
1646  return Ret;
1647 
1648  // Fast math flags for any created instructions should match the sqrt
1649  // and multiply.
1652 
1653  // If we found a repeated factor, hoist it out of the square root and
1654  // replace it with the fabs of that factor.
1655  Module *M = Callee->getParent();
1656  Type *ArgType = I->getType();
1657  Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1658  Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1659  if (OtherOp) {
1660  // If we found a non-repeated factor, we still need to get its square
1661  // root. We then multiply that by the value that was simplified out
1662  // of the square root calculation.
1663  Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1664  Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1665  return B.CreateFMul(FabsCall, SqrtCall);
1666  }
1667  return FabsCall;
1668 }
1669 
1670 // TODO: Generalize to handle any trig function and its inverse.
1671 Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1673  Value *Ret = nullptr;
1674  StringRef Name = Callee->getName();
1675  if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
1676  Ret = optimizeUnaryDoubleFP(CI, B, true);
1677 
1678  Value *Op1 = CI->getArgOperand(0);
1679  auto *OpC = dyn_cast<CallInst>(Op1);
1680  if (!OpC)
1681  return Ret;
1682 
1683  // Both calls must be 'fast' in order to remove them.
1684  if (!CI->isFast() || !OpC->isFast())
1685  return Ret;
1686 
1687  // tan(atan(x)) -> x
1688  // tanf(atanf(x)) -> x
1689  // tanl(atanl(x)) -> x
1690  LibFunc Func;
1691  Function *F = OpC->getCalledFunction();
1692  if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1693  ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1694  (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1695  (Func == LibFunc_atanl && Callee->getName() == "tanl")))
1696  Ret = OpC->getArgOperand(0);
1697  return Ret;
1698 }
1699 
1700 static bool isTrigLibCall(CallInst *CI) {
1701  // We can only hope to do anything useful if we can ignore things like errno
1702  // and floating-point exceptions.
1703  // We already checked the prototype.
1704  return CI->hasFnAttr(Attribute::NoUnwind) &&
1706 }
1707 
1708 static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1709  bool UseFloat, Value *&Sin, Value *&Cos,
1710  Value *&SinCos) {
1711  Type *ArgTy = Arg->getType();
1712  Type *ResTy;
1713  StringRef Name;
1714 
1715  Triple T(OrigCallee->getParent()->getTargetTriple());
1716  if (UseFloat) {
1717  Name = "__sincospif_stret";
1718 
1719  assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1720  // x86_64 can't use {float, float} since that would be returned in both
1721  // xmm0 and xmm1, which isn't what a real struct would do.
1722  ResTy = T.getArch() == Triple::x86_64
1723  ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1724  : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
1725  } else {
1726  Name = "__sincospi_stret";
1727  ResTy = StructType::get(ArgTy, ArgTy);
1728  }
1729 
1730  Module *M = OrigCallee->getParent();
1731  Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1732  ResTy, ArgTy);
1733 
1734  if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1735  // If the argument is an instruction, it must dominate all uses so put our
1736  // sincos call there.
1737  B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1738  } else {
1739  // Otherwise (e.g. for a constant) the beginning of the function is as
1740  // good a place as any.
1741  BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1742  B.SetInsertPoint(&EntryBB, EntryBB.begin());
1743  }
1744 
1745  SinCos = B.CreateCall(Callee, Arg, "sincospi");
1746 
1747  if (SinCos->getType()->isStructTy()) {
1748  Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1749  Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1750  } else {
1751  Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1752  "sinpi");
1753  Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1754  "cospi");
1755  }
1756 }
1757 
1758 Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1759  // Make sure the prototype is as expected, otherwise the rest of the
1760  // function is probably invalid and likely to abort.
1761  if (!isTrigLibCall(CI))
1762  return nullptr;
1763 
1764  Value *Arg = CI->getArgOperand(0);
1765  SmallVector<CallInst *, 1> SinCalls;
1766  SmallVector<CallInst *, 1> CosCalls;
1767  SmallVector<CallInst *, 1> SinCosCalls;
1768 
1769  bool IsFloat = Arg->getType()->isFloatTy();
1770 
1771  // Look for all compatible sinpi, cospi and sincospi calls with the same
1772  // argument. If there are enough (in some sense) we can make the
1773  // substitution.
1774  Function *F = CI->getFunction();
1775  for (User *U : Arg->users())
1776  classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
1777 
1778  // It's only worthwhile if both sinpi and cospi are actually used.
1779  if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1780  return nullptr;
1781 
1782  Value *Sin, *Cos, *SinCos;
1783  insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1784 
1785  auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1786  Value *Res) {
1787  for (CallInst *C : Calls)
1788  replaceAllUsesWith(C, Res);
1789  };
1790 
1791  replaceTrigInsts(SinCalls, Sin);
1792  replaceTrigInsts(CosCalls, Cos);
1793  replaceTrigInsts(SinCosCalls, SinCos);
1794 
1795  return nullptr;
1796 }
1797 
1798 void LibCallSimplifier::classifyArgUse(
1799  Value *Val, Function *F, bool IsFloat,
1800  SmallVectorImpl<CallInst *> &SinCalls,
1801  SmallVectorImpl<CallInst *> &CosCalls,
1802  SmallVectorImpl<CallInst *> &SinCosCalls) {
1803  CallInst *CI = dyn_cast<CallInst>(Val);
1804 
1805  if (!CI)
1806  return;
1807 
1808  // Don't consider calls in other functions.
1809  if (CI->getFunction() != F)
1810  return;
1811 
1813  LibFunc Func;
1814  if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
1815  !isTrigLibCall(CI))
1816  return;
1817 
1818  if (IsFloat) {
1819  if (Func == LibFunc_sinpif)
1820  SinCalls.push_back(CI);
1821  else if (Func == LibFunc_cospif)
1822  CosCalls.push_back(CI);
1823  else if (Func == LibFunc_sincospif_stret)
1824  SinCosCalls.push_back(CI);
1825  } else {
1826  if (Func == LibFunc_sinpi)
1827  SinCalls.push_back(CI);
1828  else if (Func == LibFunc_cospi)
1829  CosCalls.push_back(CI);
1830  else if (Func == LibFunc_sincospi_stret)
1831  SinCosCalls.push_back(CI);
1832  }
1833 }
1834 
1835 //===----------------------------------------------------------------------===//
1836 // Integer Library Call Optimizations
1837 //===----------------------------------------------------------------------===//
1838 
1839 Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1840  // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1841  Value *Op = CI->getArgOperand(0);
1842  Type *ArgType = Op->getType();
1844  Intrinsic::cttz, ArgType);
1845  Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
1846  V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1847  V = B.CreateIntCast(V, B.getInt32Ty(), false);
1848 
1849  Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1850  return B.CreateSelect(Cond, V, B.getInt32(0));
1851 }
1852 
1853 Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1854  // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1855  Value *Op = CI->getArgOperand(0);
1856  Type *ArgType = Op->getType();
1858  Intrinsic::ctlz, ArgType);
1859  Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1860  V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1861  V);
1862  return B.CreateIntCast(V, CI->getType(), false);
1863 }
1864 
1865 Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1866  // abs(x) -> x <s 0 ? -x : x
1867  // The negation has 'nsw' because abs of INT_MIN is undefined.
1868  Value *X = CI->getArgOperand(0);
1869  Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1870  Value *NegX = B.CreateNSWNeg(X, "neg");
1871  return B.CreateSelect(IsNeg, NegX, X);
1872 }
1873 
1874 Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1875  // isdigit(c) -> (c-'0') <u 10
1876  Value *Op = CI->getArgOperand(0);
1877  Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1878  Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1879  return B.CreateZExt(Op, CI->getType());
1880 }
1881 
1882 Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1883  // isascii(c) -> c <u 128
1884  Value *Op = CI->getArgOperand(0);
1885  Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1886  return B.CreateZExt(Op, CI->getType());
1887 }
1888 
1889 Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1890  // toascii(c) -> c & 0x7f
1891  return B.CreateAnd(CI->getArgOperand(0),
1892  ConstantInt::get(CI->getType(), 0x7F));
1893 }
1894 
1895 Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1896  StringRef Str;
1897  if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1898  return nullptr;
1899 
1900  return convertStrToNumber(CI, Str, 10);
1901 }
1902 
1903 Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1904  StringRef Str;
1905  if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1906  return nullptr;
1907 
1908  if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1909  return nullptr;
1910 
1911  if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1912  return convertStrToNumber(CI, Str, CInt->getSExtValue());
1913  }
1914 
1915  return nullptr;
1916 }
1917 
1918 //===----------------------------------------------------------------------===//
1919 // Formatting and IO Library Call Optimizations
1920 //===----------------------------------------------------------------------===//
1921 
1922 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
1923 
1924 Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1925  int StreamArg) {
1926  Function *Callee = CI->getCalledFunction();
1927  // Error reporting calls should be cold, mark them as such.
1928  // This applies even to non-builtin calls: it is only a hint and applies to
1929  // functions that the frontend might not understand as builtins.
1930 
1931  // This heuristic was suggested in:
1932  // Improving Static Branch Prediction in a Compiler
1933  // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1934  // Proceedings of PACT'98, Oct. 1998, IEEE
1935  if (!CI->hasFnAttr(Attribute::Cold) &&
1936  isReportingError(Callee, CI, StreamArg)) {
1938  }
1939 
1940  return nullptr;
1941 }
1942 
1943 static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1944  if (!Callee || !Callee->isDeclaration())
1945  return false;
1946 
1947  if (StreamArg < 0)
1948  return true;
1949 
1950  // These functions might be considered cold, but only if their stream
1951  // argument is stderr.
1952 
1953  if (StreamArg >= (int)CI->getNumArgOperands())
1954  return false;
1955  LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1956  if (!LI)
1957  return false;
1959  if (!GV || !GV->isDeclaration())
1960  return false;
1961  return GV->getName() == "stderr";
1962 }
1963 
1964 Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1965  // Check for a fixed format string.
1966  StringRef FormatStr;
1967  if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1968  return nullptr;
1969 
1970  // Empty format string -> noop.
1971  if (FormatStr.empty()) // Tolerate printf's declared void.
1972  return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
1973 
1974  // Do not do any of the following transformations if the printf return value
1975  // is used, in general the printf return value is not compatible with either
1976  // putchar() or puts().
1977  if (!CI->use_empty())
1978  return nullptr;
1979 
1980  // printf("x") -> putchar('x'), even for "%" and "%%".
1981  if (FormatStr.size() == 1 || FormatStr == "%%")
1982  return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
1983 
1984  // printf("%s", "a") --> putchar('a')
1985  if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1986  StringRef ChrStr;
1987  if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1988  return nullptr;
1989  if (ChrStr.size() != 1)
1990  return nullptr;
1991  return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
1992  }
1993 
1994  // printf("foo\n") --> puts("foo")
1995  if (FormatStr[FormatStr.size() - 1] == '\n' &&
1996  FormatStr.find('%') == StringRef::npos) { // No format characters.
1997  // Create a string literal with no \n on it. We expect the constant merge
1998  // pass to be run after this pass, to merge duplicate strings.
1999  FormatStr = FormatStr.drop_back();
2000  Value *GV = B.CreateGlobalString(FormatStr, "str");
2001  return emitPutS(GV, B, TLI);
2002  }
2003 
2004  // Optimize specific format strings.
2005  // printf("%c", chr) --> putchar(chr)
2006  if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
2007  CI->getArgOperand(1)->getType()->isIntegerTy())
2008  return emitPutChar(CI->getArgOperand(1), B, TLI);
2009 
2010  // printf("%s\n", str) --> puts(str)
2011  if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
2012  CI->getArgOperand(1)->getType()->isPointerTy())
2013  return emitPutS(CI->getArgOperand(1), B, TLI);
2014  return nullptr;
2015 }
2016 
2017 Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2018 
2019  Function *Callee = CI->getCalledFunction();
2020  FunctionType *FT = Callee->getFunctionType();
2021  if (Value *V = optimizePrintFString(CI, B)) {
2022  return V;
2023  }
2024 
2025  // printf(format, ...) -> iprintf(format, ...) if no floating point
2026  // arguments.
2027  if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
2028  Module *M = B.GetInsertBlock()->getParent()->getParent();
2029  Constant *IPrintFFn =
2030  M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
2031  CallInst *New = cast<CallInst>(CI->clone());
2032  New->setCalledFunction(IPrintFFn);
2033  B.Insert(New);
2034  return New;
2035  }
2036  return nullptr;
2037 }
2038 
2039 Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2040  // Check for a fixed format string.
2041  StringRef FormatStr;
2042  if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2043  return nullptr;
2044 
2045  // If we just have a format string (nothing else crazy) transform it.
2046  if (CI->getNumArgOperands() == 2) {
2047  // Make sure there's no % in the constant array. We could try to handle
2048  // %% -> % in the future if we cared.
2049  if (FormatStr.find('%') != StringRef::npos)
2050  return nullptr; // we found a format specifier, bail out.
2051 
2052  // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2053  B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2054  ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2055  FormatStr.size() + 1)); // Copy the null byte.
2056  return ConstantInt::get(CI->getType(), FormatStr.size());
2057  }
2058 
2059  // The remaining optimizations require the format string to be "%s" or "%c"
2060  // and have an extra operand.
2061  if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2062  CI->getNumArgOperands() < 3)
2063  return nullptr;
2064 
2065  // Decode the second character of the format string.
2066  if (FormatStr[1] == 'c') {
2067  // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2068  if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2069  return nullptr;
2070  Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2071  Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2072  B.CreateStore(V, Ptr);
2073  Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2074  B.CreateStore(B.getInt8(0), Ptr);
2075 
2076  return ConstantInt::get(CI->getType(), 1);
2077  }
2078 
2079  if (FormatStr[1] == 's') {
2080  // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
2081  if (!CI->getArgOperand(2)->getType()->isPointerTy())
2082  return nullptr;
2083 
2084  Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
2085  if (!Len)
2086  return nullptr;
2087  Value *IncLen =
2088  B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2089  B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
2090 
2091  // The sprintf result is the unincremented number of bytes in the string.
2092  return B.CreateIntCast(Len, CI->getType(), false);
2093  }
2094  return nullptr;
2095 }
2096 
2097 Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2098  Function *Callee = CI->getCalledFunction();
2099  FunctionType *FT = Callee->getFunctionType();
2100  if (Value *V = optimizeSPrintFString(CI, B)) {
2101  return V;
2102  }
2103 
2104  // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2105  // point arguments.
2106  if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
2107  Module *M = B.GetInsertBlock()->getParent()->getParent();
2108  Constant *SIPrintFFn =
2109  M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2110  CallInst *New = cast<CallInst>(CI->clone());
2111  New->setCalledFunction(SIPrintFFn);
2112  B.Insert(New);
2113  return New;
2114  }
2115  return nullptr;
2116 }
2117 
2118 Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2119  // Check for a fixed format string.
2120  StringRef FormatStr;
2121  if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2122  return nullptr;
2123 
2124  // Check for size
2126  if (!Size)
2127  return nullptr;
2128 
2129  uint64_t N = Size->getZExtValue();
2130 
2131  // If we just have a format string (nothing else crazy) transform it.
2132  if (CI->getNumArgOperands() == 3) {
2133  // Make sure there's no % in the constant array. We could try to handle
2134  // %% -> % in the future if we cared.
2135  if (FormatStr.find('%') != StringRef::npos)
2136  return nullptr; // we found a format specifier, bail out.
2137 
2138  if (N == 0)
2139  return ConstantInt::get(CI->getType(), FormatStr.size());
2140  else if (N < FormatStr.size() + 1)
2141  return nullptr;
2142 
2143  // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
2144  // strlen(fmt)+1)
2145  B.CreateMemCpy(
2146  CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2147  ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2148  FormatStr.size() + 1)); // Copy the null byte.
2149  return ConstantInt::get(CI->getType(), FormatStr.size());
2150  }
2151 
2152  // The remaining optimizations require the format string to be "%s" or "%c"
2153  // and have an extra operand.
2154  if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2155  CI->getNumArgOperands() == 4) {
2156 
2157  // Decode the second character of the format string.
2158  if (FormatStr[1] == 'c') {
2159  if (N == 0)
2160  return ConstantInt::get(CI->getType(), 1);
2161  else if (N == 1)
2162  return nullptr;
2163 
2164  // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2165  if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2166  return nullptr;
2167  Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2168  Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2169  B.CreateStore(V, Ptr);
2170  Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2171  B.CreateStore(B.getInt8(0), Ptr);
2172 
2173  return ConstantInt::get(CI->getType(), 1);
2174  }
2175 
2176  if (FormatStr[1] == 's') {
2177  // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2178  StringRef Str;
2179  if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2180  return nullptr;
2181 
2182  if (N == 0)
2183  return ConstantInt::get(CI->getType(), Str.size());
2184  else if (N < Str.size() + 1)
2185  return nullptr;
2186 
2187  B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2188  ConstantInt::get(CI->getType(), Str.size() + 1));
2189 
2190  // The snprintf result is the unincremented number of bytes in the string.
2191  return ConstantInt::get(CI->getType(), Str.size());
2192  }
2193  }
2194  return nullptr;
2195 }
2196 
2197 Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2198  if (Value *V = optimizeSnPrintFString(CI, B)) {
2199  return V;
2200  }
2201 
2202  return nullptr;
2203 }
2204 
2205 Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2206  optimizeErrorReporting(CI, B, 0);
2207 
2208  // All the optimizations depend on the format string.
2209  StringRef FormatStr;
2210  if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2211  return nullptr;
2212 
2213  // Do not do any of the following transformations if the fprintf return
2214  // value is used, in general the fprintf return value is not compatible
2215  // with fwrite(), fputc() or fputs().
2216  if (!CI->use_empty())
2217  return nullptr;
2218 
2219  // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2220  if (CI->getNumArgOperands() == 2) {
2221  // Could handle %% -> % if we cared.
2222  if (FormatStr.find('%') != StringRef::npos)
2223  return nullptr; // We found a format specifier.
2224 
2225  return emitFWrite(
2226  CI->getArgOperand(1),
2227  ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
2228  CI->getArgOperand(0), B, DL, TLI);
2229  }
2230 
2231  // The remaining optimizations require the format string to be "%s" or "%c"
2232  // and have an extra operand.
2233  if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2234  CI->getNumArgOperands() < 3)
2235  return nullptr;
2236 
2237  // Decode the second character of the format string.
2238  if (FormatStr[1] == 'c') {
2239  // fprintf(F, "%c", chr) --> fputc(chr, F)
2240  if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2241  return nullptr;
2242  return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2243  }
2244 
2245  if (FormatStr[1] == 's') {
2246  // fprintf(F, "%s", str) --> fputs(str, F)
2247  if (!CI->getArgOperand(2)->getType()->isPointerTy())
2248  return nullptr;
2249  return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
2250  }
2251  return nullptr;
2252 }
2253 
2254 Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2255  Function *Callee = CI->getCalledFunction();
2256  FunctionType *FT = Callee->getFunctionType();
2257  if (Value *V = optimizeFPrintFString(CI, B)) {
2258  return V;
2259  }
2260 
2261  // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2262  // floating point arguments.
2263  if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
2264  Module *M = B.GetInsertBlock()->getParent()->getParent();
2265  Constant *FIPrintFFn =
2266  M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2267  CallInst *New = cast<CallInst>(CI->clone());
2268  New->setCalledFunction(FIPrintFFn);
2269  B.Insert(New);
2270  return New;
2271  }
2272  return nullptr;
2273 }
2274 
2275 Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2276  optimizeErrorReporting(CI, B, 3);
2277 
2278  // Get the element size and count.
2279  ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2280  ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2281  if (SizeC && CountC) {
2282  uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2283 
2284  // If this is writing zero records, remove the call (it's a noop).
2285  if (Bytes == 0)
2286  return ConstantInt::get(CI->getType(), 0);
2287 
2288  // If this is writing one byte, turn it into fputc.
2289  // This optimisation is only valid, if the return value is unused.
2290  if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2291  Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2292  Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2293  return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2294  }
2295  }
2296 
2297  if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2298  return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2299  CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2300  TLI);
2301 
2302  return nullptr;
2303 }
2304 
2305 Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2306  optimizeErrorReporting(CI, B, 1);
2307 
2308  // Don't rewrite fputs to fwrite when optimising for size because fwrite
2309  // requires more arguments and thus extra MOVs are required.
2310  if (CI->getFunction()->optForSize())
2311  return nullptr;
2312 
2313  // Check if has any use
2314  if (!CI->use_empty()) {
2315  if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2316  return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2317  TLI);
2318  else
2319  // We can't optimize if return value is used.
2320  return nullptr;
2321  }
2322 
2323  // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2324  uint64_t Len = GetStringLength(CI->getArgOperand(0));
2325  if (!Len)
2326  return nullptr;
2327 
2328  // Known to have no uses (see above).
2329  return emitFWrite(
2330  CI->getArgOperand(0),
2331  ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
2332  CI->getArgOperand(1), B, DL, TLI);
2333 }
2334 
2335 Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2336  optimizeErrorReporting(CI, B, 1);
2337 
2338  if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2339  return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2340  TLI);
2341 
2342  return nullptr;
2343 }
2344 
2345 Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2346  if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2347  return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2348 
2349  return nullptr;
2350 }
2351 
2352 Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2353  if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2354  return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2355  CI->getArgOperand(2), B, TLI);
2356 
2357  return nullptr;
2358 }
2359 
2360 Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2361  if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2362  return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2363  CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2364  TLI);
2365 
2366  return nullptr;
2367 }
2368 
2369 Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2370  // Check for a constant string.
2371  StringRef Str;
2372  if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2373  return nullptr;
2374 
2375  if (Str.empty() && CI->use_empty()) {
2376  // puts("") -> putchar('\n')
2377  Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
2378  if (CI->use_empty() || !Res)
2379  return Res;
2380  return B.CreateIntCast(Res, CI->getType(), true);
2381  }
2382 
2383  return nullptr;
2384 }
2385 
2386 bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
2387  LibFunc Func;
2388  SmallString<20> FloatFuncName = FuncName;
2389  FloatFuncName += 'f';
2390  if (TLI->getLibFunc(FloatFuncName, Func))
2391  return TLI->has(Func);
2392  return false;
2393 }
2394 
2395 Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2396  IRBuilder<> &Builder) {
2397  LibFunc Func;
2398  Function *Callee = CI->getCalledFunction();
2399  // Check for string/memory library functions.
2400  if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2401  // Make sure we never change the calling convention.
2402  assert((ignoreCallingConv(Func) ||
2403  isCallingConvCCompatible(CI)) &&
2404  "Optimizing string/memory libcall would change the calling convention");
2405  switch (Func) {
2406  case LibFunc_strcat:
2407  return optimizeStrCat(CI, Builder);
2408  case LibFunc_strncat:
2409  return optimizeStrNCat(CI, Builder);
2410  case LibFunc_strchr:
2411  return optimizeStrChr(CI, Builder);
2412  case LibFunc_strrchr:
2413  return optimizeStrRChr(CI, Builder);
2414  case LibFunc_strcmp:
2415  return optimizeStrCmp(CI, Builder);
2416  case LibFunc_strncmp:
2417  return optimizeStrNCmp(CI, Builder);
2418  case LibFunc_strcpy:
2419  return optimizeStrCpy(CI, Builder);
2420  case LibFunc_stpcpy:
2421  return optimizeStpCpy(CI, Builder);
2422  case LibFunc_strncpy:
2423  return optimizeStrNCpy(CI, Builder);
2424  case LibFunc_strlen:
2425  return optimizeStrLen(CI, Builder);
2426  case LibFunc_strpbrk:
2427  return optimizeStrPBrk(CI, Builder);
2428  case LibFunc_strtol:
2429  case LibFunc_strtod:
2430  case LibFunc_strtof:
2431  case LibFunc_strtoul:
2432  case LibFunc_strtoll:
2433  case LibFunc_strtold:
2434  case LibFunc_strtoull:
2435  return optimizeStrTo(CI, Builder);
2436  case LibFunc_strspn:
2437  return optimizeStrSpn(CI, Builder);
2438  case LibFunc_strcspn:
2439  return optimizeStrCSpn(CI, Builder);
2440  case LibFunc_strstr:
2441  return optimizeStrStr(CI, Builder);
2442  case LibFunc_memchr:
2443  return optimizeMemChr(CI, Builder);
2444  case LibFunc_memcmp:
2445  return optimizeMemCmp(CI, Builder);
2446  case LibFunc_memcpy:
2447  return optimizeMemCpy(CI, Builder);
2448  case LibFunc_memmove:
2449  return optimizeMemMove(CI, Builder);
2450  case LibFunc_memset:
2451  return optimizeMemSet(CI, Builder);
2452  case LibFunc_realloc:
2453  return optimizeRealloc(CI, Builder);
2454  case LibFunc_wcslen:
2455  return optimizeWcslen(CI, Builder);
2456  default:
2457  break;
2458  }
2459  }
2460  return nullptr;
2461 }
2462 
2463 Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2464  LibFunc Func,
2465  IRBuilder<> &Builder) {
2466  // Don't optimize calls that require strict floating point semantics.
2467  if (CI->isStrictFP())
2468  return nullptr;
2469 
2470  if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2471  return V;
2472 
2473  switch (Func) {
2474  case LibFunc_sinpif:
2475  case LibFunc_sinpi:
2476  case LibFunc_cospif:
2477  case LibFunc_cospi:
2478  return optimizeSinCosPi(CI, Builder);
2479  case LibFunc_powf:
2480  case LibFunc_pow:
2481  case LibFunc_powl:
2482  return optimizePow(CI, Builder);
2483  case LibFunc_exp2l:
2484  case LibFunc_exp2:
2485  case LibFunc_exp2f:
2486  return optimizeExp2(CI, Builder);
2487  case LibFunc_fabsf:
2488  case LibFunc_fabs:
2489  case LibFunc_fabsl:
2490  return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2491  case LibFunc_sqrtf:
2492  case LibFunc_sqrt:
2493  case LibFunc_sqrtl:
2494  return optimizeSqrt(CI, Builder);
2495  case LibFunc_log:
2496  case LibFunc_log10:
2497  case LibFunc_log1p:
2498  case LibFunc_log2:
2499  case LibFunc_logb:
2500  return optimizeLog(CI, Builder);
2501  case LibFunc_tan:
2502  case LibFunc_tanf:
2503  case LibFunc_tanl:
2504  return optimizeTan(CI, Builder);
2505  case LibFunc_ceil:
2506  return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2507  case LibFunc_floor:
2508  return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2509  case LibFunc_round:
2510  return replaceUnaryCall(CI, Builder, Intrinsic::round);
2511  case LibFunc_nearbyint:
2512  return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2513  case LibFunc_rint:
2514  return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2515  case LibFunc_trunc:
2516  return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2517  case LibFunc_acos:
2518  case LibFunc_acosh:
2519  case LibFunc_asin:
2520  case LibFunc_asinh:
2521  case LibFunc_atan:
2522  case LibFunc_atanh:
2523  case LibFunc_cbrt:
2524  case LibFunc_cosh:
2525  case LibFunc_exp:
2526  case LibFunc_exp10:
2527  case LibFunc_expm1:
2528  case LibFunc_cos:
2529  case LibFunc_sin:
2530  case LibFunc_sinh:
2531  case LibFunc_tanh:
2532  if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2533  return optimizeUnaryDoubleFP(CI, Builder, true);
2534  return nullptr;
2535  case LibFunc_copysign:
2536  if (hasFloatVersion(CI->getCalledFunction()->getName()))
2537  return optimizeBinaryDoubleFP(CI, Builder);
2538  return nullptr;
2539  case LibFunc_fminf:
2540  case LibFunc_fmin:
2541  case LibFunc_fminl:
2542  case LibFunc_fmaxf:
2543  case LibFunc_fmax:
2544  case LibFunc_fmaxl:
2545  return optimizeFMinFMax(CI, Builder);
2546  case LibFunc_cabs:
2547  case LibFunc_cabsf:
2548  case LibFunc_cabsl:
2549  return optimizeCAbs(CI, Builder);
2550  default:
2551  return nullptr;
2552  }
2553 }
2554 
2556  // TODO: Split out the code below that operates on FP calls so that
2557  // we can all non-FP calls with the StrictFP attribute to be
2558  // optimized.
2559  if (CI->isNoBuiltin())
2560  return nullptr;
2561 
2562  LibFunc Func;
2563  Function *Callee = CI->getCalledFunction();
2564 
2566  CI->getOperandBundlesAsDefs(OpBundles);
2567  IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2568  bool isCallingConvC = isCallingConvCCompatible(CI);
2569 
2570  // Command-line parameter overrides instruction attribute.
2571  // This can't be moved to optimizeFloatingPointLibCall() because it may be
2572  // used by the intrinsic optimizations.
2573  if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2574  UnsafeFPShrink = EnableUnsafeFPShrink;
2575  else if (isa<FPMathOperator>(CI) && CI->isFast())
2576  UnsafeFPShrink = true;
2577 
2578  // First, check for intrinsics.
2579  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2580  if (!isCallingConvC)
2581  return nullptr;
2582  // The FP intrinsics have corresponding constrained versions so we don't
2583  // need to check for the StrictFP attribute here.
2584  switch (II->getIntrinsicID()) {
2585  case Intrinsic::pow:
2586  return optimizePow(CI, Builder);
2587  case Intrinsic::exp2:
2588  return optimizeExp2(CI, Builder);
2589  case Intrinsic::log:
2590  return optimizeLog(CI, Builder);
2591  case Intrinsic::sqrt:
2592  return optimizeSqrt(CI, Builder);
2593  // TODO: Use foldMallocMemset() with memset intrinsic.
2594  default:
2595  return nullptr;
2596  }
2597  }
2598 
2599  // Also try to simplify calls to fortified library functions.
2600  if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2601  // Try to further simplify the result.
2602  CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2603  if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2604  // Use an IR Builder from SimplifiedCI if available instead of CI
2605  // to guarantee we reach all uses we might replace later on.
2606  IRBuilder<> TmpBuilder(SimplifiedCI);
2607  if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
2608  // If we were able to further simplify, remove the now redundant call.
2609  SimplifiedCI->replaceAllUsesWith(V);
2610  eraseFromParent(SimplifiedCI);
2611  return V;
2612  }
2613  }
2614  return SimplifiedFortifiedCI;
2615  }
2616 
2617  // Then check for known library functions.
2618  if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
2619  // We never change the calling convention.
2620  if (!ignoreCallingConv(Func) && !isCallingConvC)
2621  return nullptr;
2622  if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2623  return V;
2624  if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2625  return V;
2626  switch (Func) {
2627  case LibFunc_ffs:
2628  case LibFunc_ffsl:
2629  case LibFunc_ffsll:
2630  return optimizeFFS(CI, Builder);
2631  case LibFunc_fls:
2632  case LibFunc_flsl:
2633  case LibFunc_flsll:
2634  return optimizeFls(CI, Builder);
2635  case LibFunc_abs:
2636  case LibFunc_labs:
2637  case LibFunc_llabs:
2638  return optimizeAbs(CI, Builder);
2639  case LibFunc_isdigit:
2640  return optimizeIsDigit(CI, Builder);
2641  case LibFunc_isascii:
2642  return optimizeIsAscii(CI, Builder);
2643  case LibFunc_toascii:
2644  return optimizeToAscii(CI, Builder);
2645  case LibFunc_atoi:
2646  case LibFunc_atol:
2647  case LibFunc_atoll:
2648  return optimizeAtoi(CI, Builder);
2649  case LibFunc_strtol:
2650  case LibFunc_strtoll:
2651  return optimizeStrtol(CI, Builder);
2652  case LibFunc_printf:
2653  return optimizePrintF(CI, Builder);
2654  case LibFunc_sprintf:
2655  return optimizeSPrintF(CI, Builder);
2656  case LibFunc_snprintf:
2657  return optimizeSnPrintF(CI, Builder);
2658  case LibFunc_fprintf:
2659  return optimizeFPrintF(CI, Builder);
2660  case LibFunc_fwrite:
2661  return optimizeFWrite(CI, Builder);
2662  case LibFunc_fread:
2663  return optimizeFRead(CI, Builder);
2664  case LibFunc_fputs:
2665  return optimizeFPuts(CI, Builder);
2666  case LibFunc_fgets:
2667  return optimizeFGets(CI, Builder);
2668  case LibFunc_fputc:
2669  return optimizeFPutc(CI, Builder);
2670  case LibFunc_fgetc:
2671  return optimizeFGetc(CI, Builder);
2672  case LibFunc_puts:
2673  return optimizePuts(CI, Builder);
2674  case LibFunc_perror:
2675  return optimizeErrorReporting(CI, Builder);
2676  case LibFunc_vfprintf:
2677  case LibFunc_fiprintf:
2678  return optimizeErrorReporting(CI, Builder, 0);
2679  default:
2680  return nullptr;
2681  }
2682  }
2683  return nullptr;
2684 }
2685 
2687  const DataLayout &DL, const TargetLibraryInfo *TLI,
2689  function_ref<void(Instruction *, Value *)> Replacer,
2690  function_ref<void(Instruction *)> Eraser)
2691  : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2692  UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
2693 
2694 void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2695  // Indirect through the replacer used in this instance.
2696  Replacer(I, With);
2697 }
2698 
2699 void LibCallSimplifier::eraseFromParent(Instruction *I) {
2700  Eraser(I);
2701 }
2702 
2703 // TODO:
2704 // Additional cases that we need to add to this file:
2705 //
2706 // cbrt:
2707 // * cbrt(expN(X)) -> expN(x/3)
2708 // * cbrt(sqrt(x)) -> pow(x,1/6)
2709 // * cbrt(cbrt(x)) -> pow(x,1/9)
2710 //
2711 // exp, expf, expl:
2712 // * exp(log(x)) -> x
2713 //
2714 // log, logf, logl:
2715 // * log(exp(x)) -> x
2716 // * log(exp(y)) -> y*log(e)
2717 // * log(exp10(y)) -> y*log(10)
2718 // * log(sqrt(x)) -> 0.5*log(x)
2719 //
2720 // pow, powf, powl:
2721 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2722 // * pow(pow(x,y),z)-> pow(x,y*z)
2723 //
2724 // signbit:
2725 // * signbit(cnst) -> cnst'
2726 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2727 //
2728 // sqrt, sqrtf, sqrtl:
2729 // * sqrt(expN(x)) -> expN(x*0.5)
2730 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2731 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2732 //
2733 
2734 //===----------------------------------------------------------------------===//
2735 // Fortified Library Call Optimizations
2736 //===----------------------------------------------------------------------===//
2737 
2738 bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2739  unsigned ObjSizeOp,
2740  unsigned SizeOp,
2741  bool isString) {
2742  if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2743  return true;
2744  if (ConstantInt *ObjSizeCI =
2745  dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2746  if (ObjSizeCI->isMinusOne())
2747  return true;
2748  // If the object size wasn't -1 (unknown), bail out if we were asked to.
2749  if (OnlyLowerUnknownSize)
2750  return false;
2751  if (isString) {
2752  uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2753  // If the length is 0 we don't know how long it is and so we can't
2754  // remove the check.
2755  if (Len == 0)
2756  return false;
2757  return ObjSizeCI->getZExtValue() >= Len;
2758  }
2759  if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2760  return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2761  }
2762  return false;
2763 }
2764 
2765 Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2766  IRBuilder<> &B) {
2767  if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2768  B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2769  CI->getArgOperand(2));
2770  return CI->getArgOperand(0);
2771  }
2772  return nullptr;
2773 }
2774 
2775 Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2776  IRBuilder<> &B) {
2777  if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2778  B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2779  CI->getArgOperand(2));
2780  return CI->getArgOperand(0);
2781  }
2782  return nullptr;
2783 }
2784 
2785 Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2786  IRBuilder<> &B) {
2787  // TODO: Try foldMallocMemset() here.
2788 
2789  if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2790  Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2791  B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2792  return CI->getArgOperand(0);
2793  }
2794  return nullptr;
2795 }
2796 
2797 Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2798  IRBuilder<> &B,
2799  LibFunc Func) {
2800  Function *Callee = CI->getCalledFunction();
2801  StringRef Name = Callee->getName();
2802  const DataLayout &DL = CI->getModule()->getDataLayout();
2803  Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2804  *ObjSize = CI->getArgOperand(2);
2805 
2806  // __stpcpy_chk(x,x,...) -> x+strlen(x)
2807  if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
2808  Value *StrLen = emitStrLen(Src, B, DL, TLI);
2809  return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
2810  }
2811 
2812  // If a) we don't have any length information, or b) we know this will
2813  // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2814  // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2815  // TODO: It might be nice to get a maximum length out of the possible
2816  // string lengths for varying.
2817  if (isFortifiedCallFoldable(CI, 2, 1, true))
2818  return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
2819 
2820  if (OnlyLowerUnknownSize)
2821  return nullptr;
2822 
2823  // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2824  uint64_t Len = GetStringLength(Src);
2825  if (Len == 0)
2826  return nullptr;
2827 
2828  Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2829  Value *LenV = ConstantInt::get(SizeTTy, Len);
2830  Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2831  // If the function was an __stpcpy_chk, and we were able to fold it into
2832  // a __memcpy_chk, we still need to return the correct end pointer.
2833  if (Ret && Func == LibFunc_stpcpy_chk)
2834  return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2835  return Ret;
2836 }
2837 
2838 Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2839  IRBuilder<> &B,
2840  LibFunc Func) {
2841  Function *Callee = CI->getCalledFunction();
2842  StringRef Name = Callee->getName();
2843  if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2844  Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2845  CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
2846  return Ret;
2847  }
2848  return nullptr;
2849 }
2850 
2852  // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2853  // Some clang users checked for _chk libcall availability using:
2854  // __has_builtin(__builtin___memcpy_chk)
2855  // When compiling with -fno-builtin, this is always true.
2856  // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2857  // end up with fortified libcalls, which isn't acceptable in a freestanding
2858  // environment which only provides their non-fortified counterparts.
2859  //
2860  // Until we change clang and/or teach external users to check for availability
2861  // differently, disregard the "nobuiltin" attribute and TLI::has.
2862  //
2863  // PR23093.
2864 
2865  LibFunc Func;
2866  Function *Callee = CI->getCalledFunction();
2867 
2869  CI->getOperandBundlesAsDefs(OpBundles);
2870  IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
2871  bool isCallingConvC = isCallingConvCCompatible(CI);
2872 
2873  // First, check that this is a known library functions and that the prototype
2874  // is correct.
2875  if (!TLI->getLibFunc(*Callee, Func))
2876  return nullptr;
2877 
2878  // We never change the calling convention.
2879  if (!ignoreCallingConv(Func) && !isCallingConvC)
2880  return nullptr;
2881 
2882  switch (Func) {
2883  case LibFunc_memcpy_chk:
2884  return optimizeMemCpyChk(CI, Builder);
2885  case LibFunc_memmove_chk:
2886  return optimizeMemMoveChk(CI, Builder);
2887  case LibFunc_memset_chk:
2888  return optimizeMemSetChk(CI, Builder);
2889  case LibFunc_stpcpy_chk:
2890  case LibFunc_strcpy_chk:
2891  return optimizeStrpCpyChk(CI, Builder, Func);
2892  case LibFunc_stpncpy_chk:
2893  case LibFunc_strncpy_chk:
2894  return optimizeStrpNCpyChk(CI, Builder, Func);
2895  default:
2896  break;
2897  }
2898  return nullptr;
2899 }
2900 
2902  const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2903  : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}
Value * CreateNSWNeg(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1318
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1477
uint64_t CallInst * C
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:199
bool hasNoInfs() const
Determine whether the no-infs flag is set.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:240
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:71
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1949
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
bool hasNoSignedZeros() const
Determine whether the no-signed-zeros flag is set.
ARM_AAPCS - ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:100
void flipAllBits()
Toggle every bit to its opposite value.
Definition: APInt.h:1477
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:35
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
bool doesNotAccessMemory(unsigned OpNo) const
Definition: InstrTypes.h:1429
void setFast(bool B=true)
Definition: Operator.h:231
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1843
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return an i1 value testing if Arg is not null.
Definition: IRBuilder.h:2116
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1669
This class represents lattice values for constants.
Definition: AllocatorList.h:24
static bool callHasFloatingPointArgument(const CallInst *CI)
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:135
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1855
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:144
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1357
Value * optimizeCall(CallInst *CI)
Take the given call instruction and return a more optimal value to replace the instruction with or 0 ...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:808
LLVM_NODISCARD size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
Definition: StringRef.h:360
void push_back(const T &Elt)
Definition: SmallVector.h:218
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1871
This class represents a function call, abstracting a target machine&#39;s calling convention.
unsigned less than
Definition: InstrTypes.h:671
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:117
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:321
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1663
F(f)
const fltSemantics & getSemantics() const
Definition: APFloat.h:1155
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memset to the specified pointer and the specified value.
Definition: IRBuilder.h:404
An instruction for reading from memory.
Definition: Instructions.h:168
Hexagon Common GEP
static bool isTrigLibCall(CallInst *CI)
Value * emitStrNCpy(Value *Dst, Value *Src, Value *Len, IRBuilder<> &B, const TargetLibraryInfo *TLI, StringRef Name="strncpy")
Emit a call to the strncpy function to the builder, for the specified pointer arguments and length...
bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize=8)
Returns true if the GEP is based on a pointer to a string (array of.
Value * emitFPutSUnlocked(Value *Str, Value *File, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the fputs_unlocked function.
uint64_t Offset
Slice starts at this Offset.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Definition: InstrTypes.h:1261
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:33
Value * emitMalloc(Value *Num, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the malloc function.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg)
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:265
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:269
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:347
static Value * replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID)
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1135
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition: APFloat.h:1069
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
Definition: PatternMatch.h:540
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:48
LibCallSimplifier(const DataLayout &DL, const TargetLibraryInfo *TLI, OptimizationRemarkEmitter &ORE, function_ref< void(Instruction *, Value *)> Replacer=&replaceAllUsesWithDefault, function_ref< void(Instruction *)> Eraser=&eraseFromParentDefault)
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Value * CreateFPExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1718
void setBit(unsigned BitPosition)
Set a given bit to 1.
Definition: APInt.h:1403
This class represents the LLVM &#39;select&#39; instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:369
FortifiedLibCallSimplifier(const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize=false)
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:652
Value * emitPutChar(Value *Char, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the putchar function. This assumes that Char is an integer.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:743
void setCalledFunction(Value *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1210
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1014
CallInst * CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memmove between the specified pointers.
Definition: IRBuilder.h:494
Value * emitUnaryFloatFnCall(Value *Op, StringRef Name, IRBuilder<> &B, const AttributeList &Attrs)
Emit a call to the unary function named &#39;Name&#39; (e.g.
static cl::opt< bool > EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden, cl::init(false), cl::desc("Enable unsafe double to float " "shrinking for math lib calls"))
Value * emitFPutCUnlocked(Value *Char, Value *File, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the fputc_unlocked function.
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:342
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1386
static Value * convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1727
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
Class to represent function types.
Definition: DerivedTypes.h:103
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1732
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1684
apfloat_match m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
Definition: PatternMatch.h:180
const ConstantDataArray * Array
ConstantDataArray pointer.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4444
#define T
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:121
Value * emitMemCpyChk(Value *Dst, Value *Src, Value *Len, Value *ObjSize, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the __memcpy_chk function to the builder.
bool has(LibFunc F) const
Tests whether a library function is available.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:126
Value * emitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B, const TargetLibraryInfo *TLI, StringRef Name="strcpy")
Emit a call to the strcpy function to the builder, for the specified pointer arguments.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1031
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:224
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:123
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
static Value * valueHasFloatPrecision(Value *Val)
Return a variant of Val with float type.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1659
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return &#39;len+1&#39;...
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
amdgpu Simplify well known AMD library false Value * Callee
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1020
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:127
Value * getOperand(unsigned i) const
Definition: User.h:170
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
Definition: IRBuilder.h:318
ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
Definition: CallingConv.h:103
static bool isOnlyUsedInComparisonWithZero(Value *V)
bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1773
Value * emitFPutS(Value *Str, Value *File, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the fputs function.
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
const BasicBlock & getEntryBlock() const
Definition: Function.h:640
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:750
bool inferLibFuncAttributes(Function &F, const TargetLibraryInfo &TLI)
Analyze the name and prototype of the given function and set any applicable attributes.
Type * getDoubleTy()
Fetch the type representing a 64-bit floating point value.
Definition: IRBuilder.h:375
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:62
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B, const TargetLibraryInfo *TLI)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1247
void setNoSignedZeros(bool B=true)
Definition: Operator.h:219
bool isNegative() const
Definition: APFloat.h:1147
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Value * CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition: IRBuilder.h:1580
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:287
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Definition: InstrTypes.h:1483
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:2021
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
LLVM_NODISCARD size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Definition: StringRef.cpp:250
FunctionType * getFunctionType() const
Definition: InstrTypes.h:1051
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
Value * CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1884
ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete, but still used on some target...
Definition: CallingConv.h:96
double convertToDouble() const
Definition: APFloat.h:1097
Diagnostic information for applied optimization remarks.
bool isExactlyValue(double V) const
We don&#39;t rely on operator== working on double values, as it returns true for things that are clearly ...
Definition: APFloat.h:1130
bool isFast() const
Determine whether all fast-math-flags are set.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1193
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1308
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:598
This instruction compares its operands according to the predicate given to the constructor.
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1229
op_range operands()
Definition: User.h:238
Value * getPointerOperand()
Definition: Instructions.h:285
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE int compare(StringRef RHS) const
compare - Compare two strings; the result is -1, 0, or 1 if this string is lexicographically less tha...
Definition: StringRef.h:184
static bool isCallingConvCCompatible(CallInst *CI)
Class to represent integer types.
Definition: DerivedTypes.h:40
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:312
Value * castToCStr(Value *V, IRBuilder<> &B)
Return V if it is an i8*, otherwise cast it to i8*.
Represents offset+length into a ConstantDataArray.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2041
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:60
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:398
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:640
const Constant * stripPointerCasts() const
Definition: Constant.h:174
Value * emitStrChr(Value *Ptr, char C, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the strchr function to the builder, for the specified pointer and character.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2083
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:149
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Definition: InstrTypes.h:1251
static bool isBinary(MachineInstr &MI)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1655
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_back(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the last N elements dropped.
Definition: StringRef.h:654
Value * emitFWriteUnlocked(Value *Ptr, Value *Size, Value *N, Value *File, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the fwrite_unlocked function.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1458
Value * CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1894
Value * emitStrLen(Value *Ptr, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strlen function to the builder, for the specified pointer.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:240
Value * emitBinaryFloatFnCall(Value *Op1, Value *Op2, StringRef Name, IRBuilder<> &B, const AttributeList &Attrs)
Emit a call to the binary function named &#39;Name&#39; (e.g.
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:120
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Definition: InstrTypes.h:1275
static Value * optimizeDoubleFP(CallInst *CI, IRBuilder<> &B, bool isBinary, bool isPrecise=false)
Shrink double -> float functions.
bool isInteger() const
Definition: APFloat.h:1162
Value * emitFGetCUnlocked(Value *File, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the fgetc_unlocked function. File is a pointer to FILE.
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
GlobalVariable * CreateGlobalString(StringRef Str, const Twine &Name="", unsigned AddressSpace=0)
Make a new global variable with initializer type i8*.
Definition: IRBuilder.cpp:43
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:1801
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:2680
Module.h This file contains the declarations for the Module class.
uint64_t Length
Length of the slice.
Provides information about what library functions are available for the current target.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:307
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Definition: InstrTypes.h:1715
CallInst * CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
Definition: IRBuilder.h:446
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:622
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:685
AttributeList getAttributes() const
Return the parameter attributes for this call.
Definition: InstrTypes.h:1244
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
Definition: PatternMatch.h:707
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:194
void setNoNaNs(bool B=true)
Definition: Operator.h:213
unsigned logBase2() const
Definition: APInt.h:1748
The access may modify the value stored in memory.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:164
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
Class for arbitrary precision integers.
Definition: APInt.h:70
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1223
bool isPowerOf2() const
Check if this APInt&#39;s value is a power of two greater than zero.
Definition: APInt.h:464
iterator_range< user_iterator > users()
Definition: Value.h:400
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:337
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1103
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
iterator begin() const
Definition: StringRef.h:106
Value * emitFPutC(Value *Char, Value *File, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the fputc function.
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:292
amdgpu Simplify well known AMD library false Value Value * Arg
Value * emitFGetSUnlocked(Value *Str, Value *Size, Value *File, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the fgets_unlocked function.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
Definition: PatternMatch.h:543
opStatus add(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:941
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:721
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match &#39;fneg X&#39; as &#39;fsub -0.0, X&#39;.
Definition: PatternMatch.h:689
unsigned getNumArgOperands() const
Definition: InstrTypes.h:1133
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:867
static const size_t npos
Definition: StringRef.h:51
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:97
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
static Value * optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B, bool isPrecise=false)
Shrink double -> float for unary functions.
Value * emitStrNCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the strncmp function to the builder.
CallingConv::ID getCallingConv() const
Definition: InstrTypes.h:1225
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
Definition: InstrTypes.h:1181
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:395
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition: APFloat.h:1213
This class represents a cast unsigned integer to floating point.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:193
static Value * optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B, bool isPrecise=false)
Shrink double -> float for binary functions.
Value * optimizeCall(CallInst *CI)
optimizeCall - Take the given call instruction and return a more optimal value to replace the instruc...
unsigned getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition: Local.h:268
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
uint32_t Size
Definition: Profile.cpp:47
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1974
static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg, bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos)
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
Definition: IRBuilder.h:370
Value * CreateFAdd(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1213
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
Definition: InstrTypes.h:1489
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1164
Value * CreateFDiv(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Definition: IRBuilder.h:1264
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:206
bool getConstantStringInfo(const Value *V, StringRef &Str, uint64_t Offset=0, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
Value * emitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the fwrite function.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:794
Value * emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memcmp function.
This class represents a cast from signed integer to floating point.
static bool isOnlyUsedInEqualityComparison(Value *V, Value *With)
Return true if it is only used in equality comparisons with With.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:376
This class represents a truncation of floating point types.
Value * emitFReadUnlocked(Value *Ptr, Value *Size, Value *N, Value *File, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the fread_unlocked function.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
Value * emitPutS(Value *Str, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Emit a call to the puts function. This assumes that Str is some pointer.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:606
Value * emitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memchr function.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:220
static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len, const DataLayout &DL)
Value * emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs, IRBuilder<> &B, const TargetLibraryInfo &TLI)
Emit a call to the calloc function.
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition: IRBuilder.h:297
static Value * optimizeTrigReflections(CallInst *Call, LibFunc Func, IRBuilder<> &B)
bool hasNoNaNs() const
Determine whether the no-NaNs flag is set.
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:413
static Value * getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno, Module *M, IRBuilder<> &B, const TargetLibraryInfo *TLI)
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool isDereferenceableAndAlignedPointer(const Value *V, unsigned Align, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested...
Definition: Loads.cpp:129
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:157
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition: IRBuilder.h:323
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:298
static bool ignoreCallingConv(LibFunc Func)
This class represents an extension of floating point types.
iterator end() const
Definition: StringRef.h:108
static Constant * getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1691
bool isDoubleTy() const
Return true if this is &#39;double&#39;, a 64-bit IEEE fp type.
Definition: Type.h:150
bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty, LibFunc DoubleFn, LibFunc FloatFn, LibFunc LongDoubleFn)
Check whether the overloaded unary floating point function corresponding to Ty is available...
The optimization diagnostic interface.
bool use_empty() const
Definition: Value.h:323
static Value * getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B)
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1326
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:218
cmpResult compare(const APFloat &RHS) const
Definition: APFloat.h:1102
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:221
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures, unsigned MaxUsesToExplore=DefaultMaxUsesToExplore)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
user_iterator user_end()
Definition: Value.h:384