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