blob: b2319945a2c0da80112875da3a282a1118daed40 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ 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"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Sanjay Patel7756edf2017-08-21 13:55:49 +000021#include "llvm/Analysis/ConstantFolding.h"
Adam Nemetea06e6e2017-07-26 19:03:18 +000022#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000028#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000032#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000034#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000036#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000037
38using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000039using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000040
Hal Finkel66cd3f12013-11-17 02:06:35 +000041static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000042 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46
47
Meador Ingedf796f82012-10-13 16:45:24 +000048//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000049// Helper Functions
50//===----------------------------------------------------------------------===//
51
David L. Jonesd21529f2017-01-23 23:16:46 +000052static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000055}
56
Sam Parker214f7bf2016-09-13 12:10:14 +000057static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
59 default:
60 return false;
61 case llvm::CallingConv::C:
62 return true;
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
66
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
70 return false;
71
72 auto *FuncTy = CI->getFunctionType();
73
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
77 return false;
78
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
81 return false;
82 }
83 return true;
84 }
85 }
86 return false;
87}
88
Sanjay Pateld707db92015-12-31 16:10:49 +000089/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000090static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000093 if (IC->isEquality() && IC->getOperand(1) == With)
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Meador Inge08ca1152012-11-26 20:37:20 +0000101static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000102 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000103 return OI->getType()->isFloatingPointTy();
104 });
Meador Inge08ca1152012-11-26 20:37:20 +0000105}
106
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000107/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000108/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000109static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000110 LibFunc DoubleFn, LibFunc FloatFn,
111 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000112 switch (Ty->getTypeID()) {
113 case Type::FloatTyID:
114 return TLI->has(FloatFn);
115 case Type::DoubleTyID:
116 return TLI->has(DoubleFn);
117 default:
118 return TLI->has(LongDoubleFn);
119 }
120}
121
Meador Inged589ac62012-10-31 03:33:06 +0000122//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000123// String and Memory Library Call Optimizations
124//===----------------------------------------------------------------------===//
125
Chris Bienemanad070d02014-09-17 20:55:46 +0000126Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000127 // Extract some information from the instruction
128 Value *Dst = CI->getArgOperand(0);
129 Value *Src = CI->getArgOperand(1);
130
131 // See if we can get the length of the input string.
132 uint64_t Len = GetStringLength(Src);
133 if (Len == 0)
134 return nullptr;
135 --Len; // Unbias length.
136
137 // Handle the simple, do-nothing case: strcat(x, "") -> x
138 if (Len == 0)
139 return Dst;
140
Chris Bienemanad070d02014-09-17 20:55:46 +0000141 return emitStrLenMemCpy(Src, Dst, Len, B);
142}
143
144Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
145 IRBuilder<> &B) {
146 // We need to find the end of the destination string. That's where the
147 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000148 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000149 if (!DstLen)
150 return nullptr;
151
152 // Now that we have the destination's length, we must index into the
153 // destination's pointer to get the actual memcpy destination (end of
154 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000155 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000156
157 // We have enough information to now generate the memcpy call to do the
158 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159 B.CreateMemCpy(CpyDst, Src,
160 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000161 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000162 return Dst;
163}
164
165Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000166 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000167 Value *Dst = CI->getArgOperand(0);
168 Value *Src = CI->getArgOperand(1);
169 uint64_t Len;
170
Sanjay Pateld707db92015-12-31 16:10:49 +0000171 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000172 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
173 Len = LengthArg->getZExtValue();
174 else
175 return nullptr;
176
177 // See if we can get the length of the input string.
178 uint64_t SrcLen = GetStringLength(Src);
179 if (SrcLen == 0)
180 return nullptr;
181 --SrcLen; // Unbias length.
182
183 // Handle the simple, do-nothing cases:
184 // strncat(x, "", c) -> x
185 // strncat(x, c, 0) -> x
186 if (SrcLen == 0 || Len == 0)
187 return Dst;
188
Sanjay Pateld707db92015-12-31 16:10:49 +0000189 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000190 if (Len < SrcLen)
191 return nullptr;
192
193 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000194 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000195 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
196}
197
198Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
199 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000201 Value *SrcStr = CI->getArgOperand(0);
202
203 // If the second operand is non-constant, see if we can compute the length
204 // of the input string and turn this into memchr.
205 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
206 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 uint64_t Len = GetStringLength(SrcStr);
208 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
209 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000210
Sanjay Pateld3112a52016-01-19 19:46:10 +0000211 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000212 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
213 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000214 }
215
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 // Otherwise, the character is a constant, see if the first argument is
217 // a string literal. If so, we can constant fold.
218 StringRef Str;
219 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000221 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000222 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000223 return nullptr;
224 }
225
226 // Compute the offset, make sure to handle the case when we're searching for
227 // zero (a weird way to spell strlen).
228 size_t I = (0xFF & CharC->getSExtValue()) == 0
229 ? Str.size()
230 : Str.find(CharC->getSExtValue());
231 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
232 return Constant::getNullValue(CI->getType());
233
234 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000235 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000236}
237
238Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 Value *SrcStr = CI->getArgOperand(0);
240 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
241
242 // Cannot fold anything if we're not looking for a constant.
243 if (!CharC)
244 return nullptr;
245
246 StringRef Str;
247 if (!getConstantStringInfo(SrcStr, Str)) {
248 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000250 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000251 return nullptr;
252 }
253
254 // Compute the offset.
255 size_t I = (0xFF & CharC->getSExtValue()) == 0
256 ? Str.size()
257 : Str.rfind(CharC->getSExtValue());
258 if (I == StringRef::npos) // Didn't find the char. Return null.
259 return Constant::getNullValue(CI->getType());
260
261 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000262 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000263}
264
265Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000266 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
267 if (Str1P == Str2P) // strcmp(x,x) -> 0
268 return ConstantInt::get(CI->getType(), 0);
269
270 StringRef Str1, Str2;
271 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
272 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
273
274 // strcmp(x, y) -> cnst (if both x and y are constant strings)
275 if (HasStr1 && HasStr2)
276 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
277
278 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
279 return B.CreateNeg(
280 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
281
282 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
283 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
284
285 // strcmp(P, "x") -> memcmp(P, "x", 2)
286 uint64_t Len1 = GetStringLength(Str1P);
287 uint64_t Len2 = GetStringLength(Str2P);
288 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000289 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000290 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000291 std::min(Len1, Len2)),
292 B, DL, TLI);
293 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000294
Chris Bienemanad070d02014-09-17 20:55:46 +0000295 return nullptr;
296}
297
298Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000299 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
300 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
301 return ConstantInt::get(CI->getType(), 0);
302
303 // Get the length argument if it is constant.
304 uint64_t Length;
305 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
306 Length = LengthArg->getZExtValue();
307 else
308 return nullptr;
309
310 if (Length == 0) // strncmp(x,y,0) -> 0
311 return ConstantInt::get(CI->getType(), 0);
312
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000313 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000314 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000315
316 StringRef Str1, Str2;
317 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
318 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
319
320 // strncmp(x, y) -> cnst (if both x and y are constant strings)
321 if (HasStr1 && HasStr2) {
322 StringRef SubStr1 = Str1.substr(0, Length);
323 StringRef SubStr2 = Str2.substr(0, Length);
324 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
325 }
326
327 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
328 return B.CreateNeg(
329 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
330
331 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
332 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
333
334 return nullptr;
335}
336
337Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000338 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
339 if (Dst == Src) // strcpy(x,x) -> x
340 return Src;
341
Chris Bienemanad070d02014-09-17 20:55:46 +0000342 // See if we can get the length of the input string.
343 uint64_t Len = GetStringLength(Src);
344 if (Len == 0)
345 return nullptr;
346
347 // We have enough information to now generate the memcpy call to do the
348 // copy for us. Make a memcpy to copy the nul byte with align = 1.
349 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000350 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000351 return Dst;
352}
353
354Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
355 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000356 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
357 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000358 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000359 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000360 }
361
362 // See if we can get the length of the input string.
363 uint64_t Len = GetStringLength(Src);
364 if (Len == 0)
365 return nullptr;
366
Davide Italianob7487e62015-11-02 23:07:14 +0000367 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000369 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
370 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000371
372 // We have enough information to now generate the memcpy call to do the
373 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000374 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000375 return DstEnd;
376}
377
378Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
379 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000380 Value *Dst = CI->getArgOperand(0);
381 Value *Src = CI->getArgOperand(1);
382 Value *LenOp = CI->getArgOperand(2);
383
384 // See if we can get the length of the input string.
385 uint64_t SrcLen = GetStringLength(Src);
386 if (SrcLen == 0)
387 return nullptr;
388 --SrcLen;
389
390 if (SrcLen == 0) {
391 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
392 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000393 return Dst;
394 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000395
Chris Bienemanad070d02014-09-17 20:55:46 +0000396 uint64_t Len;
397 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
398 Len = LengthArg->getZExtValue();
399 else
400 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000401
Chris Bienemanad070d02014-09-17 20:55:46 +0000402 if (Len == 0)
403 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000404
Chris Bienemanad070d02014-09-17 20:55:46 +0000405 // Let strncpy handle the zero padding
406 if (Len > SrcLen + 1)
407 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000408
Davide Italianob7487e62015-11-02 23:07:14 +0000409 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000410 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000411 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000412
Chris Bienemanad070d02014-09-17 20:55:46 +0000413 return Dst;
414}
Meador Inge7fb2f732012-10-13 16:45:32 +0000415
Matthias Braun50ec0b52017-05-19 22:37:09 +0000416Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
417 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000418 Value *Src = CI->getArgOperand(0);
419
420 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000421 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000422 return ConstantInt::get(CI->getType(), Len - 1);
423
David L Kreitzer752c1442016-04-13 14:31:06 +0000424 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000425 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000426 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000427 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000428 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000429 // subtraction. This will make the optimization more complex, and it's not
430 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000431 // very uncommon.
432 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000433 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000434 return nullptr;
435
Matthias Braun50ec0b52017-05-19 22:37:09 +0000436 ConstantDataArraySlice Slice;
437 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
438 uint64_t NullTermIdx;
439 if (Slice.Array == nullptr) {
440 NullTermIdx = 0;
441 } else {
442 NullTermIdx = ~((uint64_t)0);
443 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
444 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
445 NullTermIdx = I;
446 break;
447 }
448 }
449 // If the string does not have '\0', leave it to strlen to compute
450 // its length.
451 if (NullTermIdx == ~((uint64_t)0))
452 return nullptr;
453 }
454
David L Kreitzer752c1442016-04-13 14:31:06 +0000455 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000456 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000457 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000458 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000459 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
460
Matthias Braun50ec0b52017-05-19 22:37:09 +0000461 // KnownZero's bits are flipped, so zeros in KnownZero now represent
462 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000463 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000464 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000465 // unsigned-less-than NullTermIdx.
466 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000467 // If Offset is not provably in the range [0, NullTermIdx], we can still
468 // optimize if we can prove that the program has undefined behavior when
469 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000470 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000471 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000472 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000473 NullTermIdx == ArrSize - 1)) {
474 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
475 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000476 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000477 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000478 }
479
480 return nullptr;
481 }
482
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 // strlen(x?"foo":"bars") --> x ? 3 : 4
484 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000485 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
486 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000487 if (LenTrue && LenFalse) {
Adam Nemetea06e6e2017-07-26 19:03:18 +0000488 ORE.emit(OptimizationRemark("instcombine", "simplify-libcalls", CI)
489 << "folded strlen(select) to select of constants");
Chris Bienemanad070d02014-09-17 20:55:46 +0000490 return B.CreateSelect(SI->getCondition(),
491 ConstantInt::get(CI->getType(), LenTrue - 1),
492 ConstantInt::get(CI->getType(), LenFalse - 1));
493 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000494 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000495
Chris Bienemanad070d02014-09-17 20:55:46 +0000496 // strlen(x) != 0 --> *x != 0
497 // strlen(x) == 0 --> *x == 0
498 if (isOnlyUsedInZeroEqualityComparison(CI))
499 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000500
Chris Bienemanad070d02014-09-17 20:55:46 +0000501 return nullptr;
502}
Meador Inge17418502012-10-13 16:45:37 +0000503
Matthias Braun50ec0b52017-05-19 22:37:09 +0000504Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
505 return optimizeStringLength(CI, B, 8);
506}
507
508Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
509 Module &M = *CI->getParent()->getParent()->getParent();
510 unsigned WCharSize = TLI->getWCharSize(M) * 8;
511
512 return optimizeStringLength(CI, B, WCharSize);
513}
514
Chris Bienemanad070d02014-09-17 20:55:46 +0000515Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 StringRef S1, S2;
517 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
518 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000519
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000520 // strpbrk(s, "") -> nullptr
521 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000522 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
523 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000524
Chris Bienemanad070d02014-09-17 20:55:46 +0000525 // Constant folding.
526 if (HasS1 && HasS2) {
527 size_t I = S1.find_first_of(S2);
528 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000529 return Constant::getNullValue(CI->getType());
530
Sanjay Pateld707db92015-12-31 16:10:49 +0000531 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
532 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000533 }
Meador Inge17418502012-10-13 16:45:37 +0000534
Chris Bienemanad070d02014-09-17 20:55:46 +0000535 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000536 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000537 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000538
539 return nullptr;
540}
541
542Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000543 Value *EndPtr = CI->getArgOperand(1);
544 if (isa<ConstantPointerNull>(EndPtr)) {
545 // With a null EndPtr, this function won't capture the main argument.
546 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000547 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 }
549
550 return nullptr;
551}
552
553Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000554 StringRef S1, S2;
555 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
556 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
557
558 // strspn(s, "") -> 0
559 // strspn("", s) -> 0
560 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
561 return Constant::getNullValue(CI->getType());
562
563 // Constant folding.
564 if (HasS1 && HasS2) {
565 size_t Pos = S1.find_first_not_of(S2);
566 if (Pos == StringRef::npos)
567 Pos = S1.size();
568 return ConstantInt::get(CI->getType(), Pos);
569 }
570
571 return nullptr;
572}
573
574Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 StringRef S1, S2;
576 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
577 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
578
579 // strcspn("", s) -> 0
580 if (HasS1 && S1.empty())
581 return Constant::getNullValue(CI->getType());
582
583 // Constant folding.
584 if (HasS1 && HasS2) {
585 size_t Pos = S1.find_first_of(S2);
586 if (Pos == StringRef::npos)
587 Pos = S1.size();
588 return ConstantInt::get(CI->getType(), Pos);
589 }
590
591 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000592 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000593 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000594
595 return nullptr;
596}
597
598Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000599 // fold strstr(x, x) -> x.
600 if (CI->getArgOperand(0) == CI->getArgOperand(1))
601 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
602
603 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000605 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000607 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000608 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000609 StrLen, B, DL, TLI);
610 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000611 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000612 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
613 ICmpInst *Old = cast<ICmpInst>(*UI++);
614 Value *Cmp =
615 B.CreateICmp(Old->getPredicate(), StrNCmp,
616 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
617 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000618 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000619 return CI;
620 }
Meador Inge17418502012-10-13 16:45:37 +0000621
Chris Bienemanad070d02014-09-17 20:55:46 +0000622 // See if either input string is a constant string.
623 StringRef SearchStr, ToFindStr;
624 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
625 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
626
627 // fold strstr(x, "") -> x.
628 if (HasStr2 && ToFindStr.empty())
629 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
630
631 // If both strings are known, constant fold it.
632 if (HasStr1 && HasStr2) {
633 size_t Offset = SearchStr.find(ToFindStr);
634
635 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000636 return Constant::getNullValue(CI->getType());
637
Chris Bienemanad070d02014-09-17 20:55:46 +0000638 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000639 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000640 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
641 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000642 }
Meador Inge17418502012-10-13 16:45:37 +0000643
Chris Bienemanad070d02014-09-17 20:55:46 +0000644 // fold strstr(x, "y") -> strchr(x, 'y').
645 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000646 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000647 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
648 }
649 return nullptr;
650}
Meador Inge40b6fac2012-10-15 03:47:37 +0000651
Benjamin Kramer691363e2015-03-21 15:36:21 +0000652Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000653 Value *SrcStr = CI->getArgOperand(0);
654 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
655 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
656
657 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000658 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000659 return Constant::getNullValue(CI->getType());
660
Benjamin Kramer7857d722015-03-21 21:09:33 +0000661 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000662 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000663 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000664 return nullptr;
665
666 // Truncate the string to LenC. If Str is smaller than LenC we will still only
667 // scan the string, as reading past the end of it is undefined and we can just
668 // return null if we don't find the char.
669 Str = Str.substr(0, LenC->getZExtValue());
670
Benjamin Kramer7857d722015-03-21 21:09:33 +0000671 // If the char is variable but the input str and length are not we can turn
672 // this memchr call into a simple bit field test. Of course this only works
673 // when the return value is only checked against null.
674 //
675 // It would be really nice to reuse switch lowering here but we can't change
676 // the CFG at this point.
677 //
678 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
679 // after bounds check.
680 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000681 unsigned char Max =
682 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
683 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000684
685 // Make sure the bit field we're about to create fits in a register on the
686 // target.
687 // FIXME: On a 64 bit architecture this prevents us from using the
688 // interesting range of alpha ascii chars. We could do better by emitting
689 // two bitfields or shifting the range by 64 if no lower chars are used.
690 if (!DL.fitsInLegalInteger(Max + 1))
691 return nullptr;
692
693 // For the bit field use a power-of-2 type with at least 8 bits to avoid
694 // creating unnecessary illegal types.
695 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
696
697 // Now build the bit field.
698 APInt Bitfield(Width, 0);
699 for (char C : Str)
700 Bitfield.setBit((unsigned char)C);
701 Value *BitfieldC = B.getInt(Bitfield);
702
703 // First check that the bit field access is within bounds.
704 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
705 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
706 "memchr.bounds");
707
708 // Create code that checks if the given bit is set in the field.
709 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
710 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
711
712 // Finally merge both checks and cast to pointer type. The inttoptr
713 // implicitly zexts the i1 to intptr type.
714 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
715 }
716
717 // Check if all arguments are constants. If so, we can constant fold.
718 if (!CharC)
719 return nullptr;
720
Benjamin Kramer691363e2015-03-21 15:36:21 +0000721 // Compute the offset.
722 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
723 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
724 return Constant::getNullValue(CI->getType());
725
726 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000727 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000728}
729
Chris Bienemanad070d02014-09-17 20:55:46 +0000730Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000731 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000732
Chris Bienemanad070d02014-09-17 20:55:46 +0000733 if (LHS == RHS) // memcmp(s,s,x) -> 0
734 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000735
Chris Bienemanad070d02014-09-17 20:55:46 +0000736 // Make sure we have a constant length.
737 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
738 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000739 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000740
Sanjay Patel70db4242017-06-09 14:22:03 +0000741 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 if (Len == 0) // memcmp(s1,s2,0) -> 0
743 return Constant::getNullValue(CI->getType());
744
745 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
746 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000747 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000748 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000749 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000750 CI->getType(), "rhsv");
751 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000752 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000753
Chad Rosierdc655322015-08-28 18:30:18 +0000754 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel7756edf2017-08-21 13:55:49 +0000755 // TODO: The case where both inputs are constants does not need to be limited
756 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000757 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000758 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
759 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
760
Sanjay Patel7756edf2017-08-21 13:55:49 +0000761 // First, see if we can fold either argument to a constant.
762 Value *LHSV = nullptr;
763 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
764 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
765 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
766 }
767 Value *RHSV = nullptr;
768 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
769 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
770 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
771 }
Chad Rosierdc655322015-08-28 18:30:18 +0000772
Sanjay Patel7756edf2017-08-21 13:55:49 +0000773 // Don't generate unaligned loads. If either source is constant data,
774 // alignment doesn't matter for that source because there is no load.
775 if (!LHSV && getKnownAlignment(LHS, DL, CI) >= PrefAlignment) {
Chad Rosierdc655322015-08-28 18:30:18 +0000776 Type *LHSPtrTy =
777 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
Sanjay Patel7756edf2017-08-21 13:55:49 +0000778 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
779 }
780
781 if (!RHSV && getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
Chad Rosierdc655322015-08-28 18:30:18 +0000782 Type *RHSPtrTy =
783 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
Sanjay Patel7756edf2017-08-21 13:55:49 +0000784 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000785 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000786
787 if (LHSV && RHSV)
788 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Chad Rosierdc655322015-08-28 18:30:18 +0000789 }
790
Sanjay Patel7756edf2017-08-21 13:55:49 +0000791 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
792 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000793 StringRef LHSStr, RHSStr;
794 if (getConstantStringInfo(LHS, LHSStr) &&
795 getConstantStringInfo(RHS, RHSStr)) {
796 // Make sure we're not reading out-of-bounds memory.
797 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000798 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000799 // Fold the memcmp and normalize the result. This way we get consistent
800 // results across multiple platforms.
801 uint64_t Ret = 0;
802 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
803 if (Cmp < 0)
804 Ret = -1;
805 else if (Cmp > 0)
806 Ret = 1;
807 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000808 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000809
Chris Bienemanad070d02014-09-17 20:55:46 +0000810 return nullptr;
811}
Meador Inge9a6a1902012-10-31 00:20:56 +0000812
Chris Bienemanad070d02014-09-17 20:55:46 +0000813Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000814 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
815 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000816 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000817 return CI->getArgOperand(0);
818}
Meador Inge05a625a2012-10-31 14:58:26 +0000819
Chris Bienemanad070d02014-09-17 20:55:46 +0000820Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000821 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
822 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000823 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000824 return CI->getArgOperand(0);
825}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000826
Sanjay Patel980b2802016-01-26 16:17:24 +0000827// TODO: Does this belong in BuildLibCalls or should all of those similar
828// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000829static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000830 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000831 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000832 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
833 return nullptr;
834
835 Module *M = B.GetInsertBlock()->getModule();
836 const DataLayout &DL = M->getDataLayout();
837 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
838 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000839 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000840 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
841
842 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
843 CI->setCallingConv(F->getCallingConv());
844
845 return CI;
846}
847
848/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
849static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
850 const TargetLibraryInfo &TLI) {
851 // This has to be a memset of zeros (bzero).
852 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
853 if (!FillValue || FillValue->getZExtValue() != 0)
854 return nullptr;
855
856 // TODO: We should handle the case where the malloc has more than one use.
857 // This is necessary to optimize common patterns such as when the result of
858 // the malloc is checked against null or when a memset intrinsic is used in
859 // place of a memset library call.
860 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
861 if (!Malloc || !Malloc->hasOneUse())
862 return nullptr;
863
864 // Is the inner call really malloc()?
865 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000866 if (!InnerCallee)
867 return nullptr;
868
David L. Jonesd21529f2017-01-23 23:16:46 +0000869 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000870 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000871 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000872 return nullptr;
873
Sanjay Patel980b2802016-01-26 16:17:24 +0000874 // The memset must cover the same number of bytes that are malloc'd.
875 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
876 return nullptr;
877
878 // Replace the malloc with a calloc. We need the data layout to know what the
879 // actual size of a 'size_t' parameter is.
880 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
881 const DataLayout &DL = Malloc->getModule()->getDataLayout();
882 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
883 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
884 Malloc->getArgOperand(0), Malloc->getAttributes(),
885 B, TLI);
886 if (!Calloc)
887 return nullptr;
888
889 Malloc->replaceAllUsesWith(Calloc);
890 Malloc->eraseFromParent();
891
892 return Calloc;
893}
894
Chris Bienemanad070d02014-09-17 20:55:46 +0000895Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000896 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
897 return Calloc;
898
Chris Bienemanad070d02014-09-17 20:55:46 +0000899 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
900 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
901 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
902 return CI->getArgOperand(0);
903}
Meador Inged4825782012-11-11 06:49:03 +0000904
Meador Inge193e0352012-11-13 04:16:17 +0000905//===----------------------------------------------------------------------===//
906// Math Library Optimizations
907//===----------------------------------------------------------------------===//
908
Matthias Braund34e4d22014-12-03 21:46:33 +0000909/// Return a variant of Val with float type.
910/// Currently this works in two cases: If Val is an FPExtension of a float
911/// value to something bigger, simply return the operand.
912/// If Val is a ConstantFP but can be converted to a float ConstantFP without
913/// loss of precision do so.
914static Value *valueHasFloatPrecision(Value *Val) {
915 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
916 Value *Op = Cast->getOperand(0);
917 if (Op->getType()->isFloatTy())
918 return Op;
919 }
920 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
921 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000922 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000923 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000924 &losesInfo);
925 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000926 return ConstantFP::get(Const->getContext(), F);
927 }
928 return nullptr;
929}
930
Sanjay Patel4e971da2016-01-21 18:01:57 +0000931/// Shrink double -> float for unary functions like 'floor'.
932static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
933 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000934 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000935 // We know this libcall has a valid prototype, but we don't know which.
936 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000937 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000938
Chris Bienemanad070d02014-09-17 20:55:46 +0000939 if (CheckRetType) {
940 // Check if all the uses for function like 'sin' are converted to float.
941 for (User *U : CI->users()) {
942 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
943 if (!Cast || !Cast->getType()->isFloatTy())
944 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000945 }
Meador Inge193e0352012-11-13 04:16:17 +0000946 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000947
948 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000949 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
950 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000951 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000952
Andrew Ng1606fc02017-04-25 12:36:14 +0000953 // If call isn't an intrinsic, check that it isn't within a function with the
954 // same name as the float version of this call.
955 //
956 // e.g. inline float expf(float val) { return (float) exp((double) val); }
957 //
958 // A similar such definition exists in the MinGW-w64 math.h header file which
959 // when compiled with -O2 -ffast-math causes the generation of infinite loops
960 // where expf is called.
961 if (!Callee->isIntrinsic()) {
962 const Function *F = CI->getFunction();
963 StringRef FName = F->getName();
964 StringRef CalleeName = Callee->getName();
965 if ((FName.size() == (CalleeName.size() + 1)) &&
966 (FName.back() == 'f') &&
967 FName.startswith(CalleeName))
968 return nullptr;
969 }
970
Sanjay Patelaa231142015-12-31 21:52:31 +0000971 // Propagate fast-math flags from the existing call to the new call.
972 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000973 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000974
975 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000976 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000977 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000978 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000979 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
980 V = B.CreateCall(F, V);
981 } else {
982 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000983 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000984 }
985
Chris Bienemanad070d02014-09-17 20:55:46 +0000986 return B.CreateFPExt(V, B.getDoubleTy());
987}
Meador Inge193e0352012-11-13 04:16:17 +0000988
Matt Arsenault954a6242017-01-23 23:55:08 +0000989// Replace a libcall \p CI with a call to intrinsic \p IID
990static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
991 // Propagate fast-math flags from the existing call to the new call.
992 IRBuilder<>::FastMathFlagGuard Guard(B);
993 B.setFastMathFlags(CI->getFastMathFlags());
994
995 Module *M = CI->getModule();
996 Value *V = CI->getArgOperand(0);
997 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
998 CallInst *NewCall = B.CreateCall(F, V);
999 NewCall->takeName(CI);
1000 return NewCall;
1001}
1002
Sanjay Patel4e971da2016-01-21 18:01:57 +00001003/// Shrink double -> float for binary functions like 'fmin/fmax'.
1004static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001005 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +00001006 // We know this libcall has a valid prototype, but we don't know which.
1007 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001008 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001009
Chris Bienemanad070d02014-09-17 20:55:46 +00001010 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001011 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1012 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1013 if (V1 == nullptr)
1014 return nullptr;
1015 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1016 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001017 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001018
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001019 // Propagate fast-math flags from the existing call to the new call.
1020 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001021 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001022
Chris Bienemanad070d02014-09-17 20:55:46 +00001023 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001024 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001025 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001026 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001027 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001028 return B.CreateFPExt(V, B.getDoubleTy());
1029}
1030
1031Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1032 Function *Callee = CI->getCalledFunction();
1033 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001034 StringRef Name = Callee->getName();
1035 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001036 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001037
Chris Bienemanad070d02014-09-17 20:55:46 +00001038 // cos(-x) -> cos(x)
1039 Value *Op1 = CI->getArgOperand(0);
1040 if (BinaryOperator::isFNeg(Op1)) {
1041 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1042 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1043 }
1044 return Ret;
1045}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001046
Weiming Zhao82130722015-12-04 22:00:47 +00001047static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1048 // Multiplications calculated using Addition Chains.
1049 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1050
1051 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1052
1053 if (InnerChain[Exp])
1054 return InnerChain[Exp];
1055
1056 static const unsigned AddChain[33][2] = {
1057 {0, 0}, // Unused.
1058 {0, 0}, // Unused (base case = pow1).
1059 {1, 1}, // Unused (pre-computed).
1060 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1061 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1062 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1063 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1064 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1065 };
1066
1067 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1068 getPow(InnerChain, AddChain[Exp][1], B));
1069 return InnerChain[Exp];
1070}
1071
Chris Bienemanad070d02014-09-17 20:55:46 +00001072Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1073 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001074 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001075 StringRef Name = Callee->getName();
1076 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001077 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001078
Chris Bienemanad070d02014-09-17 20:55:46 +00001079 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001080
1081 // pow(1.0, x) -> 1.0
1082 if (match(Op1, m_SpecificFP(1.0)))
1083 return Op1;
1084 // pow(2.0, x) -> llvm.exp2(x)
1085 if (match(Op1, m_SpecificFP(2.0))) {
1086 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1087 CI->getType());
1088 return B.CreateCall(Exp2, Op2, "exp2");
1089 }
1090
1091 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1092 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001093 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001094 // pow(10.0, x) -> exp10(x)
1095 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001096 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1097 LibFunc_exp10l))
1098 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001099 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001100 }
1101
Sanjay Patel6002e782016-01-12 17:30:37 +00001102 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001103 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001104 // We enable these only with fast-math. Besides rounding differences, the
1105 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001106 // Example: x = 1000, y = 0.001.
1107 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001108 auto *OpC = dyn_cast<CallInst>(Op1);
1109 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001110 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001111 Function *OpCCallee = OpC->getCalledFunction();
1112 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001113 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001114 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001115 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001116 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001117 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001118 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001119 }
1120 }
1121
Chris Bienemanad070d02014-09-17 20:55:46 +00001122 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1123 if (!Op2C)
1124 return Ret;
1125
1126 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1127 return ConstantFP::get(CI->getType(), 1.0);
1128
Davide Italiano472684e2017-01-09 21:55:23 +00001129 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001130 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1131 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001132 // If -ffast-math:
1133 // pow(x, -0.5) -> 1.0 / sqrt(x)
1134 if (CI->hasUnsafeAlgebra()) {
1135 IRBuilder<>::FastMathFlagGuard Guard(B);
1136 B.setFastMathFlags(CI->getFastMathFlags());
1137
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001138 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1139 // intrinsic, so we match errno semantics. We also should check that the
1140 // target can in fact lower the sqrt intrinsic -- we currently have no way
1141 // to ask this question other than asking whether the target has a sqrt
1142 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001143 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001144 Callee->getAttributes());
1145
1146 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1147 }
1148 }
1149
Chris Bienemanad070d02014-09-17 20:55:46 +00001150 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001151 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1152 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001153
1154 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001155 if (CI->hasUnsafeAlgebra()) {
1156 IRBuilder<>::FastMathFlagGuard Guard(B);
1157 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001158
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001159 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1160 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001161 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001162 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001163 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001164
Chris Bienemanad070d02014-09-17 20:55:46 +00001165 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1166 // This is faster than calling pow, and still handles negative zero
1167 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001168 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1169 Value *Inf = ConstantFP::getInfinity(CI->getType());
1170 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001171
1172 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1173 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001174 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001175
1176 Module *M = Callee->getParent();
1177 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1178 CI->getType());
1179 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1180
Chris Bienemanad070d02014-09-17 20:55:46 +00001181 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1182 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1183 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001184 }
1185
Chris Bienemanad070d02014-09-17 20:55:46 +00001186 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1187 return Op1;
1188 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1189 return B.CreateFMul(Op1, Op1, "pow2");
1190 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1191 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001192
1193 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001194 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001195 APFloat V = abs(Op2C->getValueAPF());
1196 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1197 // This transformation applies to integer exponents only.
1198 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1199 !V.isInteger())
1200 return nullptr;
1201
Davide Italianof8711f02017-01-10 18:02:05 +00001202 // Propagate fast math flags.
1203 IRBuilder<>::FastMathFlagGuard Guard(B);
1204 B.setFastMathFlags(CI->getFastMathFlags());
1205
Weiming Zhao82130722015-12-04 22:00:47 +00001206 // We will memoize intermediate products of the Addition Chain.
1207 Value *InnerChain[33] = {nullptr};
1208 InnerChain[1] = Op1;
1209 InnerChain[2] = B.CreateFMul(Op1, Op1);
1210
1211 // We cannot readily convert a non-double type (like float) to a double.
1212 // So we first convert V to something which could be converted to double.
1213 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001214 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001215
Weiming Zhao82130722015-12-04 22:00:47 +00001216 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1217 // For negative exponents simply compute the reciprocal.
1218 if (Op2C->isNegative())
1219 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1220 return FMul;
1221 }
1222
Chris Bienemanad070d02014-09-17 20:55:46 +00001223 return nullptr;
1224}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001225
Chris Bienemanad070d02014-09-17 20:55:46 +00001226Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1227 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001228 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001229 StringRef Name = Callee->getName();
1230 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001231 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001232
Chris Bienemanad070d02014-09-17 20:55:46 +00001233 Value *Op = CI->getArgOperand(0);
1234 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1235 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001236 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001237 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001238 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001239 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001240 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001241
1242 if (TLI->has(LdExp)) {
1243 Value *LdExpArg = nullptr;
1244 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1245 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1246 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1247 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1248 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1249 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1250 }
1251
1252 if (LdExpArg) {
1253 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1254 if (!Op->getType()->isFloatTy())
1255 One = ConstantExpr::getFPExtend(One, Op->getType());
1256
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001257 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001258 Value *NewCallee =
1259 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001260 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001261 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001262 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1263 CI->setCallingConv(F->getCallingConv());
1264
1265 return CI;
1266 }
1267 }
1268 return Ret;
1269}
1270
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001271Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001272 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001273 // If we can shrink the call to a float function rather than a double
1274 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001275 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001276 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1277 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001278 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001279
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001280 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001281 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001282 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001283 // Unsafe algebra sets all fast-math-flags to true.
1284 FMF.setUnsafeAlgebra();
1285 } else {
1286 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001287 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001288 return nullptr;
1289 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1290 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001291 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001292 // might be impractical."
1293 FMF.setNoSignedZeros();
1294 FMF.setNoNaNs();
1295 }
Sanjay Patela2528152016-01-12 18:03:37 +00001296 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001297
1298 // We have a relaxed floating-point environment. We can ignore NaN-handling
1299 // and transform to a compare and select. We do not have to consider errno or
1300 // exceptions, because fmin/fmax do not have those.
1301 Value *Op0 = CI->getArgOperand(0);
1302 Value *Op1 = CI->getArgOperand(1);
1303 Value *Cmp = Callee->getName().startswith("fmin") ?
1304 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1305 return B.CreateSelect(Cmp, Op0, Op1);
1306}
1307
Davide Italianob8b71332015-11-29 20:58:04 +00001308Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1309 Function *Callee = CI->getCalledFunction();
1310 Value *Ret = nullptr;
1311 StringRef Name = Callee->getName();
1312 if (UnsafeFPShrink && hasFloatVersion(Name))
1313 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001314
Sanjay Patele896ede2016-01-11 23:31:48 +00001315 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001316 return Ret;
1317 Value *Op1 = CI->getArgOperand(0);
1318 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001319
1320 // The earlier call must also be unsafe in order to do these transforms.
1321 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001322 return Ret;
1323
1324 // log(pow(x,y)) -> y*log(x)
1325 // This is only applicable to log, log2, log10.
1326 if (Name != "log" && Name != "log2" && Name != "log10")
1327 return Ret;
1328
1329 IRBuilder<>::FastMathFlagGuard Guard(B);
1330 FastMathFlags FMF;
1331 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001332 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001333
David L. Jonesd21529f2017-01-23 23:16:46 +00001334 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001335 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001336 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001337 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001338 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001339 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001340 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001341
1342 // log(exp2(y)) -> y*log(2)
1343 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001344 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001345 return B.CreateFMul(
1346 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001347 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001348 Callee->getName(), B, Callee->getAttributes()),
1349 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001350 return Ret;
1351}
1352
Sanjay Patelc699a612014-10-16 18:48:17 +00001353Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1354 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001355 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001356 // TODO: Once we have a way (other than checking for the existince of the
1357 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1358 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001359 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001360 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001361 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001362
1363 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001364 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001365
Sanjay Patelc2d64612016-01-06 20:52:21 +00001366 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1367 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1368 return Ret;
1369
1370 // We're looking for a repeated factor in a multiplication tree,
1371 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001372 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001373 Value *Op0 = I->getOperand(0);
1374 Value *Op1 = I->getOperand(1);
1375 Value *RepeatOp = nullptr;
1376 Value *OtherOp = nullptr;
1377 if (Op0 == Op1) {
1378 // Simple match: the operands of the multiply are identical.
1379 RepeatOp = Op0;
1380 } else {
1381 // Look for a more complicated pattern: one of the operands is itself
1382 // a multiply, so search for a common factor in that multiply.
1383 // Note: We don't bother looking any deeper than this first level or for
1384 // variations of this pattern because instcombine's visitFMUL and/or the
1385 // reassociation pass should give us this form.
1386 Value *OtherMul0, *OtherMul1;
1387 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1388 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001389 if (OtherMul0 == OtherMul1 &&
1390 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001391 // Matched: sqrt((x * x) * z)
1392 RepeatOp = OtherMul0;
1393 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001394 }
1395 }
1396 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001397 if (!RepeatOp)
1398 return Ret;
1399
1400 // Fast math flags for any created instructions should match the sqrt
1401 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001402 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001403 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001404
Sanjay Patelc2d64612016-01-06 20:52:21 +00001405 // If we found a repeated factor, hoist it out of the square root and
1406 // replace it with the fabs of that factor.
1407 Module *M = Callee->getParent();
1408 Type *ArgType = I->getType();
1409 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1410 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1411 if (OtherOp) {
1412 // If we found a non-repeated factor, we still need to get its square
1413 // root. We then multiply that by the value that was simplified out
1414 // of the square root calculation.
1415 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1416 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1417 return B.CreateFMul(FabsCall, SqrtCall);
1418 }
1419 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001420}
1421
Sanjay Patelcddcd722016-01-06 19:23:35 +00001422// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001423Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1424 Function *Callee = CI->getCalledFunction();
1425 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001426 StringRef Name = Callee->getName();
1427 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001428 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001429
Davide Italiano51507d22015-11-04 23:36:56 +00001430 Value *Op1 = CI->getArgOperand(0);
1431 auto *OpC = dyn_cast<CallInst>(Op1);
1432 if (!OpC)
1433 return Ret;
1434
Sanjay Patelcddcd722016-01-06 19:23:35 +00001435 // Both calls must allow unsafe optimizations in order to remove them.
1436 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1437 return Ret;
1438
Davide Italiano51507d22015-11-04 23:36:56 +00001439 // tan(atan(x)) -> x
1440 // tanf(atanf(x)) -> x
1441 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001442 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001443 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001444 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001445 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1446 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1447 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001448 Ret = OpC->getArgOperand(0);
1449 return Ret;
1450}
1451
Sanjay Patel57747212016-01-21 23:38:43 +00001452static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001453 // We can only hope to do anything useful if we can ignore things like errno
1454 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001455 // We already checked the prototype.
1456 return CI->hasFnAttr(Attribute::NoUnwind) &&
1457 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001458}
1459
Chris Bienemanad070d02014-09-17 20:55:46 +00001460static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1461 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001462 Value *&SinCos) {
1463 Type *ArgTy = Arg->getType();
1464 Type *ResTy;
1465 StringRef Name;
1466
1467 Triple T(OrigCallee->getParent()->getTargetTriple());
1468 if (UseFloat) {
1469 Name = "__sincospif_stret";
1470
1471 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1472 // x86_64 can't use {float, float} since that would be returned in both
1473 // xmm0 and xmm1, which isn't what a real struct would do.
1474 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001475 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1476 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001477 } else {
1478 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001479 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001480 }
1481
1482 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001483 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001484 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001485
1486 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1487 // If the argument is an instruction, it must dominate all uses so put our
1488 // sincos call there.
1489 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1490 } else {
1491 // Otherwise (e.g. for a constant) the beginning of the function is as
1492 // good a place as any.
1493 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1494 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1495 }
1496
1497 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1498
1499 if (SinCos->getType()->isStructTy()) {
1500 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1501 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1502 } else {
1503 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1504 "sinpi");
1505 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1506 "cospi");
1507 }
1508}
Chris Bienemanad070d02014-09-17 20:55:46 +00001509
1510Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001511 // Make sure the prototype is as expected, otherwise the rest of the
1512 // function is probably invalid and likely to abort.
1513 if (!isTrigLibCall(CI))
1514 return nullptr;
1515
1516 Value *Arg = CI->getArgOperand(0);
1517 SmallVector<CallInst *, 1> SinCalls;
1518 SmallVector<CallInst *, 1> CosCalls;
1519 SmallVector<CallInst *, 1> SinCosCalls;
1520
1521 bool IsFloat = Arg->getType()->isFloatTy();
1522
1523 // Look for all compatible sinpi, cospi and sincospi calls with the same
1524 // argument. If there are enough (in some sense) we can make the
1525 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001526 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001527 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001528 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001529
1530 // It's only worthwhile if both sinpi and cospi are actually used.
1531 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1532 return nullptr;
1533
1534 Value *Sin, *Cos, *SinCos;
1535 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1536
Davide Italianof024a562016-12-16 02:28:38 +00001537 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1538 Value *Res) {
1539 for (CallInst *C : Calls)
1540 replaceAllUsesWith(C, Res);
1541 };
1542
Chris Bienemanad070d02014-09-17 20:55:46 +00001543 replaceTrigInsts(SinCalls, Sin);
1544 replaceTrigInsts(CosCalls, Cos);
1545 replaceTrigInsts(SinCosCalls, SinCos);
1546
1547 return nullptr;
1548}
1549
David Majnemerabae6b52016-03-19 04:53:02 +00001550void LibCallSimplifier::classifyArgUse(
1551 Value *Val, Function *F, bool IsFloat,
1552 SmallVectorImpl<CallInst *> &SinCalls,
1553 SmallVectorImpl<CallInst *> &CosCalls,
1554 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 CallInst *CI = dyn_cast<CallInst>(Val);
1556
1557 if (!CI)
1558 return;
1559
David Majnemerabae6b52016-03-19 04:53:02 +00001560 // Don't consider calls in other functions.
1561 if (CI->getFunction() != F)
1562 return;
1563
Chris Bienemanad070d02014-09-17 20:55:46 +00001564 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001565 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001566 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001567 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001568 return;
1569
1570 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001571 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001572 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001573 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001574 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001575 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001576 SinCosCalls.push_back(CI);
1577 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001578 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001579 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001580 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001581 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001582 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001583 SinCosCalls.push_back(CI);
1584 }
1585}
1586
Meador Inge7415f842012-11-25 20:45:27 +00001587//===----------------------------------------------------------------------===//
1588// Integer Library Call Optimizations
1589//===----------------------------------------------------------------------===//
1590
Chris Bienemanad070d02014-09-17 20:55:46 +00001591Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001592 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001593 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001594 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001595 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1596 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001597 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1599 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001600
Chris Bienemanad070d02014-09-17 20:55:46 +00001601 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1602 return B.CreateSelect(Cond, V, B.getInt32(0));
1603}
Meador Ingea0b6d872012-11-26 00:24:07 +00001604
Davide Italiano85ad36b2016-12-15 23:45:11 +00001605Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1606 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1607 Value *Op = CI->getArgOperand(0);
1608 Type *ArgType = Op->getType();
1609 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1610 Intrinsic::ctlz, ArgType);
1611 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1612 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1613 V);
1614 return B.CreateIntCast(V, CI->getType(), false);
1615}
1616
Chris Bienemanad070d02014-09-17 20:55:46 +00001617Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 // abs(x) -> x >s -1 ? x : -x
1619 Value *Op = CI->getArgOperand(0);
1620 Value *Pos =
1621 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1622 Value *Neg = B.CreateNeg(Op, "neg");
1623 return B.CreateSelect(Pos, Op, Neg);
1624}
Meador Inge9a59ab62012-11-26 02:31:59 +00001625
Chris Bienemanad070d02014-09-17 20:55:46 +00001626Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001627 // isdigit(c) -> (c-'0') <u 10
1628 Value *Op = CI->getArgOperand(0);
1629 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1630 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1631 return B.CreateZExt(Op, CI->getType());
1632}
Meador Ingea62a39e2012-11-26 03:10:07 +00001633
Chris Bienemanad070d02014-09-17 20:55:46 +00001634Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001635 // isascii(c) -> c <u 128
1636 Value *Op = CI->getArgOperand(0);
1637 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1638 return B.CreateZExt(Op, CI->getType());
1639}
1640
1641Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001642 // toascii(c) -> c & 0x7f
1643 return B.CreateAnd(CI->getArgOperand(0),
1644 ConstantInt::get(CI->getType(), 0x7F));
1645}
Meador Inge604937d2012-11-26 03:38:52 +00001646
Meador Inge08ca1152012-11-26 20:37:20 +00001647//===----------------------------------------------------------------------===//
1648// Formatting and IO Library Call Optimizations
1649//===----------------------------------------------------------------------===//
1650
Chris Bienemanad070d02014-09-17 20:55:46 +00001651static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001652
Chris Bienemanad070d02014-09-17 20:55:46 +00001653Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1654 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001655 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001656 // Error reporting calls should be cold, mark them as such.
1657 // This applies even to non-builtin calls: it is only a hint and applies to
1658 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001659
Chris Bienemanad070d02014-09-17 20:55:46 +00001660 // This heuristic was suggested in:
1661 // Improving Static Branch Prediction in a Compiler
1662 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1663 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 if (!CI->hasFnAttr(Attribute::Cold) &&
1665 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001666 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001667 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001668
Chris Bienemanad070d02014-09-17 20:55:46 +00001669 return nullptr;
1670}
1671
1672static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001673 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001674 return false;
1675
1676 if (StreamArg < 0)
1677 return true;
1678
1679 // These functions might be considered cold, but only if their stream
1680 // argument is stderr.
1681
1682 if (StreamArg >= (int)CI->getNumArgOperands())
1683 return false;
1684 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1685 if (!LI)
1686 return false;
1687 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1688 if (!GV || !GV->isDeclaration())
1689 return false;
1690 return GV->getName() == "stderr";
1691}
1692
1693Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1694 // Check for a fixed format string.
1695 StringRef FormatStr;
1696 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001697 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001698
Chris Bienemanad070d02014-09-17 20:55:46 +00001699 // Empty format string -> noop.
1700 if (FormatStr.empty()) // Tolerate printf's declared void.
1701 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001702
Chris Bienemanad070d02014-09-17 20:55:46 +00001703 // Do not do any of the following transformations if the printf return value
1704 // is used, in general the printf return value is not compatible with either
1705 // putchar() or puts().
1706 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001707 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001708
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001709 // printf("x") -> putchar('x'), even for "%" and "%%".
1710 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001711 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001712
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001713 // printf("%s", "a") --> putchar('a')
1714 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1715 StringRef ChrStr;
1716 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1717 return nullptr;
1718 if (ChrStr.size() != 1)
1719 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001720 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001721 }
1722
Chris Bienemanad070d02014-09-17 20:55:46 +00001723 // printf("foo\n") --> puts("foo")
1724 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1725 FormatStr.find('%') == StringRef::npos) { // No format characters.
1726 // Create a string literal with no \n on it. We expect the constant merge
1727 // pass to be run after this pass, to merge duplicate strings.
1728 FormatStr = FormatStr.drop_back();
1729 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001730 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001731 }
Meador Inge08ca1152012-11-26 20:37:20 +00001732
Chris Bienemanad070d02014-09-17 20:55:46 +00001733 // Optimize specific format strings.
1734 // printf("%c", chr) --> putchar(chr)
1735 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001736 CI->getArgOperand(1)->getType()->isIntegerTy())
1737 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001738
1739 // printf("%s\n", str) --> puts(str)
1740 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001741 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001742 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 return nullptr;
1744}
1745
1746Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1747
1748 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001749 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001750 if (Value *V = optimizePrintFString(CI, B)) {
1751 return V;
1752 }
1753
1754 // printf(format, ...) -> iprintf(format, ...) if no floating point
1755 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001756 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001757 Module *M = B.GetInsertBlock()->getParent()->getParent();
1758 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001759 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001760 CallInst *New = cast<CallInst>(CI->clone());
1761 New->setCalledFunction(IPrintFFn);
1762 B.Insert(New);
1763 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001764 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 return nullptr;
1766}
Meador Inge08ca1152012-11-26 20:37:20 +00001767
Chris Bienemanad070d02014-09-17 20:55:46 +00001768Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1769 // Check for a fixed format string.
1770 StringRef FormatStr;
1771 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001772 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001773
Chris Bienemanad070d02014-09-17 20:55:46 +00001774 // If we just have a format string (nothing else crazy) transform it.
1775 if (CI->getNumArgOperands() == 2) {
1776 // Make sure there's no % in the constant array. We could try to handle
1777 // %% -> % in the future if we cared.
1778 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1779 if (FormatStr[i] == '%')
1780 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001781
Chris Bienemanad070d02014-09-17 20:55:46 +00001782 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001783 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1784 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1785 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001786 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001787 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001788 }
Meador Ingef8e72502012-11-29 15:45:43 +00001789
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 // The remaining optimizations require the format string to be "%s" or "%c"
1791 // and have an extra operand.
1792 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1793 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001794 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001795
Chris Bienemanad070d02014-09-17 20:55:46 +00001796 // Decode the second character of the format string.
1797 if (FormatStr[1] == 'c') {
1798 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1799 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1800 return nullptr;
1801 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001802 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001803 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001804 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001805 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001806
Chris Bienemanad070d02014-09-17 20:55:46 +00001807 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001808 }
1809
Chris Bienemanad070d02014-09-17 20:55:46 +00001810 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001811 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1812 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1813 return nullptr;
1814
Sanjay Pateld3112a52016-01-19 19:46:10 +00001815 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001816 if (!Len)
1817 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001818 Value *IncLen =
1819 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1820 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001821
1822 // The sprintf result is the unincremented number of bytes in the string.
1823 return B.CreateIntCast(Len, CI->getType(), false);
1824 }
1825 return nullptr;
1826}
1827
1828Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1829 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001830 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001831 if (Value *V = optimizeSPrintFString(CI, B)) {
1832 return V;
1833 }
1834
1835 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1836 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001837 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001838 Module *M = B.GetInsertBlock()->getParent()->getParent();
1839 Constant *SIPrintFFn =
1840 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1841 CallInst *New = cast<CallInst>(CI->clone());
1842 New->setCalledFunction(SIPrintFFn);
1843 B.Insert(New);
1844 return New;
1845 }
1846 return nullptr;
1847}
1848
1849Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1850 optimizeErrorReporting(CI, B, 0);
1851
1852 // All the optimizations depend on the format string.
1853 StringRef FormatStr;
1854 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1855 return nullptr;
1856
1857 // Do not do any of the following transformations if the fprintf return
1858 // value is used, in general the fprintf return value is not compatible
1859 // with fwrite(), fputc() or fputs().
1860 if (!CI->use_empty())
1861 return nullptr;
1862
1863 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1864 if (CI->getNumArgOperands() == 2) {
1865 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1866 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1867 return nullptr; // We found a format specifier.
1868
Sanjay Pateld3112a52016-01-19 19:46:10 +00001869 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001870 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001871 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001872 CI->getArgOperand(0), B, DL, TLI);
1873 }
1874
1875 // The remaining optimizations require the format string to be "%s" or "%c"
1876 // and have an extra operand.
1877 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1878 CI->getNumArgOperands() < 3)
1879 return nullptr;
1880
1881 // Decode the second character of the format string.
1882 if (FormatStr[1] == 'c') {
1883 // fprintf(F, "%c", chr) --> fputc(chr, F)
1884 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1885 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001886 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001887 }
1888
1889 if (FormatStr[1] == 's') {
1890 // fprintf(F, "%s", str) --> fputs(str, F)
1891 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1892 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001893 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001894 }
1895 return nullptr;
1896}
1897
1898Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1899 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001900 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001901 if (Value *V = optimizeFPrintFString(CI, B)) {
1902 return V;
1903 }
1904
1905 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1906 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001907 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001908 Module *M = B.GetInsertBlock()->getParent()->getParent();
1909 Constant *FIPrintFFn =
1910 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1911 CallInst *New = cast<CallInst>(CI->clone());
1912 New->setCalledFunction(FIPrintFFn);
1913 B.Insert(New);
1914 return New;
1915 }
1916 return nullptr;
1917}
1918
1919Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1920 optimizeErrorReporting(CI, B, 3);
1921
Chris Bienemanad070d02014-09-17 20:55:46 +00001922 // Get the element size and count.
1923 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1924 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1925 if (!SizeC || !CountC)
1926 return nullptr;
1927 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1928
1929 // If this is writing zero records, remove the call (it's a noop).
1930 if (Bytes == 0)
1931 return ConstantInt::get(CI->getType(), 0);
1932
1933 // If this is writing one byte, turn it into fputc.
1934 // This optimisation is only valid, if the return value is unused.
1935 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001936 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1937 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001938 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1939 }
1940
1941 return nullptr;
1942}
1943
1944Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1945 optimizeErrorReporting(CI, B, 1);
1946
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001947 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1948 // requires more arguments and thus extra MOVs are required.
1949 if (CI->getParent()->getParent()->optForSize())
1950 return nullptr;
1951
Ahmed Bougachad765a822016-04-27 19:04:35 +00001952 // We can't optimize if return value is used.
1953 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001954 return nullptr;
1955
1956 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1957 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1958 if (!Len)
1959 return nullptr;
1960
1961 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001962 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001963 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001964 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001965 CI->getArgOperand(1), B, DL, TLI);
1966}
1967
1968Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001969 // Check for a constant string.
1970 StringRef Str;
1971 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1972 return nullptr;
1973
1974 if (Str.empty() && CI->use_empty()) {
1975 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001976 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001977 if (CI->use_empty() || !Res)
1978 return Res;
1979 return B.CreateIntCast(Res, CI->getType(), true);
1980 }
1981
1982 return nullptr;
1983}
1984
1985bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001986 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001987 SmallString<20> FloatFuncName = FuncName;
1988 FloatFuncName += 'f';
1989 if (TLI->getLibFunc(FloatFuncName, Func))
1990 return TLI->has(Func);
1991 return false;
1992}
Meador Inge7fb2f732012-10-13 16:45:32 +00001993
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001994Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1995 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001996 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001997 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001999 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 // Make sure we never change the calling convention.
2001 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002002 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002003 "Optimizing string/memory libcall would change the calling convention");
2004 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002005 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002006 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002007 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002008 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002009 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002010 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002011 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002012 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002013 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002014 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002015 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002016 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002017 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002018 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002019 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002020 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002021 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002022 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002024 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002025 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002026 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002027 case LibFunc_strtol:
2028 case LibFunc_strtod:
2029 case LibFunc_strtof:
2030 case LibFunc_strtoul:
2031 case LibFunc_strtoll:
2032 case LibFunc_strtold:
2033 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002034 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002035 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002036 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002037 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002038 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002039 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002040 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002041 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002042 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002043 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002044 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002045 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002046 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002047 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002048 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002049 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002050 return optimizeMemSet(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002051 case LibFunc_wcslen:
2052 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002053 default:
2054 break;
2055 }
2056 }
2057 return nullptr;
2058}
2059
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002060Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2061 LibFunc Func,
2062 IRBuilder<> &Builder) {
2063 // Don't optimize calls that require strict floating point semantics.
2064 if (CI->isStrictFP())
2065 return nullptr;
2066
2067 switch (Func) {
2068 case LibFunc_cosf:
2069 case LibFunc_cos:
2070 case LibFunc_cosl:
2071 return optimizeCos(CI, Builder);
2072 case LibFunc_sinpif:
2073 case LibFunc_sinpi:
2074 case LibFunc_cospif:
2075 case LibFunc_cospi:
2076 return optimizeSinCosPi(CI, Builder);
2077 case LibFunc_powf:
2078 case LibFunc_pow:
2079 case LibFunc_powl:
2080 return optimizePow(CI, Builder);
2081 case LibFunc_exp2l:
2082 case LibFunc_exp2:
2083 case LibFunc_exp2f:
2084 return optimizeExp2(CI, Builder);
2085 case LibFunc_fabsf:
2086 case LibFunc_fabs:
2087 case LibFunc_fabsl:
2088 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2089 case LibFunc_sqrtf:
2090 case LibFunc_sqrt:
2091 case LibFunc_sqrtl:
2092 return optimizeSqrt(CI, Builder);
2093 case LibFunc_log:
2094 case LibFunc_log10:
2095 case LibFunc_log1p:
2096 case LibFunc_log2:
2097 case LibFunc_logb:
2098 return optimizeLog(CI, Builder);
2099 case LibFunc_tan:
2100 case LibFunc_tanf:
2101 case LibFunc_tanl:
2102 return optimizeTan(CI, Builder);
2103 case LibFunc_ceil:
2104 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2105 case LibFunc_floor:
2106 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2107 case LibFunc_round:
2108 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2109 case LibFunc_nearbyint:
2110 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2111 case LibFunc_rint:
2112 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2113 case LibFunc_trunc:
2114 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2115 case LibFunc_acos:
2116 case LibFunc_acosh:
2117 case LibFunc_asin:
2118 case LibFunc_asinh:
2119 case LibFunc_atan:
2120 case LibFunc_atanh:
2121 case LibFunc_cbrt:
2122 case LibFunc_cosh:
2123 case LibFunc_exp:
2124 case LibFunc_exp10:
2125 case LibFunc_expm1:
2126 case LibFunc_sin:
2127 case LibFunc_sinh:
2128 case LibFunc_tanh:
2129 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2130 return optimizeUnaryDoubleFP(CI, Builder, true);
2131 return nullptr;
2132 case LibFunc_copysign:
2133 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2134 return optimizeBinaryDoubleFP(CI, Builder);
2135 return nullptr;
2136 case LibFunc_fminf:
2137 case LibFunc_fmin:
2138 case LibFunc_fminl:
2139 case LibFunc_fmaxf:
2140 case LibFunc_fmax:
2141 case LibFunc_fmaxl:
2142 return optimizeFMinFMax(CI, Builder);
2143 default:
2144 return nullptr;
2145 }
2146}
2147
Chris Bienemanad070d02014-09-17 20:55:46 +00002148Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002149 // TODO: Split out the code below that operates on FP calls so that
2150 // we can all non-FP calls with the StrictFP attribute to be
2151 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002152 if (CI->isNoBuiltin())
2153 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002154
David L. Jonesd21529f2017-01-23 23:16:46 +00002155 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002156 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002157
2158 SmallVector<OperandBundleDef, 2> OpBundles;
2159 CI->getOperandBundlesAsDefs(OpBundles);
2160 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002161 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002162
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002163 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002164 // This can't be moved to optimizeFloatingPointLibCall() because it may be
2165 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002166 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2167 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002168 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002169 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002170
Sanjay Patel848309d2014-10-23 21:52:45 +00002171 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002172 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002173 if (!isCallingConvC)
2174 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002175 // The FP intrinsics have corresponding constrained versions so we don't
2176 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002177 switch (II->getIntrinsicID()) {
2178 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002179 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002180 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002181 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002182 case Intrinsic::log:
2183 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002184 case Intrinsic::sqrt:
2185 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002186 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002187 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002188 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002189 }
2190 }
2191
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002192 // Also try to simplify calls to fortified library functions.
2193 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2194 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002195 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002196 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2197 // Use an IR Builder from SimplifiedCI if available instead of CI
2198 // to guarantee we reach all uses we might replace later on.
2199 IRBuilder<> TmpBuilder(SimplifiedCI);
2200 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002201 // If we were able to further simplify, remove the now redundant call.
2202 SimplifiedCI->replaceAllUsesWith(V);
2203 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002204 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002205 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002206 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002207 return SimplifiedFortifiedCI;
2208 }
2209
Meador Inge20255ef2013-03-12 00:08:29 +00002210 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002211 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002212 // We never change the calling convention.
2213 if (!ignoreCallingConv(Func) && !isCallingConvC)
2214 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002215 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2216 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002217 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2218 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002219 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002220 case LibFunc_ffs:
2221 case LibFunc_ffsl:
2222 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002223 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002224 case LibFunc_fls:
2225 case LibFunc_flsl:
2226 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002227 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002228 case LibFunc_abs:
2229 case LibFunc_labs:
2230 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002231 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002232 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002233 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002234 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002235 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002236 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002237 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002238 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002239 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002240 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002241 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002242 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002243 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002244 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002245 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002246 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002247 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002248 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002249 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002250 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002251 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002252 case LibFunc_vfprintf:
2253 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002254 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002255 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002256 return optimizeErrorReporting(CI, Builder, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002257 default:
2258 return nullptr;
2259 }
Meador Inge20255ef2013-03-12 00:08:29 +00002260 }
Craig Topperf40110f2014-04-25 05:29:35 +00002261 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002262}
2263
Chandler Carruth92803822015-01-21 02:11:59 +00002264LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002265 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002266 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002267 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002268 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2269 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002270
2271void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2272 // Indirect through the replacer used in this instance.
2273 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002274}
2275
Meador Ingedfb08a22013-06-20 19:48:07 +00002276// TODO:
2277// Additional cases that we need to add to this file:
2278//
2279// cbrt:
2280// * cbrt(expN(X)) -> expN(x/3)
2281// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002282// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002283//
2284// exp, expf, expl:
2285// * exp(log(x)) -> x
2286//
2287// log, logf, logl:
2288// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002289// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002290// * log(exp10(y)) -> y*log(10)
2291// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002292//
Meador Ingedfb08a22013-06-20 19:48:07 +00002293// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002294// * pow(sqrt(x),y) -> pow(x,y*0.5)
2295// * pow(pow(x,y),z)-> pow(x,y*z)
2296//
Meador Ingedfb08a22013-06-20 19:48:07 +00002297// signbit:
2298// * signbit(cnst) -> cnst'
2299// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2300//
2301// sqrt, sqrtf, sqrtl:
2302// * sqrt(expN(x)) -> expN(x*0.5)
2303// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2304// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2305//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002306
2307//===----------------------------------------------------------------------===//
2308// Fortified Library Call Optimizations
2309//===----------------------------------------------------------------------===//
2310
2311bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2312 unsigned ObjSizeOp,
2313 unsigned SizeOp,
2314 bool isString) {
2315 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2316 return true;
2317 if (ConstantInt *ObjSizeCI =
2318 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002319 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002320 return true;
2321 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2322 if (OnlyLowerUnknownSize)
2323 return false;
2324 if (isString) {
2325 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2326 // If the length is 0 we don't know how long it is and so we can't
2327 // remove the check.
2328 if (Len == 0)
2329 return false;
2330 return ObjSizeCI->getZExtValue() >= Len;
2331 }
2332 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2333 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2334 }
2335 return false;
2336}
2337
Sanjay Pateld707db92015-12-31 16:10:49 +00002338Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2339 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002340 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2341 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002342 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002343 return CI->getArgOperand(0);
2344 }
2345 return nullptr;
2346}
2347
Sanjay Pateld707db92015-12-31 16:10:49 +00002348Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2349 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002350 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2351 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002352 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002353 return CI->getArgOperand(0);
2354 }
2355 return nullptr;
2356}
2357
Sanjay Pateld707db92015-12-31 16:10:49 +00002358Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2359 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002360 // TODO: Try foldMallocMemset() here.
2361
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002362 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2363 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2364 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2365 return CI->getArgOperand(0);
2366 }
2367 return nullptr;
2368}
2369
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002370Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2371 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002372 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002373 Function *Callee = CI->getCalledFunction();
2374 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002375 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002376 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2377 *ObjSize = CI->getArgOperand(2);
2378
2379 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002380 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002381 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002382 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002383 }
2384
2385 // If a) we don't have any length information, or b) we know this will
2386 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2387 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2388 // TODO: It might be nice to get a maximum length out of the possible
2389 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002390 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002391 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002392
David Blaikie65fab6d2015-04-03 21:32:06 +00002393 if (OnlyLowerUnknownSize)
2394 return nullptr;
2395
2396 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2397 uint64_t Len = GetStringLength(Src);
2398 if (Len == 0)
2399 return nullptr;
2400
2401 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2402 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002403 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002404 // If the function was an __stpcpy_chk, and we were able to fold it into
2405 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002406 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002407 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2408 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002409}
2410
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002411Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2412 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002413 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414 Function *Callee = CI->getCalledFunction();
2415 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002417 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002418 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002419 return Ret;
2420 }
2421 return nullptr;
2422}
2423
2424Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002425 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2426 // Some clang users checked for _chk libcall availability using:
2427 // __has_builtin(__builtin___memcpy_chk)
2428 // When compiling with -fno-builtin, this is always true.
2429 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2430 // end up with fortified libcalls, which isn't acceptable in a freestanding
2431 // environment which only provides their non-fortified counterparts.
2432 //
2433 // Until we change clang and/or teach external users to check for availability
2434 // differently, disregard the "nobuiltin" attribute and TLI::has.
2435 //
2436 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002437
David L. Jonesd21529f2017-01-23 23:16:46 +00002438 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002439 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002440
2441 SmallVector<OperandBundleDef, 2> OpBundles;
2442 CI->getOperandBundlesAsDefs(OpBundles);
2443 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002444 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002445
Ahmed Bougachad765a822016-04-27 19:04:35 +00002446 // First, check that this is a known library functions and that the prototype
2447 // is correct.
2448 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002449 return nullptr;
2450
2451 // We never change the calling convention.
2452 if (!ignoreCallingConv(Func) && !isCallingConvC)
2453 return nullptr;
2454
2455 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002456 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002457 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002458 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002459 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002460 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002461 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002462 case LibFunc_stpcpy_chk:
2463 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002464 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002465 case LibFunc_stpncpy_chk:
2466 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002467 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002468 default:
2469 break;
2470 }
2471 return nullptr;
2472}
2473
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002474FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2475 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2476 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}