blob: 4252cf58fef23fcddcd9aeefb53650f9680a1dfa [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"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000031#include "llvm/IR/PatternMatch.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000032#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000041 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000043
Sanjay Patela92fa442014-10-22 15:29:23 +000044static cl::opt<bool>
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
Chris Bienemanad070d02014-09-17 20:55:46 +000055static bool ignoreCallingConv(LibFunc::Func Func) {
Davide Italianob883b012015-11-12 23:39:00 +000056 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000058}
59
Sanjay Pateld707db92015-12-31 16:10:49 +000060/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000061static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000062 for (User *U : V->users()) {
63 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000064 if (IC->isEquality())
65 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
66 if (C->isNullValue())
67 continue;
68 // Unknown instruction.
69 return false;
70 }
71 return true;
72}
73
Sanjay Pateld707db92015-12-31 16:10:49 +000074/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000075static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000076 for (User *U : V->users()) {
77 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000078 if (IC->isEquality() && IC->getOperand(1) == With)
79 continue;
80 // Unknown instruction.
81 return false;
82 }
83 return true;
84}
85
Meador Inge08ca1152012-11-26 20:37:20 +000086static bool callHasFloatingPointArgument(const CallInst *CI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +000087 return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
88 return OI->getType()->isFloatingPointTy();
89 });
Meador Inge08ca1152012-11-26 20:37:20 +000090}
91
Benjamin Kramer2702caa2013-08-31 18:19:35 +000092/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000093/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000094static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
95 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
96 LibFunc::Func LongDoubleFn) {
97 switch (Ty->getTypeID()) {
98 case Type::FloatTyID:
99 return TLI->has(FloatFn);
100 case Type::DoubleTyID:
101 return TLI->has(DoubleFn);
102 default:
103 return TLI->has(LongDoubleFn);
104 }
105}
106
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000107/// \brief Returns whether \p F matches the signature expected for the
108/// string/memory copying library function \p Func.
109/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
110/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000111static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
112 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000113 FunctionType *FT = F->getFunctionType();
114 LLVMContext &Context = F->getContext();
115 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000116 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000117 unsigned NumParams = FT->getNumParams();
118
119 // All string libfuncs return the same type as the first parameter.
120 if (FT->getReturnType() != FT->getParamType(0))
121 return false;
122
123 switch (Func) {
124 default:
125 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
126 case LibFunc::stpncpy_chk:
127 case LibFunc::strncpy_chk:
128 --NumParams; // fallthrough
129 case LibFunc::stpncpy:
130 case LibFunc::strncpy: {
131 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
132 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
133 return false;
134 break;
135 }
136 case LibFunc::strcpy_chk:
137 case LibFunc::stpcpy_chk:
138 --NumParams; // fallthrough
139 case LibFunc::stpcpy:
140 case LibFunc::strcpy: {
141 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
142 FT->getParamType(0) != PCharTy)
143 return false;
144 break;
145 }
146 case LibFunc::memmove_chk:
147 case LibFunc::memcpy_chk:
148 --NumParams; // fallthrough
149 case LibFunc::memmove:
150 case LibFunc::memcpy: {
151 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
152 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
153 return false;
154 break;
155 }
156 case LibFunc::memset_chk:
157 --NumParams; // fallthrough
158 case LibFunc::memset: {
159 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
160 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
161 return false;
162 break;
163 }
164 }
165 // If this is a fortified libcall, the last parameter is a size_t.
166 if (NumParams == FT->getNumParams() - 1)
167 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
168 return true;
169}
170
Meador Inged589ac62012-10-31 03:33:06 +0000171//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000172// String and Memory Library Call Optimizations
173//===----------------------------------------------------------------------===//
174
Chris Bienemanad070d02014-09-17 20:55:46 +0000175Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
176 Function *Callee = CI->getCalledFunction();
177 // Verify the "strcat" function prototype.
178 FunctionType *FT = Callee->getFunctionType();
179 if (FT->getNumParams() != 2||
180 FT->getReturnType() != B.getInt8PtrTy() ||
181 FT->getParamType(0) != FT->getReturnType() ||
182 FT->getParamType(1) != FT->getReturnType())
183 return nullptr;
184
185 // Extract some information from the instruction
186 Value *Dst = CI->getArgOperand(0);
187 Value *Src = CI->getArgOperand(1);
188
189 // See if we can get the length of the input string.
190 uint64_t Len = GetStringLength(Src);
191 if (Len == 0)
192 return nullptr;
193 --Len; // Unbias length.
194
195 // Handle the simple, do-nothing case: strcat(x, "") -> x
196 if (Len == 0)
197 return Dst;
198
Chris Bienemanad070d02014-09-17 20:55:46 +0000199 return emitStrLenMemCpy(Src, Dst, Len, B);
200}
201
202Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
203 IRBuilder<> &B) {
204 // We need to find the end of the destination string. That's where the
205 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000206 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 if (!DstLen)
208 return nullptr;
209
210 // Now that we have the destination's length, we must index into the
211 // destination's pointer to get the actual memcpy destination (end of
212 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000213 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000214
215 // We have enough information to now generate the memcpy call to do the
216 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000217 B.CreateMemCpy(CpyDst, Src,
218 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000219 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000220 return Dst;
221}
222
223Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
224 Function *Callee = CI->getCalledFunction();
225 // Verify the "strncat" function prototype.
226 FunctionType *FT = Callee->getFunctionType();
227 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
228 FT->getParamType(0) != FT->getReturnType() ||
229 FT->getParamType(1) != FT->getReturnType() ||
230 !FT->getParamType(2)->isIntegerTy())
231 return nullptr;
232
Sanjay Pateld707db92015-12-31 16:10:49 +0000233 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000234 Value *Dst = CI->getArgOperand(0);
235 Value *Src = CI->getArgOperand(1);
236 uint64_t Len;
237
Sanjay Pateld707db92015-12-31 16:10:49 +0000238 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
240 Len = LengthArg->getZExtValue();
241 else
242 return nullptr;
243
244 // See if we can get the length of the input string.
245 uint64_t SrcLen = GetStringLength(Src);
246 if (SrcLen == 0)
247 return nullptr;
248 --SrcLen; // Unbias length.
249
250 // Handle the simple, do-nothing cases:
251 // strncat(x, "", c) -> x
252 // strncat(x, c, 0) -> x
253 if (SrcLen == 0 || Len == 0)
254 return Dst;
255
Sanjay Pateld707db92015-12-31 16:10:49 +0000256 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000257 if (Len < SrcLen)
258 return nullptr;
259
260 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000261 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000262 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
263}
264
265Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
266 Function *Callee = CI->getCalledFunction();
267 // Verify the "strchr" function prototype.
268 FunctionType *FT = Callee->getFunctionType();
269 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
270 FT->getParamType(0) != FT->getReturnType() ||
271 !FT->getParamType(1)->isIntegerTy(32))
272 return nullptr;
273
274 Value *SrcStr = CI->getArgOperand(0);
275
276 // If the second operand is non-constant, see if we can compute the length
277 // of the input string and turn this into memchr.
278 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
279 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000280 uint64_t Len = GetStringLength(SrcStr);
281 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
282 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000283
Sanjay Pateld3112a52016-01-19 19:46:10 +0000284 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000285 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
286 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000287 }
288
Chris Bienemanad070d02014-09-17 20:55:46 +0000289 // Otherwise, the character is a constant, see if the first argument is
290 // a string literal. If so, we can constant fold.
291 StringRef Str;
292 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000293 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000294 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000295 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000296 return nullptr;
297 }
298
299 // Compute the offset, make sure to handle the case when we're searching for
300 // zero (a weird way to spell strlen).
301 size_t I = (0xFF & CharC->getSExtValue()) == 0
302 ? Str.size()
303 : Str.find(CharC->getSExtValue());
304 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
305 return Constant::getNullValue(CI->getType());
306
307 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000308 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000309}
310
311Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
312 Function *Callee = CI->getCalledFunction();
313 // Verify the "strrchr" function prototype.
314 FunctionType *FT = Callee->getFunctionType();
315 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
316 FT->getParamType(0) != FT->getReturnType() ||
317 !FT->getParamType(1)->isIntegerTy(32))
318 return nullptr;
319
320 Value *SrcStr = CI->getArgOperand(0);
321 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
322
323 // Cannot fold anything if we're not looking for a constant.
324 if (!CharC)
325 return nullptr;
326
327 StringRef Str;
328 if (!getConstantStringInfo(SrcStr, Str)) {
329 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000330 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000331 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000332 return nullptr;
333 }
334
335 // Compute the offset.
336 size_t I = (0xFF & CharC->getSExtValue()) == 0
337 ? Str.size()
338 : Str.rfind(CharC->getSExtValue());
339 if (I == StringRef::npos) // Didn't find the char. Return null.
340 return Constant::getNullValue(CI->getType());
341
342 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000343 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000344}
345
346Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
347 Function *Callee = CI->getCalledFunction();
348 // Verify the "strcmp" function prototype.
349 FunctionType *FT = Callee->getFunctionType();
350 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
351 FT->getParamType(0) != FT->getParamType(1) ||
352 FT->getParamType(0) != B.getInt8PtrTy())
353 return nullptr;
354
355 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
356 if (Str1P == Str2P) // strcmp(x,x) -> 0
357 return ConstantInt::get(CI->getType(), 0);
358
359 StringRef Str1, Str2;
360 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
361 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
362
363 // strcmp(x, y) -> cnst (if both x and y are constant strings)
364 if (HasStr1 && HasStr2)
365 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
366
367 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
368 return B.CreateNeg(
369 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
370
371 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
372 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
373
374 // strcmp(P, "x") -> memcmp(P, "x", 2)
375 uint64_t Len1 = GetStringLength(Str1P);
376 uint64_t Len2 = GetStringLength(Str2P);
377 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000378 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000379 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000380 std::min(Len1, Len2)),
381 B, DL, TLI);
382 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000383
Chris Bienemanad070d02014-09-17 20:55:46 +0000384 return nullptr;
385}
386
387Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
388 Function *Callee = CI->getCalledFunction();
389 // Verify the "strncmp" function prototype.
390 FunctionType *FT = Callee->getFunctionType();
391 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
392 FT->getParamType(0) != FT->getParamType(1) ||
393 FT->getParamType(0) != B.getInt8PtrTy() ||
394 !FT->getParamType(2)->isIntegerTy())
395 return nullptr;
396
397 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
398 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
399 return ConstantInt::get(CI->getType(), 0);
400
401 // Get the length argument if it is constant.
402 uint64_t Length;
403 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
404 Length = LengthArg->getZExtValue();
405 else
406 return nullptr;
407
408 if (Length == 0) // strncmp(x,y,0) -> 0
409 return ConstantInt::get(CI->getType(), 0);
410
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000411 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000412 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000413
414 StringRef Str1, Str2;
415 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
416 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
417
418 // strncmp(x, y) -> cnst (if both x and y are constant strings)
419 if (HasStr1 && HasStr2) {
420 StringRef SubStr1 = Str1.substr(0, Length);
421 StringRef SubStr2 = Str2.substr(0, Length);
422 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
423 }
424
425 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
426 return B.CreateNeg(
427 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
428
429 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
430 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
431
432 return nullptr;
433}
434
435Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
436 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000437
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000438 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000439 return nullptr;
440
441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
444
Chris Bienemanad070d02014-09-17 20:55:46 +0000445 // See if we can get the length of the input string.
446 uint64_t Len = GetStringLength(Src);
447 if (Len == 0)
448 return nullptr;
449
450 // We have enough information to now generate the memcpy call to do the
451 // copy for us. Make a memcpy to copy the nul byte with align = 1.
452 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000453 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000454 return Dst;
455}
456
457Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
458 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000460 return nullptr;
461
462 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
463 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000464 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000465 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000466 }
467
468 // See if we can get the length of the input string.
469 uint64_t Len = GetStringLength(Src);
470 if (Len == 0)
471 return nullptr;
472
Davide Italianob7487e62015-11-02 23:07:14 +0000473 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000475 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
476 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000477
478 // We have enough information to now generate the memcpy call to do the
479 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000480 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000481 return DstEnd;
482}
483
484Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
485 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000487 return nullptr;
488
489 Value *Dst = CI->getArgOperand(0);
490 Value *Src = CI->getArgOperand(1);
491 Value *LenOp = CI->getArgOperand(2);
492
493 // See if we can get the length of the input string.
494 uint64_t SrcLen = GetStringLength(Src);
495 if (SrcLen == 0)
496 return nullptr;
497 --SrcLen;
498
499 if (SrcLen == 0) {
500 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
501 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000502 return Dst;
503 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 uint64_t Len;
506 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
507 Len = LengthArg->getZExtValue();
508 else
509 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000510
Chris Bienemanad070d02014-09-17 20:55:46 +0000511 if (Len == 0)
512 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000513
Chris Bienemanad070d02014-09-17 20:55:46 +0000514 // Let strncpy handle the zero padding
515 if (Len > SrcLen + 1)
516 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000517
Davide Italianob7487e62015-11-02 23:07:14 +0000518 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000519 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000520 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000521
Chris Bienemanad070d02014-09-17 20:55:46 +0000522 return Dst;
523}
Meador Inge7fb2f732012-10-13 16:45:32 +0000524
Chris Bienemanad070d02014-09-17 20:55:46 +0000525Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
526 Function *Callee = CI->getCalledFunction();
527 FunctionType *FT = Callee->getFunctionType();
528 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
529 !FT->getReturnType()->isIntegerTy())
530 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000531
Chris Bienemanad070d02014-09-17 20:55:46 +0000532 Value *Src = CI->getArgOperand(0);
533
534 // Constant folding: strlen("xyz") -> 3
535 if (uint64_t Len = GetStringLength(Src))
536 return ConstantInt::get(CI->getType(), Len - 1);
537
538 // strlen(x?"foo":"bars") --> x ? 3 : 4
539 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
540 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
541 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
542 if (LenTrue && LenFalse) {
543 Function *Caller = CI->getParent()->getParent();
544 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
545 SI->getDebugLoc(),
546 "folded strlen(select) to select of constants");
547 return B.CreateSelect(SI->getCondition(),
548 ConstantInt::get(CI->getType(), LenTrue - 1),
549 ConstantInt::get(CI->getType(), LenFalse - 1));
550 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000551 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000552
Chris Bienemanad070d02014-09-17 20:55:46 +0000553 // strlen(x) != 0 --> *x != 0
554 // strlen(x) == 0 --> *x == 0
555 if (isOnlyUsedInZeroEqualityComparison(CI))
556 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000557
Chris Bienemanad070d02014-09-17 20:55:46 +0000558 return nullptr;
559}
Meador Inge17418502012-10-13 16:45:37 +0000560
Chris Bienemanad070d02014-09-17 20:55:46 +0000561Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
562 Function *Callee = CI->getCalledFunction();
563 FunctionType *FT = Callee->getFunctionType();
564 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
565 FT->getParamType(1) != FT->getParamType(0) ||
566 FT->getReturnType() != FT->getParamType(0))
567 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000568
Chris Bienemanad070d02014-09-17 20:55:46 +0000569 StringRef S1, S2;
570 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
571 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000572
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000573 // strpbrk(s, "") -> nullptr
574 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
576 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000577
Chris Bienemanad070d02014-09-17 20:55:46 +0000578 // Constant folding.
579 if (HasS1 && HasS2) {
580 size_t I = S1.find_first_of(S2);
581 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000582 return Constant::getNullValue(CI->getType());
583
Sanjay Pateld707db92015-12-31 16:10:49 +0000584 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
585 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000586 }
Meador Inge17418502012-10-13 16:45:37 +0000587
Chris Bienemanad070d02014-09-17 20:55:46 +0000588 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000589 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000590 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000591
592 return nullptr;
593}
594
595Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
596 Function *Callee = CI->getCalledFunction();
597 FunctionType *FT = Callee->getFunctionType();
598 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
599 !FT->getParamType(0)->isPointerTy() ||
600 !FT->getParamType(1)->isPointerTy())
601 return nullptr;
602
603 Value *EndPtr = CI->getArgOperand(1);
604 if (isa<ConstantPointerNull>(EndPtr)) {
605 // With a null EndPtr, this function won't capture the main argument.
606 // It would be readonly too, except that it still may write to errno.
607 CI->addAttribute(1, Attribute::NoCapture);
608 }
609
610 return nullptr;
611}
612
613Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
614 Function *Callee = CI->getCalledFunction();
615 FunctionType *FT = Callee->getFunctionType();
616 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
617 FT->getParamType(1) != FT->getParamType(0) ||
618 !FT->getReturnType()->isIntegerTy())
619 return nullptr;
620
621 StringRef S1, S2;
622 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
623 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
624
625 // strspn(s, "") -> 0
626 // strspn("", s) -> 0
627 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
628 return Constant::getNullValue(CI->getType());
629
630 // Constant folding.
631 if (HasS1 && HasS2) {
632 size_t Pos = S1.find_first_not_of(S2);
633 if (Pos == StringRef::npos)
634 Pos = S1.size();
635 return ConstantInt::get(CI->getType(), Pos);
636 }
637
638 return nullptr;
639}
640
641Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
642 Function *Callee = CI->getCalledFunction();
643 FunctionType *FT = Callee->getFunctionType();
644 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
645 FT->getParamType(1) != FT->getParamType(0) ||
646 !FT->getReturnType()->isIntegerTy())
647 return nullptr;
648
649 StringRef S1, S2;
650 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
651 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
652
653 // strcspn("", s) -> 0
654 if (HasS1 && S1.empty())
655 return Constant::getNullValue(CI->getType());
656
657 // Constant folding.
658 if (HasS1 && HasS2) {
659 size_t Pos = S1.find_first_of(S2);
660 if (Pos == StringRef::npos)
661 Pos = S1.size();
662 return ConstantInt::get(CI->getType(), Pos);
663 }
664
665 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000666 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000667 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000668
669 return nullptr;
670}
671
672Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
673 Function *Callee = CI->getCalledFunction();
674 FunctionType *FT = Callee->getFunctionType();
675 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
676 !FT->getParamType(1)->isPointerTy() ||
677 !FT->getReturnType()->isPointerTy())
678 return nullptr;
679
680 // fold strstr(x, x) -> x.
681 if (CI->getArgOperand(0) == CI->getArgOperand(1))
682 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
683
684 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000685 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000686 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000687 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000688 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000689 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000690 StrLen, B, DL, TLI);
691 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000692 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000693 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
694 ICmpInst *Old = cast<ICmpInst>(*UI++);
695 Value *Cmp =
696 B.CreateICmp(Old->getPredicate(), StrNCmp,
697 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
698 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000699 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000700 return CI;
701 }
Meador Inge17418502012-10-13 16:45:37 +0000702
Chris Bienemanad070d02014-09-17 20:55:46 +0000703 // See if either input string is a constant string.
704 StringRef SearchStr, ToFindStr;
705 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
706 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
707
708 // fold strstr(x, "") -> x.
709 if (HasStr2 && ToFindStr.empty())
710 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
711
712 // If both strings are known, constant fold it.
713 if (HasStr1 && HasStr2) {
714 size_t Offset = SearchStr.find(ToFindStr);
715
716 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000717 return Constant::getNullValue(CI->getType());
718
Chris Bienemanad070d02014-09-17 20:55:46 +0000719 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000720 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
722 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000723 }
Meador Inge17418502012-10-13 16:45:37 +0000724
Chris Bienemanad070d02014-09-17 20:55:46 +0000725 // fold strstr(x, "y") -> strchr(x, 'y').
726 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000727 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000728 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
729 }
730 return nullptr;
731}
Meador Inge40b6fac2012-10-15 03:47:37 +0000732
Benjamin Kramer691363e2015-03-21 15:36:21 +0000733Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
734 Function *Callee = CI->getCalledFunction();
735 FunctionType *FT = Callee->getFunctionType();
736 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
737 !FT->getParamType(1)->isIntegerTy(32) ||
738 !FT->getParamType(2)->isIntegerTy() ||
739 !FT->getReturnType()->isPointerTy())
740 return nullptr;
741
742 Value *SrcStr = CI->getArgOperand(0);
743 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
744 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
745
746 // memchr(x, y, 0) -> null
747 if (LenC && LenC->isNullValue())
748 return Constant::getNullValue(CI->getType());
749
Benjamin Kramer7857d722015-03-21 21:09:33 +0000750 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000751 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000752 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000753 return nullptr;
754
755 // Truncate the string to LenC. If Str is smaller than LenC we will still only
756 // scan the string, as reading past the end of it is undefined and we can just
757 // return null if we don't find the char.
758 Str = Str.substr(0, LenC->getZExtValue());
759
Benjamin Kramer7857d722015-03-21 21:09:33 +0000760 // If the char is variable but the input str and length are not we can turn
761 // this memchr call into a simple bit field test. Of course this only works
762 // when the return value is only checked against null.
763 //
764 // It would be really nice to reuse switch lowering here but we can't change
765 // the CFG at this point.
766 //
767 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
768 // after bounds check.
769 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000770 unsigned char Max =
771 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
772 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000773
774 // Make sure the bit field we're about to create fits in a register on the
775 // target.
776 // FIXME: On a 64 bit architecture this prevents us from using the
777 // interesting range of alpha ascii chars. We could do better by emitting
778 // two bitfields or shifting the range by 64 if no lower chars are used.
779 if (!DL.fitsInLegalInteger(Max + 1))
780 return nullptr;
781
782 // For the bit field use a power-of-2 type with at least 8 bits to avoid
783 // creating unnecessary illegal types.
784 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
785
786 // Now build the bit field.
787 APInt Bitfield(Width, 0);
788 for (char C : Str)
789 Bitfield.setBit((unsigned char)C);
790 Value *BitfieldC = B.getInt(Bitfield);
791
792 // First check that the bit field access is within bounds.
793 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
794 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
795 "memchr.bounds");
796
797 // Create code that checks if the given bit is set in the field.
798 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
799 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
800
801 // Finally merge both checks and cast to pointer type. The inttoptr
802 // implicitly zexts the i1 to intptr type.
803 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
804 }
805
806 // Check if all arguments are constants. If so, we can constant fold.
807 if (!CharC)
808 return nullptr;
809
Benjamin Kramer691363e2015-03-21 15:36:21 +0000810 // Compute the offset.
811 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
812 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
813 return Constant::getNullValue(CI->getType());
814
815 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000816 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000817}
818
Chris Bienemanad070d02014-09-17 20:55:46 +0000819Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
820 Function *Callee = CI->getCalledFunction();
821 FunctionType *FT = Callee->getFunctionType();
822 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
823 !FT->getParamType(1)->isPointerTy() ||
824 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000825 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000826
Chris Bienemanad070d02014-09-17 20:55:46 +0000827 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000828
Chris Bienemanad070d02014-09-17 20:55:46 +0000829 if (LHS == RHS) // memcmp(s,s,x) -> 0
830 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000831
Chris Bienemanad070d02014-09-17 20:55:46 +0000832 // Make sure we have a constant length.
833 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
834 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000835 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000836 uint64_t Len = LenC->getZExtValue();
837
838 if (Len == 0) // memcmp(s1,s2,0) -> 0
839 return Constant::getNullValue(CI->getType());
840
841 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
842 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000843 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000844 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000845 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000846 CI->getType(), "rhsv");
847 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000848 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000849
Chad Rosierdc655322015-08-28 18:30:18 +0000850 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
851 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
852
853 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
854 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
855
856 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
857 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
858
859 Type *LHSPtrTy =
860 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
861 Type *RHSPtrTy =
862 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
863
Sanjay Pateld707db92015-12-31 16:10:49 +0000864 Value *LHSV =
865 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
866 Value *RHSV =
867 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000868
869 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
870 }
871 }
872
Chris Bienemanad070d02014-09-17 20:55:46 +0000873 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
874 StringRef LHSStr, RHSStr;
875 if (getConstantStringInfo(LHS, LHSStr) &&
876 getConstantStringInfo(RHS, RHSStr)) {
877 // Make sure we're not reading out-of-bounds memory.
878 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000879 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000880 // Fold the memcmp and normalize the result. This way we get consistent
881 // results across multiple platforms.
882 uint64_t Ret = 0;
883 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
884 if (Cmp < 0)
885 Ret = -1;
886 else if (Cmp > 0)
887 Ret = 1;
888 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000889 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000890
Chris Bienemanad070d02014-09-17 20:55:46 +0000891 return nullptr;
892}
Meador Inge9a6a1902012-10-31 00:20:56 +0000893
Chris Bienemanad070d02014-09-17 20:55:46 +0000894Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
895 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000896
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000897 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000898 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000899
Chris Bienemanad070d02014-09-17 20:55:46 +0000900 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
901 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000902 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000903 return CI->getArgOperand(0);
904}
Meador Inge05a625a2012-10-31 14:58:26 +0000905
Chris Bienemanad070d02014-09-17 20:55:46 +0000906Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
907 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000908
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000909 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000910 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000911
Chris Bienemanad070d02014-09-17 20:55:46 +0000912 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
913 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000914 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000915 return CI->getArgOperand(0);
916}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000917
Sanjay Patel980b2802016-01-26 16:17:24 +0000918// TODO: Does this belong in BuildLibCalls or should all of those similar
919// functions be moved here?
920static Value *emitCalloc(Value *Num, Value *Size, const AttributeSet &Attrs,
921 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
922 LibFunc::Func Func;
923 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
924 return nullptr;
925
926 Module *M = B.GetInsertBlock()->getModule();
927 const DataLayout &DL = M->getDataLayout();
928 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
929 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
930 PtrType, PtrType, nullptr);
931 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
932
933 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
934 CI->setCallingConv(F->getCallingConv());
935
936 return CI;
937}
938
939/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
940static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
941 const TargetLibraryInfo &TLI) {
942 // This has to be a memset of zeros (bzero).
943 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
944 if (!FillValue || FillValue->getZExtValue() != 0)
945 return nullptr;
946
947 // TODO: We should handle the case where the malloc has more than one use.
948 // This is necessary to optimize common patterns such as when the result of
949 // the malloc is checked against null or when a memset intrinsic is used in
950 // place of a memset library call.
951 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
952 if (!Malloc || !Malloc->hasOneUse())
953 return nullptr;
954
955 // Is the inner call really malloc()?
956 Function *InnerCallee = Malloc->getCalledFunction();
957 LibFunc::Func Func;
958 if (!TLI.getLibFunc(InnerCallee->getName(), Func) || !TLI.has(Func) ||
959 Func != LibFunc::malloc)
960 return nullptr;
961
962 // Matching the name is not good enough. Make sure the parameter and return
963 // type match the standard library signature.
964 FunctionType *FT = InnerCallee->getFunctionType();
965 if (FT->getNumParams() != 1 || !FT->getParamType(0)->isIntegerTy())
966 return nullptr;
967
968 auto *RetType = dyn_cast<PointerType>(FT->getReturnType());
969 if (!RetType || !RetType->getPointerElementType()->isIntegerTy(8))
970 return nullptr;
971
972 // The memset must cover the same number of bytes that are malloc'd.
973 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
974 return nullptr;
975
976 // Replace the malloc with a calloc. We need the data layout to know what the
977 // actual size of a 'size_t' parameter is.
978 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
979 const DataLayout &DL = Malloc->getModule()->getDataLayout();
980 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
981 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
982 Malloc->getArgOperand(0), Malloc->getAttributes(),
983 B, TLI);
984 if (!Calloc)
985 return nullptr;
986
987 Malloc->replaceAllUsesWith(Calloc);
988 Malloc->eraseFromParent();
989
990 return Calloc;
991}
992
Chris Bienemanad070d02014-09-17 20:55:46 +0000993Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
994 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000995
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000997 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000998
Sanjay Patel980b2802016-01-26 16:17:24 +0000999 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
1000 return Calloc;
1001
Chris Bienemanad070d02014-09-17 20:55:46 +00001002 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1003 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1004 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1005 return CI->getArgOperand(0);
1006}
Meador Inged4825782012-11-11 06:49:03 +00001007
Meador Inge193e0352012-11-13 04:16:17 +00001008//===----------------------------------------------------------------------===//
1009// Math Library Optimizations
1010//===----------------------------------------------------------------------===//
1011
Matthias Braund34e4d22014-12-03 21:46:33 +00001012/// Return a variant of Val with float type.
1013/// Currently this works in two cases: If Val is an FPExtension of a float
1014/// value to something bigger, simply return the operand.
1015/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1016/// loss of precision do so.
1017static Value *valueHasFloatPrecision(Value *Val) {
1018 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1019 Value *Op = Cast->getOperand(0);
1020 if (Op->getType()->isFloatTy())
1021 return Op;
1022 }
1023 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1024 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001025 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +00001026 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001027 &losesInfo);
1028 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001029 return ConstantFP::get(Const->getContext(), F);
1030 }
1031 return nullptr;
1032}
1033
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001034/// Any floating-point library function that we're trying to simplify will have
1035/// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
1036/// CheckDoubleTy indicates that 'fptype' must be 'double'.
1037static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
1038 bool CheckDoubleTy) {
1039 FunctionType *FT = F->getFunctionType();
1040 if (FT->getNumParams() != NumParams)
1041 return false;
1042
1043 // The return type must match what we're looking for.
1044 Type *RetTy = FT->getReturnType();
1045 if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
1046 return false;
1047
1048 // Each parameter must match the return type, and therefore, match every other
1049 // parameter too.
1050 for (const Type *ParamTy : FT->params())
1051 if (ParamTy != RetTy)
1052 return false;
1053
1054 return true;
1055}
1056
Sanjay Patel4e971da2016-01-21 18:01:57 +00001057/// Shrink double -> float for unary functions like 'floor'.
1058static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1059 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001060 Function *Callee = CI->getCalledFunction();
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001061 if (!matchesFPLibFunctionSignature(Callee, 1, true))
Chris Bienemanad070d02014-09-17 20:55:46 +00001062 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001063
Chris Bienemanad070d02014-09-17 20:55:46 +00001064 if (CheckRetType) {
1065 // Check if all the uses for function like 'sin' are converted to float.
1066 for (User *U : CI->users()) {
1067 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1068 if (!Cast || !Cast->getType()->isFloatTy())
1069 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001070 }
Meador Inge193e0352012-11-13 04:16:17 +00001071 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001072
1073 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +00001074 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1075 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +00001076 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +00001077
1078 // Propagate fast-math flags from the existing call to the new call.
1079 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001080 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001081
1082 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001083 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001084 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001085 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001086 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1087 V = B.CreateCall(F, V);
1088 } else {
1089 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001090 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +00001091 }
1092
Chris Bienemanad070d02014-09-17 20:55:46 +00001093 return B.CreateFPExt(V, B.getDoubleTy());
1094}
Meador Inge193e0352012-11-13 04:16:17 +00001095
Sanjay Patel4e971da2016-01-21 18:01:57 +00001096/// Shrink double -> float for binary functions like 'fmin/fmax'.
1097static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001098 Function *Callee = CI->getCalledFunction();
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001099 if (!matchesFPLibFunctionSignature(Callee, 2, true))
Craig Topperf40110f2014-04-25 05:29:35 +00001100 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001101
Chris Bienemanad070d02014-09-17 20:55:46 +00001102 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001103 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1104 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1105 if (V1 == nullptr)
1106 return nullptr;
1107 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1108 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001109 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001110
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001111 // Propagate fast-math flags from the existing call to the new call.
1112 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001113 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001114
Chris Bienemanad070d02014-09-17 20:55:46 +00001115 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001116 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001117 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001118 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001119 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001120 return B.CreateFPExt(V, B.getDoubleTy());
1121}
1122
1123Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1124 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001125 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1126 return nullptr;
1127
Chris Bienemanad070d02014-09-17 20:55:46 +00001128 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001129 StringRef Name = Callee->getName();
1130 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001131 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001132
Chris Bienemanad070d02014-09-17 20:55:46 +00001133 // cos(-x) -> cos(x)
1134 Value *Op1 = CI->getArgOperand(0);
1135 if (BinaryOperator::isFNeg(Op1)) {
1136 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1137 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1138 }
1139 return Ret;
1140}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001141
Weiming Zhao82130722015-12-04 22:00:47 +00001142static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1143 // Multiplications calculated using Addition Chains.
1144 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1145
1146 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1147
1148 if (InnerChain[Exp])
1149 return InnerChain[Exp];
1150
1151 static const unsigned AddChain[33][2] = {
1152 {0, 0}, // Unused.
1153 {0, 0}, // Unused (base case = pow1).
1154 {1, 1}, // Unused (pre-computed).
1155 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1156 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1157 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1158 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1159 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1160 };
1161
1162 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1163 getPow(InnerChain, AddChain[Exp][1], B));
1164 return InnerChain[Exp];
1165}
1166
Chris Bienemanad070d02014-09-17 20:55:46 +00001167Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1168 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001169 if (!matchesFPLibFunctionSignature(Callee, 2, false))
1170 return nullptr;
1171
Chris Bienemanad070d02014-09-17 20:55:46 +00001172 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001173 StringRef Name = Callee->getName();
1174 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001175 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001176
Chris Bienemanad070d02014-09-17 20:55:46 +00001177 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1178 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1179 // pow(1.0, x) -> 1.0
1180 if (Op1C->isExactlyValue(1.0))
1181 return Op1C;
1182 // pow(2.0, x) -> exp2(x)
1183 if (Op1C->isExactlyValue(2.0) &&
1184 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1185 LibFunc::exp2l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001186 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
Davide Italianod9f87b42015-11-06 21:05:07 +00001187 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001188 // pow(10.0, x) -> exp10(x)
1189 if (Op1C->isExactlyValue(10.0) &&
1190 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1191 LibFunc::exp10l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001192 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001193 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001194 }
1195
Sanjay Patel6002e782016-01-12 17:30:37 +00001196 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001197 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001198 // We enable these only with fast-math. Besides rounding differences, the
1199 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001200 // Example: x = 1000, y = 0.001.
1201 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001202 auto *OpC = dyn_cast<CallInst>(Op1);
1203 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1204 LibFunc::Func Func;
1205 Function *OpCCallee = OpC->getCalledFunction();
1206 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1207 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001208 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001209 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001210 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001211 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001212 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001213 }
1214 }
1215
Chris Bienemanad070d02014-09-17 20:55:46 +00001216 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1217 if (!Op2C)
1218 return Ret;
1219
1220 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1221 return ConstantFP::get(CI->getType(), 1.0);
1222
1223 if (Op2C->isExactlyValue(0.5) &&
1224 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1225 LibFunc::sqrtl) &&
1226 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1227 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001228
1229 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001230 if (CI->hasUnsafeAlgebra()) {
1231 IRBuilder<>::FastMathFlagGuard Guard(B);
1232 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Pateld3112a52016-01-19 19:46:10 +00001233 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
Davide Italianoc5cedd12015-11-18 23:21:32 +00001234 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001235 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001236
Chris Bienemanad070d02014-09-17 20:55:46 +00001237 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1238 // This is faster than calling pow, and still handles negative zero
1239 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001240 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1241 Value *Inf = ConstantFP::getInfinity(CI->getType());
1242 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Sanjay Pateld3112a52016-01-19 19:46:10 +00001243 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001244 Value *FAbs =
Sanjay Pateld3112a52016-01-19 19:46:10 +00001245 emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001246 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1247 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1248 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001249 }
1250
Chris Bienemanad070d02014-09-17 20:55:46 +00001251 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1252 return Op1;
1253 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1254 return B.CreateFMul(Op1, Op1, "pow2");
1255 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1256 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001257
1258 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001259 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001260 APFloat V = abs(Op2C->getValueAPF());
1261 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1262 // This transformation applies to integer exponents only.
1263 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1264 !V.isInteger())
1265 return nullptr;
1266
1267 // We will memoize intermediate products of the Addition Chain.
1268 Value *InnerChain[33] = {nullptr};
1269 InnerChain[1] = Op1;
1270 InnerChain[2] = B.CreateFMul(Op1, Op1);
1271
1272 // We cannot readily convert a non-double type (like float) to a double.
1273 // So we first convert V to something which could be converted to double.
1274 bool ignored;
1275 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001276
1277 // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
Weiming Zhao82130722015-12-04 22:00:47 +00001278 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1279 // For negative exponents simply compute the reciprocal.
1280 if (Op2C->isNegative())
1281 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1282 return FMul;
1283 }
1284
Chris Bienemanad070d02014-09-17 20:55:46 +00001285 return nullptr;
1286}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001287
Chris Bienemanad070d02014-09-17 20:55:46 +00001288Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1289 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001290 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1291 return nullptr;
1292
Chris Bienemanad070d02014-09-17 20:55:46 +00001293 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001294 StringRef Name = Callee->getName();
1295 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001296 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001297
Chris Bienemanad070d02014-09-17 20:55:46 +00001298 Value *Op = CI->getArgOperand(0);
1299 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1300 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1301 LibFunc::Func LdExp = LibFunc::ldexpl;
1302 if (Op->getType()->isFloatTy())
1303 LdExp = LibFunc::ldexpf;
1304 else if (Op->getType()->isDoubleTy())
1305 LdExp = LibFunc::ldexp;
1306
1307 if (TLI->has(LdExp)) {
1308 Value *LdExpArg = nullptr;
1309 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1310 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1311 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1312 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1313 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1314 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1315 }
1316
1317 if (LdExpArg) {
1318 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1319 if (!Op->getType()->isFloatTy())
1320 One = ConstantExpr::getFPExtend(One, Op->getType());
1321
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001322 Module *M = CI->getModule();
Sanjay Patel042aed902016-01-21 22:41:16 +00001323 Value *NewCallee =
Chris Bienemanad070d02014-09-17 20:55:46 +00001324 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001325 Op->getType(), B.getInt32Ty(), nullptr);
Sanjay Patel042aed902016-01-21 22:41:16 +00001326 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001327 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1328 CI->setCallingConv(F->getCallingConv());
1329
1330 return CI;
1331 }
1332 }
1333 return Ret;
1334}
1335
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001336Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1337 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001338 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1339 return nullptr;
1340
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001341 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001342 StringRef Name = Callee->getName();
1343 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001344 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001345
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001346 Value *Op = CI->getArgOperand(0);
1347 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1348 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1349 if (I->getOpcode() == Instruction::FMul)
1350 if (I->getOperand(0) == I->getOperand(1))
1351 return Op;
1352 }
1353 return Ret;
1354}
1355
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001356Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001357 Function *Callee = CI->getCalledFunction();
1358 if (!matchesFPLibFunctionSignature(Callee, 2, false))
1359 return nullptr;
1360
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001361 // If we can shrink the call to a float function rather than a double
1362 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001363 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001364 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1365 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001366 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001367
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001368 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001369 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001370 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001371 // Unsafe algebra sets all fast-math-flags to true.
1372 FMF.setUnsafeAlgebra();
1373 } else {
1374 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001375 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001376 return nullptr;
1377 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1378 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001379 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001380 // might be impractical."
1381 FMF.setNoSignedZeros();
1382 FMF.setNoNaNs();
1383 }
Sanjay Patela2528152016-01-12 18:03:37 +00001384 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001385
1386 // We have a relaxed floating-point environment. We can ignore NaN-handling
1387 // and transform to a compare and select. We do not have to consider errno or
1388 // exceptions, because fmin/fmax do not have those.
1389 Value *Op0 = CI->getArgOperand(0);
1390 Value *Op1 = CI->getArgOperand(1);
1391 Value *Cmp = Callee->getName().startswith("fmin") ?
1392 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1393 return B.CreateSelect(Cmp, Op0, Op1);
1394}
1395
Davide Italianob8b71332015-11-29 20:58:04 +00001396Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1397 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001398 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1399 return nullptr;
1400
Davide Italianob8b71332015-11-29 20:58:04 +00001401 Value *Ret = nullptr;
1402 StringRef Name = Callee->getName();
1403 if (UnsafeFPShrink && hasFloatVersion(Name))
1404 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001405
Sanjay Patele896ede2016-01-11 23:31:48 +00001406 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001407 return Ret;
1408 Value *Op1 = CI->getArgOperand(0);
1409 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001410
1411 // The earlier call must also be unsafe in order to do these transforms.
1412 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001413 return Ret;
1414
1415 // log(pow(x,y)) -> y*log(x)
1416 // This is only applicable to log, log2, log10.
1417 if (Name != "log" && Name != "log2" && Name != "log10")
1418 return Ret;
1419
1420 IRBuilder<>::FastMathFlagGuard Guard(B);
1421 FastMathFlags FMF;
1422 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001423 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001424
1425 LibFunc::Func Func;
1426 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001427 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1428 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001429 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001430 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001431 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001432
1433 // log(exp2(y)) -> y*log(2)
1434 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1435 TLI->has(Func) && Func == LibFunc::exp2)
1436 return B.CreateFMul(
1437 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001438 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001439 Callee->getName(), B, Callee->getAttributes()),
1440 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001441 return Ret;
1442}
1443
Sanjay Patelc699a612014-10-16 18:48:17 +00001444Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1445 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001446 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1447 return nullptr;
Sanjay Patelbd2dc672016-01-20 17:41:14 +00001448
Sanjay Patelc699a612014-10-16 18:48:17 +00001449 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001450 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1451 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001452 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001453
1454 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001455 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001456
Sanjay Patelc2d64612016-01-06 20:52:21 +00001457 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1458 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1459 return Ret;
1460
1461 // We're looking for a repeated factor in a multiplication tree,
1462 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001463 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001464 Value *Op0 = I->getOperand(0);
1465 Value *Op1 = I->getOperand(1);
1466 Value *RepeatOp = nullptr;
1467 Value *OtherOp = nullptr;
1468 if (Op0 == Op1) {
1469 // Simple match: the operands of the multiply are identical.
1470 RepeatOp = Op0;
1471 } else {
1472 // Look for a more complicated pattern: one of the operands is itself
1473 // a multiply, so search for a common factor in that multiply.
1474 // Note: We don't bother looking any deeper than this first level or for
1475 // variations of this pattern because instcombine's visitFMUL and/or the
1476 // reassociation pass should give us this form.
1477 Value *OtherMul0, *OtherMul1;
1478 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1479 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001480 if (OtherMul0 == OtherMul1 &&
1481 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001482 // Matched: sqrt((x * x) * z)
1483 RepeatOp = OtherMul0;
1484 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001485 }
1486 }
1487 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001488 if (!RepeatOp)
1489 return Ret;
1490
1491 // Fast math flags for any created instructions should match the sqrt
1492 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001493 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001494 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001495
Sanjay Patelc2d64612016-01-06 20:52:21 +00001496 // If we found a repeated factor, hoist it out of the square root and
1497 // replace it with the fabs of that factor.
1498 Module *M = Callee->getParent();
1499 Type *ArgType = I->getType();
1500 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1501 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1502 if (OtherOp) {
1503 // If we found a non-repeated factor, we still need to get its square
1504 // root. We then multiply that by the value that was simplified out
1505 // of the square root calculation.
1506 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1507 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1508 return B.CreateFMul(FabsCall, SqrtCall);
1509 }
1510 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001511}
1512
Sanjay Patelcddcd722016-01-06 19:23:35 +00001513// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001514Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1515 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001516 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1517 return nullptr;
1518
Davide Italiano51507d22015-11-04 23:36:56 +00001519 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001520 StringRef Name = Callee->getName();
1521 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001522 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001523
Davide Italiano51507d22015-11-04 23:36:56 +00001524 Value *Op1 = CI->getArgOperand(0);
1525 auto *OpC = dyn_cast<CallInst>(Op1);
1526 if (!OpC)
1527 return Ret;
1528
Sanjay Patelcddcd722016-01-06 19:23:35 +00001529 // Both calls must allow unsafe optimizations in order to remove them.
1530 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1531 return Ret;
1532
Davide Italiano51507d22015-11-04 23:36:56 +00001533 // tan(atan(x)) -> x
1534 // tanf(atanf(x)) -> x
1535 // tanl(atanl(x)) -> x
1536 LibFunc::Func Func;
1537 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001538 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001539 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1540 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1541 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1542 Ret = OpC->getArgOperand(0);
1543 return Ret;
1544}
1545
Sanjay Patel57747212016-01-21 23:38:43 +00001546static bool isTrigLibCall(CallInst *CI) {
1547 Function *Callee = CI->getCalledFunction();
1548 FunctionType *FT = Callee->getFunctionType();
1549
1550 // We can only hope to do anything useful if we can ignore things like errno
1551 // and floating-point exceptions.
1552 bool AttributesSafe =
1553 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1554
1555 // Other than that we need float(float) or double(double)
1556 return AttributesSafe && FT->getNumParams() == 1 &&
1557 FT->getReturnType() == FT->getParamType(0) &&
1558 (FT->getParamType(0)->isFloatTy() ||
1559 FT->getParamType(0)->isDoubleTy());
1560}
1561
Chris Bienemanad070d02014-09-17 20:55:46 +00001562static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1563 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001564 Value *&SinCos) {
1565 Type *ArgTy = Arg->getType();
1566 Type *ResTy;
1567 StringRef Name;
1568
1569 Triple T(OrigCallee->getParent()->getTargetTriple());
1570 if (UseFloat) {
1571 Name = "__sincospif_stret";
1572
1573 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1574 // x86_64 can't use {float, float} since that would be returned in both
1575 // xmm0 and xmm1, which isn't what a real struct would do.
1576 ResTy = T.getArch() == Triple::x86_64
1577 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1578 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1579 } else {
1580 Name = "__sincospi_stret";
1581 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1582 }
1583
1584 Module *M = OrigCallee->getParent();
1585 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1586 ResTy, ArgTy, nullptr);
1587
1588 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1589 // If the argument is an instruction, it must dominate all uses so put our
1590 // sincos call there.
1591 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1592 } else {
1593 // Otherwise (e.g. for a constant) the beginning of the function is as
1594 // good a place as any.
1595 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1596 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1597 }
1598
1599 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1600
1601 if (SinCos->getType()->isStructTy()) {
1602 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1603 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1604 } else {
1605 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1606 "sinpi");
1607 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1608 "cospi");
1609 }
1610}
Chris Bienemanad070d02014-09-17 20:55:46 +00001611
1612Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001613 // Make sure the prototype is as expected, otherwise the rest of the
1614 // function is probably invalid and likely to abort.
1615 if (!isTrigLibCall(CI))
1616 return nullptr;
1617
1618 Value *Arg = CI->getArgOperand(0);
1619 SmallVector<CallInst *, 1> SinCalls;
1620 SmallVector<CallInst *, 1> CosCalls;
1621 SmallVector<CallInst *, 1> SinCosCalls;
1622
1623 bool IsFloat = Arg->getType()->isFloatTy();
1624
1625 // Look for all compatible sinpi, cospi and sincospi calls with the same
1626 // argument. If there are enough (in some sense) we can make the
1627 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001628 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001629 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001630 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001631
1632 // It's only worthwhile if both sinpi and cospi are actually used.
1633 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1634 return nullptr;
1635
1636 Value *Sin, *Cos, *SinCos;
1637 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1638
1639 replaceTrigInsts(SinCalls, Sin);
1640 replaceTrigInsts(CosCalls, Cos);
1641 replaceTrigInsts(SinCosCalls, SinCos);
1642
1643 return nullptr;
1644}
1645
David Majnemerabae6b52016-03-19 04:53:02 +00001646void LibCallSimplifier::classifyArgUse(
1647 Value *Val, Function *F, bool IsFloat,
1648 SmallVectorImpl<CallInst *> &SinCalls,
1649 SmallVectorImpl<CallInst *> &CosCalls,
1650 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001651 CallInst *CI = dyn_cast<CallInst>(Val);
1652
1653 if (!CI)
1654 return;
1655
David Majnemerabae6b52016-03-19 04:53:02 +00001656 // Don't consider calls in other functions.
1657 if (CI->getFunction() != F)
1658 return;
1659
Chris Bienemanad070d02014-09-17 20:55:46 +00001660 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001662 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1663 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 return;
1665
1666 if (IsFloat) {
1667 if (Func == LibFunc::sinpif)
1668 SinCalls.push_back(CI);
1669 else if (Func == LibFunc::cospif)
1670 CosCalls.push_back(CI);
1671 else if (Func == LibFunc::sincospif_stret)
1672 SinCosCalls.push_back(CI);
1673 } else {
1674 if (Func == LibFunc::sinpi)
1675 SinCalls.push_back(CI);
1676 else if (Func == LibFunc::cospi)
1677 CosCalls.push_back(CI);
1678 else if (Func == LibFunc::sincospi_stret)
1679 SinCosCalls.push_back(CI);
1680 }
1681}
1682
1683void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1684 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001685 for (CallInst *C : Calls)
1686 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001687}
1688
Meador Inge7415f842012-11-25 20:45:27 +00001689//===----------------------------------------------------------------------===//
1690// Integer Library Call Optimizations
1691//===----------------------------------------------------------------------===//
1692
Davide Italiano396f3ee2015-10-31 23:17:45 +00001693static bool checkIntUnaryReturnAndParam(Function *Callee) {
1694 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001695 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1696 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001697}
1698
Chris Bienemanad070d02014-09-17 20:55:46 +00001699Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1700 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001701 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001703 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001704
Chris Bienemanad070d02014-09-17 20:55:46 +00001705 // Constant fold.
1706 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1707 if (CI->isZero()) // ffs(0) -> 0.
1708 return B.getInt32(0);
1709 // ffs(c) -> cttz(c)+1
1710 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001711 }
Meador Inge7415f842012-11-25 20:45:27 +00001712
Chris Bienemanad070d02014-09-17 20:55:46 +00001713 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1714 Type *ArgType = Op->getType();
1715 Value *F =
1716 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001717 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001718 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1719 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001720
Chris Bienemanad070d02014-09-17 20:55:46 +00001721 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1722 return B.CreateSelect(Cond, V, B.getInt32(0));
1723}
Meador Ingea0b6d872012-11-26 00:24:07 +00001724
Chris Bienemanad070d02014-09-17 20:55:46 +00001725Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1726 Function *Callee = CI->getCalledFunction();
1727 FunctionType *FT = Callee->getFunctionType();
1728 // We require integer(integer) where the types agree.
1729 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1730 FT->getParamType(0) != FT->getReturnType())
1731 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001732
Chris Bienemanad070d02014-09-17 20:55:46 +00001733 // abs(x) -> x >s -1 ? x : -x
1734 Value *Op = CI->getArgOperand(0);
1735 Value *Pos =
1736 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1737 Value *Neg = B.CreateNeg(Op, "neg");
1738 return B.CreateSelect(Pos, Op, Neg);
1739}
Meador Inge9a59ab62012-11-26 02:31:59 +00001740
Chris Bienemanad070d02014-09-17 20:55:46 +00001741Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001742 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001744
Chris Bienemanad070d02014-09-17 20:55:46 +00001745 // isdigit(c) -> (c-'0') <u 10
1746 Value *Op = CI->getArgOperand(0);
1747 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1748 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1749 return B.CreateZExt(Op, CI->getType());
1750}
Meador Ingea62a39e2012-11-26 03:10:07 +00001751
Chris Bienemanad070d02014-09-17 20:55:46 +00001752Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001753 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001754 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001755
Chris Bienemanad070d02014-09-17 20:55:46 +00001756 // isascii(c) -> c <u 128
1757 Value *Op = CI->getArgOperand(0);
1758 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1759 return B.CreateZExt(Op, CI->getType());
1760}
1761
1762Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001763 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001764 return nullptr;
1765
1766 // toascii(c) -> c & 0x7f
1767 return B.CreateAnd(CI->getArgOperand(0),
1768 ConstantInt::get(CI->getType(), 0x7F));
1769}
Meador Inge604937d2012-11-26 03:38:52 +00001770
Meador Inge08ca1152012-11-26 20:37:20 +00001771//===----------------------------------------------------------------------===//
1772// Formatting and IO Library Call Optimizations
1773//===----------------------------------------------------------------------===//
1774
Chris Bienemanad070d02014-09-17 20:55:46 +00001775static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001776
Chris Bienemanad070d02014-09-17 20:55:46 +00001777Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1778 int StreamArg) {
1779 // Error reporting calls should be cold, mark them as such.
1780 // This applies even to non-builtin calls: it is only a hint and applies to
1781 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001782
Chris Bienemanad070d02014-09-17 20:55:46 +00001783 // This heuristic was suggested in:
1784 // Improving Static Branch Prediction in a Compiler
1785 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1786 // Proceedings of PACT'98, Oct. 1998, IEEE
1787 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001788
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 if (!CI->hasFnAttr(Attribute::Cold) &&
1790 isReportingError(Callee, CI, StreamArg)) {
1791 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1792 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001793
Chris Bienemanad070d02014-09-17 20:55:46 +00001794 return nullptr;
1795}
1796
1797static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001798 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001799 return false;
1800
1801 if (StreamArg < 0)
1802 return true;
1803
1804 // These functions might be considered cold, but only if their stream
1805 // argument is stderr.
1806
1807 if (StreamArg >= (int)CI->getNumArgOperands())
1808 return false;
1809 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1810 if (!LI)
1811 return false;
1812 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1813 if (!GV || !GV->isDeclaration())
1814 return false;
1815 return GV->getName() == "stderr";
1816}
1817
1818Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1819 // Check for a fixed format string.
1820 StringRef FormatStr;
1821 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001822 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001823
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 // Empty format string -> noop.
1825 if (FormatStr.empty()) // Tolerate printf's declared void.
1826 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001827
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 // Do not do any of the following transformations if the printf return value
1829 // is used, in general the printf return value is not compatible with either
1830 // putchar() or puts().
1831 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001832 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001833
1834 // printf("x") -> putchar('x'), even for '%'.
1835 if (FormatStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00001836 Value *Res = emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001837 if (CI->use_empty() || !Res)
1838 return Res;
1839 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001840 }
1841
Chris Bienemanad070d02014-09-17 20:55:46 +00001842 // printf("foo\n") --> puts("foo")
1843 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1844 FormatStr.find('%') == StringRef::npos) { // No format characters.
1845 // Create a string literal with no \n on it. We expect the constant merge
1846 // pass to be run after this pass, to merge duplicate strings.
1847 FormatStr = FormatStr.drop_back();
1848 Value *GV = B.CreateGlobalString(FormatStr, "str");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001849 Value *NewCI = emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 return (CI->use_empty() || !NewCI)
1851 ? NewCI
1852 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1853 }
Meador Inge08ca1152012-11-26 20:37:20 +00001854
Chris Bienemanad070d02014-09-17 20:55:46 +00001855 // Optimize specific format strings.
1856 // printf("%c", chr) --> putchar(chr)
1857 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1858 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00001859 Value *Res = emitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001860
Chris Bienemanad070d02014-09-17 20:55:46 +00001861 if (CI->use_empty() || !Res)
1862 return Res;
1863 return B.CreateIntCast(Res, CI->getType(), true);
1864 }
1865
1866 // printf("%s\n", str) --> puts(str)
1867 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1868 CI->getArgOperand(1)->getType()->isPointerTy()) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00001869 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001870 }
1871 return nullptr;
1872}
1873
1874Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1875
1876 Function *Callee = CI->getCalledFunction();
1877 // Require one fixed pointer argument and an integer/void result.
1878 FunctionType *FT = Callee->getFunctionType();
1879 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1880 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1881 return nullptr;
1882
1883 if (Value *V = optimizePrintFString(CI, B)) {
1884 return V;
1885 }
1886
1887 // printf(format, ...) -> iprintf(format, ...) if no floating point
1888 // arguments.
1889 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1890 Module *M = B.GetInsertBlock()->getParent()->getParent();
1891 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001892 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001893 CallInst *New = cast<CallInst>(CI->clone());
1894 New->setCalledFunction(IPrintFFn);
1895 B.Insert(New);
1896 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001897 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001898 return nullptr;
1899}
Meador Inge08ca1152012-11-26 20:37:20 +00001900
Chris Bienemanad070d02014-09-17 20:55:46 +00001901Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1902 // Check for a fixed format string.
1903 StringRef FormatStr;
1904 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001905 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001906
Chris Bienemanad070d02014-09-17 20:55:46 +00001907 // If we just have a format string (nothing else crazy) transform it.
1908 if (CI->getNumArgOperands() == 2) {
1909 // Make sure there's no % in the constant array. We could try to handle
1910 // %% -> % in the future if we cared.
1911 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1912 if (FormatStr[i] == '%')
1913 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001914
Chris Bienemanad070d02014-09-17 20:55:46 +00001915 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001916 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1917 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1918 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001919 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001920 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001921 }
Meador Ingef8e72502012-11-29 15:45:43 +00001922
Chris Bienemanad070d02014-09-17 20:55:46 +00001923 // The remaining optimizations require the format string to be "%s" or "%c"
1924 // and have an extra operand.
1925 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1926 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001927 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001928
Chris Bienemanad070d02014-09-17 20:55:46 +00001929 // Decode the second character of the format string.
1930 if (FormatStr[1] == 'c') {
1931 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1932 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1933 return nullptr;
1934 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001935 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001936 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001937 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001938 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001939
Chris Bienemanad070d02014-09-17 20:55:46 +00001940 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001941 }
1942
Chris Bienemanad070d02014-09-17 20:55:46 +00001943 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001944 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1945 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1946 return nullptr;
1947
Sanjay Pateld3112a52016-01-19 19:46:10 +00001948 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001949 if (!Len)
1950 return nullptr;
1951 Value *IncLen =
1952 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper67cf9a72015-11-19 05:56:52 +00001953 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001954
1955 // The sprintf result is the unincremented number of bytes in the string.
1956 return B.CreateIntCast(Len, CI->getType(), false);
1957 }
1958 return nullptr;
1959}
1960
1961Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1962 Function *Callee = CI->getCalledFunction();
1963 // Require two fixed pointer arguments and an integer result.
1964 FunctionType *FT = Callee->getFunctionType();
1965 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1966 !FT->getParamType(1)->isPointerTy() ||
1967 !FT->getReturnType()->isIntegerTy())
1968 return nullptr;
1969
1970 if (Value *V = optimizeSPrintFString(CI, B)) {
1971 return V;
1972 }
1973
1974 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1975 // point arguments.
1976 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1977 Module *M = B.GetInsertBlock()->getParent()->getParent();
1978 Constant *SIPrintFFn =
1979 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1980 CallInst *New = cast<CallInst>(CI->clone());
1981 New->setCalledFunction(SIPrintFFn);
1982 B.Insert(New);
1983 return New;
1984 }
1985 return nullptr;
1986}
1987
1988Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1989 optimizeErrorReporting(CI, B, 0);
1990
1991 // All the optimizations depend on the format string.
1992 StringRef FormatStr;
1993 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1994 return nullptr;
1995
1996 // Do not do any of the following transformations if the fprintf return
1997 // value is used, in general the fprintf return value is not compatible
1998 // with fwrite(), fputc() or fputs().
1999 if (!CI->use_empty())
2000 return nullptr;
2001
2002 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2003 if (CI->getNumArgOperands() == 2) {
2004 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
2005 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
2006 return nullptr; // We found a format specifier.
2007
Sanjay Pateld3112a52016-01-19 19:46:10 +00002008 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002009 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002010 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002011 CI->getArgOperand(0), B, DL, TLI);
2012 }
2013
2014 // The remaining optimizations require the format string to be "%s" or "%c"
2015 // and have an extra operand.
2016 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2017 CI->getNumArgOperands() < 3)
2018 return nullptr;
2019
2020 // Decode the second character of the format string.
2021 if (FormatStr[1] == 'c') {
2022 // fprintf(F, "%c", chr) --> fputc(chr, F)
2023 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2024 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002025 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002026 }
2027
2028 if (FormatStr[1] == 's') {
2029 // fprintf(F, "%s", str) --> fputs(str, F)
2030 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2031 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002032 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002033 }
2034 return nullptr;
2035}
2036
2037Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2038 Function *Callee = CI->getCalledFunction();
2039 // Require two fixed paramters as pointers and integer result.
2040 FunctionType *FT = Callee->getFunctionType();
2041 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2042 !FT->getParamType(1)->isPointerTy() ||
2043 !FT->getReturnType()->isIntegerTy())
2044 return nullptr;
2045
2046 if (Value *V = optimizeFPrintFString(CI, B)) {
2047 return V;
2048 }
2049
2050 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2051 // floating point arguments.
2052 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2053 Module *M = B.GetInsertBlock()->getParent()->getParent();
2054 Constant *FIPrintFFn =
2055 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2056 CallInst *New = cast<CallInst>(CI->clone());
2057 New->setCalledFunction(FIPrintFFn);
2058 B.Insert(New);
2059 return New;
2060 }
2061 return nullptr;
2062}
2063
2064Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2065 optimizeErrorReporting(CI, B, 3);
2066
2067 Function *Callee = CI->getCalledFunction();
2068 // Require a pointer, an integer, an integer, a pointer, returning integer.
2069 FunctionType *FT = Callee->getFunctionType();
2070 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2071 !FT->getParamType(1)->isIntegerTy() ||
2072 !FT->getParamType(2)->isIntegerTy() ||
2073 !FT->getParamType(3)->isPointerTy() ||
2074 !FT->getReturnType()->isIntegerTy())
2075 return nullptr;
2076
2077 // Get the element size and count.
2078 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2079 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2080 if (!SizeC || !CountC)
2081 return nullptr;
2082 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2083
2084 // If this is writing zero records, remove the call (it's a noop).
2085 if (Bytes == 0)
2086 return ConstantInt::get(CI->getType(), 0);
2087
2088 // If this is writing one byte, turn it into fputc.
2089 // This optimisation is only valid, if the return value is unused.
2090 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00002091 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2092 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002093 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2094 }
2095
2096 return nullptr;
2097}
2098
2099Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2100 optimizeErrorReporting(CI, B, 1);
2101
2102 Function *Callee = CI->getCalledFunction();
2103
Chris Bienemanad070d02014-09-17 20:55:46 +00002104 // Require two pointers. Also, we can't optimize if return value is used.
2105 FunctionType *FT = Callee->getFunctionType();
2106 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2107 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2108 return nullptr;
2109
2110 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2111 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2112 if (!Len)
2113 return nullptr;
2114
2115 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002116 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002117 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002118 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002119 CI->getArgOperand(1), B, DL, TLI);
2120}
2121
2122Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2123 Function *Callee = CI->getCalledFunction();
2124 // Require one fixed pointer argument and an integer/void result.
2125 FunctionType *FT = Callee->getFunctionType();
2126 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2127 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2128 return nullptr;
2129
2130 // Check for a constant string.
2131 StringRef Str;
2132 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2133 return nullptr;
2134
2135 if (Str.empty() && CI->use_empty()) {
2136 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002137 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002138 if (CI->use_empty() || !Res)
2139 return Res;
2140 return B.CreateIntCast(Res, CI->getType(), true);
2141 }
2142
2143 return nullptr;
2144}
2145
2146bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002147 LibFunc::Func Func;
2148 SmallString<20> FloatFuncName = FuncName;
2149 FloatFuncName += 'f';
2150 if (TLI->getLibFunc(FloatFuncName, Func))
2151 return TLI->has(Func);
2152 return false;
2153}
Meador Inge7fb2f732012-10-13 16:45:32 +00002154
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002155Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2156 IRBuilder<> &Builder) {
2157 LibFunc::Func Func;
2158 Function *Callee = CI->getCalledFunction();
2159 StringRef FuncName = Callee->getName();
2160
2161 // Check for string/memory library functions.
2162 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2163 // Make sure we never change the calling convention.
2164 assert((ignoreCallingConv(Func) ||
2165 CI->getCallingConv() == llvm::CallingConv::C) &&
2166 "Optimizing string/memory libcall would change the calling convention");
2167 switch (Func) {
2168 case LibFunc::strcat:
2169 return optimizeStrCat(CI, Builder);
2170 case LibFunc::strncat:
2171 return optimizeStrNCat(CI, Builder);
2172 case LibFunc::strchr:
2173 return optimizeStrChr(CI, Builder);
2174 case LibFunc::strrchr:
2175 return optimizeStrRChr(CI, Builder);
2176 case LibFunc::strcmp:
2177 return optimizeStrCmp(CI, Builder);
2178 case LibFunc::strncmp:
2179 return optimizeStrNCmp(CI, Builder);
2180 case LibFunc::strcpy:
2181 return optimizeStrCpy(CI, Builder);
2182 case LibFunc::stpcpy:
2183 return optimizeStpCpy(CI, Builder);
2184 case LibFunc::strncpy:
2185 return optimizeStrNCpy(CI, Builder);
2186 case LibFunc::strlen:
2187 return optimizeStrLen(CI, Builder);
2188 case LibFunc::strpbrk:
2189 return optimizeStrPBrk(CI, Builder);
2190 case LibFunc::strtol:
2191 case LibFunc::strtod:
2192 case LibFunc::strtof:
2193 case LibFunc::strtoul:
2194 case LibFunc::strtoll:
2195 case LibFunc::strtold:
2196 case LibFunc::strtoull:
2197 return optimizeStrTo(CI, Builder);
2198 case LibFunc::strspn:
2199 return optimizeStrSpn(CI, Builder);
2200 case LibFunc::strcspn:
2201 return optimizeStrCSpn(CI, Builder);
2202 case LibFunc::strstr:
2203 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002204 case LibFunc::memchr:
2205 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002206 case LibFunc::memcmp:
2207 return optimizeMemCmp(CI, Builder);
2208 case LibFunc::memcpy:
2209 return optimizeMemCpy(CI, Builder);
2210 case LibFunc::memmove:
2211 return optimizeMemMove(CI, Builder);
2212 case LibFunc::memset:
2213 return optimizeMemSet(CI, Builder);
2214 default:
2215 break;
2216 }
2217 }
2218 return nullptr;
2219}
2220
Chris Bienemanad070d02014-09-17 20:55:46 +00002221Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2222 if (CI->isNoBuiltin())
2223 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002224
Meador Inge20255ef2013-03-12 00:08:29 +00002225 LibFunc::Func Func;
2226 Function *Callee = CI->getCalledFunction();
2227 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002228
2229 SmallVector<OperandBundleDef, 2> OpBundles;
2230 CI->getOperandBundlesAsDefs(OpBundles);
2231 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Chris Bienemanad070d02014-09-17 20:55:46 +00002232 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002233
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002234 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002235 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2236 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002237 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002238 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002239
Sanjay Patel848309d2014-10-23 21:52:45 +00002240 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002241 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002242 if (!isCallingConvC)
2243 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002244 switch (II->getIntrinsicID()) {
2245 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002246 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002247 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002248 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002249 case Intrinsic::fabs:
2250 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002251 case Intrinsic::log:
2252 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002253 case Intrinsic::sqrt:
2254 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002255 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002256 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002257 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002258 }
2259 }
2260
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002261 // Also try to simplify calls to fortified library functions.
2262 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2263 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002264 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002265 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2266 // Use an IR Builder from SimplifiedCI if available instead of CI
2267 // to guarantee we reach all uses we might replace later on.
2268 IRBuilder<> TmpBuilder(SimplifiedCI);
2269 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002270 // If we were able to further simplify, remove the now redundant call.
2271 SimplifiedCI->replaceAllUsesWith(V);
2272 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002273 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002274 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002275 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002276 return SimplifiedFortifiedCI;
2277 }
2278
Meador Inge20255ef2013-03-12 00:08:29 +00002279 // Then check for known library functions.
2280 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002281 // We never change the calling convention.
2282 if (!ignoreCallingConv(Func) && !isCallingConvC)
2283 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002284 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2285 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002286 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002287 case LibFunc::cosf:
2288 case LibFunc::cos:
2289 case LibFunc::cosl:
2290 return optimizeCos(CI, Builder);
2291 case LibFunc::sinpif:
2292 case LibFunc::sinpi:
2293 case LibFunc::cospif:
2294 case LibFunc::cospi:
2295 return optimizeSinCosPi(CI, Builder);
2296 case LibFunc::powf:
2297 case LibFunc::pow:
2298 case LibFunc::powl:
2299 return optimizePow(CI, Builder);
2300 case LibFunc::exp2l:
2301 case LibFunc::exp2:
2302 case LibFunc::exp2f:
2303 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002304 case LibFunc::fabsf:
2305 case LibFunc::fabs:
2306 case LibFunc::fabsl:
2307 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002308 case LibFunc::sqrtf:
2309 case LibFunc::sqrt:
2310 case LibFunc::sqrtl:
2311 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002312 case LibFunc::ffs:
2313 case LibFunc::ffsl:
2314 case LibFunc::ffsll:
2315 return optimizeFFS(CI, Builder);
2316 case LibFunc::abs:
2317 case LibFunc::labs:
2318 case LibFunc::llabs:
2319 return optimizeAbs(CI, Builder);
2320 case LibFunc::isdigit:
2321 return optimizeIsDigit(CI, Builder);
2322 case LibFunc::isascii:
2323 return optimizeIsAscii(CI, Builder);
2324 case LibFunc::toascii:
2325 return optimizeToAscii(CI, Builder);
2326 case LibFunc::printf:
2327 return optimizePrintF(CI, Builder);
2328 case LibFunc::sprintf:
2329 return optimizeSPrintF(CI, Builder);
2330 case LibFunc::fprintf:
2331 return optimizeFPrintF(CI, Builder);
2332 case LibFunc::fwrite:
2333 return optimizeFWrite(CI, Builder);
2334 case LibFunc::fputs:
2335 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002336 case LibFunc::log:
2337 case LibFunc::log10:
2338 case LibFunc::log1p:
2339 case LibFunc::log2:
2340 case LibFunc::logb:
2341 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002342 case LibFunc::puts:
2343 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002344 case LibFunc::tan:
2345 case LibFunc::tanf:
2346 case LibFunc::tanl:
2347 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002348 case LibFunc::perror:
2349 return optimizeErrorReporting(CI, Builder);
2350 case LibFunc::vfprintf:
2351 case LibFunc::fiprintf:
2352 return optimizeErrorReporting(CI, Builder, 0);
2353 case LibFunc::fputc:
2354 return optimizeErrorReporting(CI, Builder, 1);
2355 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002356 case LibFunc::floor:
2357 case LibFunc::rint:
2358 case LibFunc::round:
2359 case LibFunc::nearbyint:
2360 case LibFunc::trunc:
2361 if (hasFloatVersion(FuncName))
2362 return optimizeUnaryDoubleFP(CI, Builder, false);
2363 return nullptr;
2364 case LibFunc::acos:
2365 case LibFunc::acosh:
2366 case LibFunc::asin:
2367 case LibFunc::asinh:
2368 case LibFunc::atan:
2369 case LibFunc::atanh:
2370 case LibFunc::cbrt:
2371 case LibFunc::cosh:
2372 case LibFunc::exp:
2373 case LibFunc::exp10:
2374 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002375 case LibFunc::sin:
2376 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002377 case LibFunc::tanh:
2378 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2379 return optimizeUnaryDoubleFP(CI, Builder, true);
2380 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002381 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002382 if (hasFloatVersion(FuncName))
2383 return optimizeBinaryDoubleFP(CI, Builder);
2384 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002385 case LibFunc::fminf:
2386 case LibFunc::fmin:
2387 case LibFunc::fminl:
2388 case LibFunc::fmaxf:
2389 case LibFunc::fmax:
2390 case LibFunc::fmaxl:
2391 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002392 default:
2393 return nullptr;
2394 }
Meador Inge20255ef2013-03-12 00:08:29 +00002395 }
Craig Topperf40110f2014-04-25 05:29:35 +00002396 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002397}
2398
Chandler Carruth92803822015-01-21 02:11:59 +00002399LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002400 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002401 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002402 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002403 Replacer(Replacer) {}
2404
2405void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2406 // Indirect through the replacer used in this instance.
2407 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002408}
2409
Meador Ingedfb08a22013-06-20 19:48:07 +00002410// TODO:
2411// Additional cases that we need to add to this file:
2412//
2413// cbrt:
2414// * cbrt(expN(X)) -> expN(x/3)
2415// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002416// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002417//
2418// exp, expf, expl:
2419// * exp(log(x)) -> x
2420//
2421// log, logf, logl:
2422// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002423// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002424// * log(exp10(y)) -> y*log(10)
2425// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002426//
2427// lround, lroundf, lroundl:
2428// * lround(cnst) -> cnst'
2429//
2430// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002431// * pow(sqrt(x),y) -> pow(x,y*0.5)
2432// * pow(pow(x,y),z)-> pow(x,y*z)
2433//
2434// round, roundf, roundl:
2435// * round(cnst) -> cnst'
2436//
2437// signbit:
2438// * signbit(cnst) -> cnst'
2439// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2440//
2441// sqrt, sqrtf, sqrtl:
2442// * sqrt(expN(x)) -> expN(x*0.5)
2443// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2444// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2445//
Meador Ingedfb08a22013-06-20 19:48:07 +00002446// trunc, truncf, truncl:
2447// * trunc(cnst) -> cnst'
2448//
2449//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002450
2451//===----------------------------------------------------------------------===//
2452// Fortified Library Call Optimizations
2453//===----------------------------------------------------------------------===//
2454
2455bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2456 unsigned ObjSizeOp,
2457 unsigned SizeOp,
2458 bool isString) {
2459 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2460 return true;
2461 if (ConstantInt *ObjSizeCI =
2462 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2463 if (ObjSizeCI->isAllOnesValue())
2464 return true;
2465 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2466 if (OnlyLowerUnknownSize)
2467 return false;
2468 if (isString) {
2469 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2470 // If the length is 0 we don't know how long it is and so we can't
2471 // remove the check.
2472 if (Len == 0)
2473 return false;
2474 return ObjSizeCI->getZExtValue() >= Len;
2475 }
2476 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2477 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2478 }
2479 return false;
2480}
2481
Sanjay Pateld707db92015-12-31 16:10:49 +00002482Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2483 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002484 Function *Callee = CI->getCalledFunction();
2485
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002486 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002487 return nullptr;
2488
2489 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2490 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002491 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002492 return CI->getArgOperand(0);
2493 }
2494 return nullptr;
2495}
2496
Sanjay Pateld707db92015-12-31 16:10:49 +00002497Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2498 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002499 Function *Callee = CI->getCalledFunction();
2500
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002501 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002502 return nullptr;
2503
2504 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2505 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002506 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002507 return CI->getArgOperand(0);
2508 }
2509 return nullptr;
2510}
2511
Sanjay Pateld707db92015-12-31 16:10:49 +00002512Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2513 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002514 Function *Callee = CI->getCalledFunction();
2515
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002516 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002517 return nullptr;
2518
Sanjay Patel980b2802016-01-26 16:17:24 +00002519 // TODO: Try foldMallocMemset() here.
2520
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002521 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2522 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2523 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2524 return CI->getArgOperand(0);
2525 }
2526 return nullptr;
2527}
2528
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002529Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2530 IRBuilder<> &B,
2531 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002532 Function *Callee = CI->getCalledFunction();
2533 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002534 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002535
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002536 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002537 return nullptr;
2538
2539 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2540 *ObjSize = CI->getArgOperand(2);
2541
2542 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002543 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002544 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002545 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002546 }
2547
2548 // If a) we don't have any length information, or b) we know this will
2549 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2550 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2551 // TODO: It might be nice to get a maximum length out of the possible
2552 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002553 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002554 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002555
David Blaikie65fab6d2015-04-03 21:32:06 +00002556 if (OnlyLowerUnknownSize)
2557 return nullptr;
2558
2559 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2560 uint64_t Len = GetStringLength(Src);
2561 if (Len == 0)
2562 return nullptr;
2563
2564 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2565 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002566 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002567 // If the function was an __stpcpy_chk, and we were able to fold it into
2568 // a __memcpy_chk, we still need to return the correct end pointer.
2569 if (Ret && Func == LibFunc::stpcpy_chk)
2570 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2571 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002572}
2573
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002574Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2575 IRBuilder<> &B,
2576 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002577 Function *Callee = CI->getCalledFunction();
2578 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002579
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002580 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002581 return nullptr;
2582 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002583 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002584 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002585 return Ret;
2586 }
2587 return nullptr;
2588}
2589
2590Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002591 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2592 // Some clang users checked for _chk libcall availability using:
2593 // __has_builtin(__builtin___memcpy_chk)
2594 // When compiling with -fno-builtin, this is always true.
2595 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2596 // end up with fortified libcalls, which isn't acceptable in a freestanding
2597 // environment which only provides their non-fortified counterparts.
2598 //
2599 // Until we change clang and/or teach external users to check for availability
2600 // differently, disregard the "nobuiltin" attribute and TLI::has.
2601 //
2602 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002603
2604 LibFunc::Func Func;
2605 Function *Callee = CI->getCalledFunction();
2606 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002607
2608 SmallVector<OperandBundleDef, 2> OpBundles;
2609 CI->getOperandBundlesAsDefs(OpBundles);
2610 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002611 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2612
2613 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002614 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002615 return nullptr;
2616
2617 // We never change the calling convention.
2618 if (!ignoreCallingConv(Func) && !isCallingConvC)
2619 return nullptr;
2620
2621 switch (Func) {
2622 case LibFunc::memcpy_chk:
2623 return optimizeMemCpyChk(CI, Builder);
2624 case LibFunc::memmove_chk:
2625 return optimizeMemMoveChk(CI, Builder);
2626 case LibFunc::memset_chk:
2627 return optimizeMemSetChk(CI, Builder);
2628 case LibFunc::stpcpy_chk:
2629 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002630 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002631 case LibFunc::stpncpy_chk:
2632 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002633 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002634 default:
2635 break;
2636 }
2637 return nullptr;
2638}
2639
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002640FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2641 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2642 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}