blob: 4f795093d9d694ca2275a67d33e5166dad5a1428 [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
Chris Bienemanad070d02014-09-17 20:55:46 +0000918Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
919 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000920
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000921 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000922 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000923
Chris Bienemanad070d02014-09-17 20:55:46 +0000924 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
925 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
926 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
927 return CI->getArgOperand(0);
928}
Meador Inged4825782012-11-11 06:49:03 +0000929
Meador Inge193e0352012-11-13 04:16:17 +0000930//===----------------------------------------------------------------------===//
931// Math Library Optimizations
932//===----------------------------------------------------------------------===//
933
Matthias Braund34e4d22014-12-03 21:46:33 +0000934/// Return a variant of Val with float type.
935/// Currently this works in two cases: If Val is an FPExtension of a float
936/// value to something bigger, simply return the operand.
937/// If Val is a ConstantFP but can be converted to a float ConstantFP without
938/// loss of precision do so.
939static Value *valueHasFloatPrecision(Value *Val) {
940 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
941 Value *Op = Cast->getOperand(0);
942 if (Op->getType()->isFloatTy())
943 return Op;
944 }
945 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
946 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000947 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000948 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000949 &losesInfo);
950 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000951 return ConstantFP::get(Const->getContext(), F);
952 }
953 return nullptr;
954}
955
Sanjay Patel4e971da2016-01-21 18:01:57 +0000956/// Shrink double -> float for unary functions like 'floor'.
957static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
958 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000959 Function *Callee = CI->getCalledFunction();
960 FunctionType *FT = Callee->getFunctionType();
961 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
962 !FT->getParamType(0)->isDoubleTy())
963 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000964
Chris Bienemanad070d02014-09-17 20:55:46 +0000965 if (CheckRetType) {
966 // Check if all the uses for function like 'sin' are converted to float.
967 for (User *U : CI->users()) {
968 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
969 if (!Cast || !Cast->getType()->isFloatTy())
970 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000971 }
Meador Inge193e0352012-11-13 04:16:17 +0000972 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000973
974 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000975 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
976 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000977 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000978
979 // Propagate fast-math flags from the existing call to the new call.
980 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000981 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000982
983 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000984 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000985 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000986 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000987 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
988 V = B.CreateCall(F, V);
989 } else {
990 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000991 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000992 }
993
Chris Bienemanad070d02014-09-17 20:55:46 +0000994 return B.CreateFPExt(V, B.getDoubleTy());
995}
Meador Inge193e0352012-11-13 04:16:17 +0000996
Sanjay Patel4e971da2016-01-21 18:01:57 +0000997/// Shrink double -> float for binary functions like 'fmin/fmax'.
998static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000999 Function *Callee = CI->getCalledFunction();
1000 FunctionType *FT = Callee->getFunctionType();
1001 // Just make sure this has 2 arguments of the same FP type, which match the
1002 // result type.
1003 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1004 FT->getParamType(0) != FT->getParamType(1) ||
1005 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001006 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001007
Chris Bienemanad070d02014-09-17 20:55:46 +00001008 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001009 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1010 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1011 if (V1 == nullptr)
1012 return nullptr;
1013 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1014 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001015 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001016
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001017 // Propagate fast-math flags from the existing call to the new call.
1018 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001019 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001020
Chris Bienemanad070d02014-09-17 20:55:46 +00001021 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001022 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001023 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001024 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001025 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001026 return B.CreateFPExt(V, B.getDoubleTy());
1027}
1028
1029Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1030 Function *Callee = CI->getCalledFunction();
1031 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001032 StringRef Name = Callee->getName();
1033 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001034 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001035
Chris Bienemanad070d02014-09-17 20:55:46 +00001036 FunctionType *FT = Callee->getFunctionType();
1037 // Just make sure this has 1 argument of FP type, which matches the
1038 // result type.
1039 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1040 !FT->getParamType(0)->isFloatingPointTy())
1041 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001042
Chris Bienemanad070d02014-09-17 20:55:46 +00001043 // cos(-x) -> cos(x)
1044 Value *Op1 = CI->getArgOperand(0);
1045 if (BinaryOperator::isFNeg(Op1)) {
1046 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1047 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1048 }
1049 return Ret;
1050}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001051
Weiming Zhao82130722015-12-04 22:00:47 +00001052static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1053 // Multiplications calculated using Addition Chains.
1054 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1055
1056 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1057
1058 if (InnerChain[Exp])
1059 return InnerChain[Exp];
1060
1061 static const unsigned AddChain[33][2] = {
1062 {0, 0}, // Unused.
1063 {0, 0}, // Unused (base case = pow1).
1064 {1, 1}, // Unused (pre-computed).
1065 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1066 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1067 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1068 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1069 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1070 };
1071
1072 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1073 getPow(InnerChain, AddChain[Exp][1], B));
1074 return InnerChain[Exp];
1075}
1076
Chris Bienemanad070d02014-09-17 20:55:46 +00001077Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1078 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001079 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001080 StringRef Name = Callee->getName();
1081 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001082 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001083
Chris Bienemanad070d02014-09-17 20:55:46 +00001084 FunctionType *FT = Callee->getFunctionType();
1085 // Just make sure this has 2 arguments of the same FP type, which match the
1086 // result type.
1087 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1088 FT->getParamType(0) != FT->getParamType(1) ||
1089 !FT->getParamType(0)->isFloatingPointTy())
1090 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001091
Chris Bienemanad070d02014-09-17 20:55:46 +00001092 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1093 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1094 // pow(1.0, x) -> 1.0
1095 if (Op1C->isExactlyValue(1.0))
1096 return Op1C;
1097 // pow(2.0, x) -> exp2(x)
1098 if (Op1C->isExactlyValue(2.0) &&
1099 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1100 LibFunc::exp2l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001101 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
Davide Italianod9f87b42015-11-06 21:05:07 +00001102 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001103 // pow(10.0, x) -> exp10(x)
1104 if (Op1C->isExactlyValue(10.0) &&
1105 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1106 LibFunc::exp10l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001107 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001108 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001109 }
1110
Sanjay Patel6002e782016-01-12 17:30:37 +00001111 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001112 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001113 // We enable these only with fast-math. Besides rounding differences, the
1114 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001115 // Example: x = 1000, y = 0.001.
1116 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001117 auto *OpC = dyn_cast<CallInst>(Op1);
1118 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1119 LibFunc::Func Func;
1120 Function *OpCCallee = OpC->getCalledFunction();
1121 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1122 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001123 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001124 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001125 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001126 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001127 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001128 }
1129 }
1130
Chris Bienemanad070d02014-09-17 20:55:46 +00001131 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1132 if (!Op2C)
1133 return Ret;
1134
1135 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1136 return ConstantFP::get(CI->getType(), 1.0);
1137
1138 if (Op2C->isExactlyValue(0.5) &&
1139 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1140 LibFunc::sqrtl) &&
1141 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1142 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001143
1144 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001145 if (CI->hasUnsafeAlgebra()) {
1146 IRBuilder<>::FastMathFlagGuard Guard(B);
1147 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Pateld3112a52016-01-19 19:46:10 +00001148 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
Davide Italianoc5cedd12015-11-18 23:21:32 +00001149 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001150 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001151
Chris Bienemanad070d02014-09-17 20:55:46 +00001152 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1153 // This is faster than calling pow, and still handles negative zero
1154 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001155 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1156 Value *Inf = ConstantFP::getInfinity(CI->getType());
1157 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Sanjay Pateld3112a52016-01-19 19:46:10 +00001158 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001159 Value *FAbs =
Sanjay Pateld3112a52016-01-19 19:46:10 +00001160 emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001161 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1162 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1163 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001164 }
1165
Chris Bienemanad070d02014-09-17 20:55:46 +00001166 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1167 return Op1;
1168 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1169 return B.CreateFMul(Op1, Op1, "pow2");
1170 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1171 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001172
1173 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001174 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001175 APFloat V = abs(Op2C->getValueAPF());
1176 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1177 // This transformation applies to integer exponents only.
1178 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1179 !V.isInteger())
1180 return nullptr;
1181
1182 // We will memoize intermediate products of the Addition Chain.
1183 Value *InnerChain[33] = {nullptr};
1184 InnerChain[1] = Op1;
1185 InnerChain[2] = B.CreateFMul(Op1, Op1);
1186
1187 // We cannot readily convert a non-double type (like float) to a double.
1188 // So we first convert V to something which could be converted to double.
1189 bool ignored;
1190 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001191
1192 // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
Weiming Zhao82130722015-12-04 22:00:47 +00001193 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1194 // For negative exponents simply compute the reciprocal.
1195 if (Op2C->isNegative())
1196 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1197 return FMul;
1198 }
1199
Chris Bienemanad070d02014-09-17 20:55:46 +00001200 return nullptr;
1201}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001202
Chris Bienemanad070d02014-09-17 20:55:46 +00001203Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1204 Function *Callee = CI->getCalledFunction();
1205 Function *Caller = CI->getParent()->getParent();
Chris Bienemanad070d02014-09-17 20:55:46 +00001206 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001207 StringRef Name = Callee->getName();
1208 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001209 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001210
Chris Bienemanad070d02014-09-17 20:55:46 +00001211 FunctionType *FT = Callee->getFunctionType();
1212 // Just make sure this has 1 argument of FP type, which matches the
1213 // result type.
1214 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1215 !FT->getParamType(0)->isFloatingPointTy())
1216 return Ret;
1217
1218 Value *Op = CI->getArgOperand(0);
1219 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1220 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1221 LibFunc::Func LdExp = LibFunc::ldexpl;
1222 if (Op->getType()->isFloatTy())
1223 LdExp = LibFunc::ldexpf;
1224 else if (Op->getType()->isDoubleTy())
1225 LdExp = LibFunc::ldexp;
1226
1227 if (TLI->has(LdExp)) {
1228 Value *LdExpArg = nullptr;
1229 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1230 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1231 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1232 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1233 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1234 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1235 }
1236
1237 if (LdExpArg) {
1238 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1239 if (!Op->getType()->isFloatTy())
1240 One = ConstantExpr::getFPExtend(One, Op->getType());
1241
1242 Module *M = Caller->getParent();
1243 Value *Callee =
1244 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001245 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001246 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001247 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1248 CI->setCallingConv(F->getCallingConv());
1249
1250 return CI;
1251 }
1252 }
1253 return Ret;
1254}
1255
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001256Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1257 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001258 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001259 StringRef Name = Callee->getName();
1260 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001261 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001262
1263 FunctionType *FT = Callee->getFunctionType();
1264 // Make sure this has 1 argument of FP type which matches the result type.
1265 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1266 !FT->getParamType(0)->isFloatingPointTy())
1267 return Ret;
1268
1269 Value *Op = CI->getArgOperand(0);
1270 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1271 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1272 if (I->getOpcode() == Instruction::FMul)
1273 if (I->getOperand(0) == I->getOperand(1))
1274 return Op;
1275 }
1276 return Ret;
1277}
1278
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001279Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1280 // If we can shrink the call to a float function rather than a double
1281 // function, do that first.
1282 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001283 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001284 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1285 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001286 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001287
1288 // Make sure this has 2 arguments of FP type which match the result type.
1289 FunctionType *FT = Callee->getFunctionType();
1290 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1291 FT->getParamType(0) != FT->getParamType(1) ||
1292 !FT->getParamType(0)->isFloatingPointTy())
1293 return nullptr;
1294
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001295 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001296 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001297 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001298 // Unsafe algebra sets all fast-math-flags to true.
1299 FMF.setUnsafeAlgebra();
1300 } else {
1301 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001302 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001303 return nullptr;
1304 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1305 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001306 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001307 // might be impractical."
1308 FMF.setNoSignedZeros();
1309 FMF.setNoNaNs();
1310 }
Sanjay Patela2528152016-01-12 18:03:37 +00001311 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001312
1313 // We have a relaxed floating-point environment. We can ignore NaN-handling
1314 // and transform to a compare and select. We do not have to consider errno or
1315 // exceptions, because fmin/fmax do not have those.
1316 Value *Op0 = CI->getArgOperand(0);
1317 Value *Op1 = CI->getArgOperand(1);
1318 Value *Cmp = Callee->getName().startswith("fmin") ?
1319 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1320 return B.CreateSelect(Cmp, Op0, Op1);
1321}
1322
Davide Italianob8b71332015-11-29 20:58:04 +00001323Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1324 Function *Callee = CI->getCalledFunction();
1325 Value *Ret = nullptr;
1326 StringRef Name = Callee->getName();
1327 if (UnsafeFPShrink && hasFloatVersion(Name))
1328 Ret = optimizeUnaryDoubleFP(CI, B, true);
1329 FunctionType *FT = Callee->getFunctionType();
1330
1331 // Just make sure this has 1 argument of FP type, which matches the
1332 // result type.
1333 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1334 !FT->getParamType(0)->isFloatingPointTy())
1335 return Ret;
1336
Sanjay Patele896ede2016-01-11 23:31:48 +00001337 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001338 return Ret;
1339 Value *Op1 = CI->getArgOperand(0);
1340 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001341
1342 // The earlier call must also be unsafe in order to do these transforms.
1343 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001344 return Ret;
1345
1346 // log(pow(x,y)) -> y*log(x)
1347 // This is only applicable to log, log2, log10.
1348 if (Name != "log" && Name != "log2" && Name != "log10")
1349 return Ret;
1350
1351 IRBuilder<>::FastMathFlagGuard Guard(B);
1352 FastMathFlags FMF;
1353 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001354 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001355
1356 LibFunc::Func Func;
1357 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001358 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1359 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001360 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001361 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001362 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001363
1364 // log(exp2(y)) -> y*log(2)
1365 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1366 TLI->has(Func) && Func == LibFunc::exp2)
1367 return B.CreateFMul(
1368 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001369 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001370 Callee->getName(), B, Callee->getAttributes()),
1371 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001372 return Ret;
1373}
1374
Sanjay Patelc699a612014-10-16 18:48:17 +00001375Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1376 Function *Callee = CI->getCalledFunction();
Sanjay Patelbd2dc672016-01-20 17:41:14 +00001377
Sanjay Patelc699a612014-10-16 18:48:17 +00001378 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001379 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1380 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001381 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001382
Sanjay Patelbd2dc672016-01-20 17:41:14 +00001383 // FIXME: Refactor - this check is repeated all over this file and even in the
1384 // preceding call to shrink double -> float.
1385
1386 // Make sure this has 1 argument of FP type, which matches the result type.
1387 FunctionType *FT = Callee->getFunctionType();
1388 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1389 !FT->getParamType(0)->isFloatingPointTy())
1390 return Ret;
1391
Sanjay Patel683f2972016-01-11 22:34:19 +00001392 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001393 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001394
Sanjay Patelc2d64612016-01-06 20:52:21 +00001395 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1396 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1397 return Ret;
1398
1399 // We're looking for a repeated factor in a multiplication tree,
1400 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001401 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001402 Value *Op0 = I->getOperand(0);
1403 Value *Op1 = I->getOperand(1);
1404 Value *RepeatOp = nullptr;
1405 Value *OtherOp = nullptr;
1406 if (Op0 == Op1) {
1407 // Simple match: the operands of the multiply are identical.
1408 RepeatOp = Op0;
1409 } else {
1410 // Look for a more complicated pattern: one of the operands is itself
1411 // a multiply, so search for a common factor in that multiply.
1412 // Note: We don't bother looking any deeper than this first level or for
1413 // variations of this pattern because instcombine's visitFMUL and/or the
1414 // reassociation pass should give us this form.
1415 Value *OtherMul0, *OtherMul1;
1416 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1417 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001418 if (OtherMul0 == OtherMul1 &&
1419 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001420 // Matched: sqrt((x * x) * z)
1421 RepeatOp = OtherMul0;
1422 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001423 }
1424 }
1425 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001426 if (!RepeatOp)
1427 return Ret;
1428
1429 // Fast math flags for any created instructions should match the sqrt
1430 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001431 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001432 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001433
Sanjay Patelc2d64612016-01-06 20:52:21 +00001434 // If we found a repeated factor, hoist it out of the square root and
1435 // replace it with the fabs of that factor.
1436 Module *M = Callee->getParent();
1437 Type *ArgType = I->getType();
1438 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1439 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1440 if (OtherOp) {
1441 // If we found a non-repeated factor, we still need to get its square
1442 // root. We then multiply that by the value that was simplified out
1443 // of the square root calculation.
1444 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1445 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1446 return B.CreateFMul(FabsCall, SqrtCall);
1447 }
1448 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001449}
1450
Sanjay Patelcddcd722016-01-06 19:23:35 +00001451// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001452Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1453 Function *Callee = CI->getCalledFunction();
1454 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001455 StringRef Name = Callee->getName();
1456 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001457 Ret = optimizeUnaryDoubleFP(CI, B, true);
1458 FunctionType *FT = Callee->getFunctionType();
1459
1460 // Just make sure this has 1 argument of FP type, which matches the
1461 // result type.
1462 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1463 !FT->getParamType(0)->isFloatingPointTy())
1464 return Ret;
1465
Davide Italiano51507d22015-11-04 23:36:56 +00001466 Value *Op1 = CI->getArgOperand(0);
1467 auto *OpC = dyn_cast<CallInst>(Op1);
1468 if (!OpC)
1469 return Ret;
1470
Sanjay Patelcddcd722016-01-06 19:23:35 +00001471 // Both calls must allow unsafe optimizations in order to remove them.
1472 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1473 return Ret;
1474
Davide Italiano51507d22015-11-04 23:36:56 +00001475 // tan(atan(x)) -> x
1476 // tanf(atanf(x)) -> x
1477 // tanl(atanl(x)) -> x
1478 LibFunc::Func Func;
1479 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001480 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001481 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1482 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1483 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1484 Ret = OpC->getArgOperand(0);
1485 return Ret;
1486}
1487
Chris Bienemanad070d02014-09-17 20:55:46 +00001488static bool isTrigLibCall(CallInst *CI);
1489static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1490 bool UseFloat, Value *&Sin, Value *&Cos,
1491 Value *&SinCos);
1492
1493Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1494
1495 // Make sure the prototype is as expected, otherwise the rest of the
1496 // function is probably invalid and likely to abort.
1497 if (!isTrigLibCall(CI))
1498 return nullptr;
1499
1500 Value *Arg = CI->getArgOperand(0);
1501 SmallVector<CallInst *, 1> SinCalls;
1502 SmallVector<CallInst *, 1> CosCalls;
1503 SmallVector<CallInst *, 1> SinCosCalls;
1504
1505 bool IsFloat = Arg->getType()->isFloatTy();
1506
1507 // Look for all compatible sinpi, cospi and sincospi calls with the same
1508 // argument. If there are enough (in some sense) we can make the
1509 // substitution.
1510 for (User *U : Arg->users())
1511 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1512 SinCosCalls);
1513
1514 // It's only worthwhile if both sinpi and cospi are actually used.
1515 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1516 return nullptr;
1517
1518 Value *Sin, *Cos, *SinCos;
1519 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1520
1521 replaceTrigInsts(SinCalls, Sin);
1522 replaceTrigInsts(CosCalls, Cos);
1523 replaceTrigInsts(SinCosCalls, SinCos);
1524
1525 return nullptr;
1526}
1527
1528static bool isTrigLibCall(CallInst *CI) {
1529 Function *Callee = CI->getCalledFunction();
1530 FunctionType *FT = Callee->getFunctionType();
1531
1532 // We can only hope to do anything useful if we can ignore things like errno
1533 // and floating-point exceptions.
1534 bool AttributesSafe =
1535 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1536
1537 // Other than that we need float(float) or double(double)
1538 return AttributesSafe && FT->getNumParams() == 1 &&
1539 FT->getReturnType() == FT->getParamType(0) &&
1540 (FT->getParamType(0)->isFloatTy() ||
1541 FT->getParamType(0)->isDoubleTy());
1542}
1543
1544void
1545LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1546 SmallVectorImpl<CallInst *> &SinCalls,
1547 SmallVectorImpl<CallInst *> &CosCalls,
1548 SmallVectorImpl<CallInst *> &SinCosCalls) {
1549 CallInst *CI = dyn_cast<CallInst>(Val);
1550
1551 if (!CI)
1552 return;
1553
1554 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001556 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1557 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001558 return;
1559
1560 if (IsFloat) {
1561 if (Func == LibFunc::sinpif)
1562 SinCalls.push_back(CI);
1563 else if (Func == LibFunc::cospif)
1564 CosCalls.push_back(CI);
1565 else if (Func == LibFunc::sincospif_stret)
1566 SinCosCalls.push_back(CI);
1567 } else {
1568 if (Func == LibFunc::sinpi)
1569 SinCalls.push_back(CI);
1570 else if (Func == LibFunc::cospi)
1571 CosCalls.push_back(CI);
1572 else if (Func == LibFunc::sincospi_stret)
1573 SinCosCalls.push_back(CI);
1574 }
1575}
1576
1577void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1578 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001579 for (CallInst *C : Calls)
1580 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001581}
1582
1583void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1584 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1585 Type *ArgTy = Arg->getType();
1586 Type *ResTy;
1587 StringRef Name;
1588
1589 Triple T(OrigCallee->getParent()->getTargetTriple());
1590 if (UseFloat) {
1591 Name = "__sincospif_stret";
1592
1593 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1594 // x86_64 can't use {float, float} since that would be returned in both
1595 // xmm0 and xmm1, which isn't what a real struct would do.
1596 ResTy = T.getArch() == Triple::x86_64
1597 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001598 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001599 } else {
1600 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001601 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001602 }
1603
1604 Module *M = OrigCallee->getParent();
1605 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001606 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001607
1608 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1609 // If the argument is an instruction, it must dominate all uses so put our
1610 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001611 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001612 } else {
1613 // Otherwise (e.g. for a constant) the beginning of the function is as
1614 // good a place as any.
1615 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1616 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1617 }
1618
1619 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1620
1621 if (SinCos->getType()->isStructTy()) {
1622 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1623 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1624 } else {
1625 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1626 "sinpi");
1627 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1628 "cospi");
1629 }
1630}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001631
Meador Inge7415f842012-11-25 20:45:27 +00001632//===----------------------------------------------------------------------===//
1633// Integer Library Call Optimizations
1634//===----------------------------------------------------------------------===//
1635
Davide Italiano396f3ee2015-10-31 23:17:45 +00001636static bool checkIntUnaryReturnAndParam(Function *Callee) {
1637 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001638 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1639 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001640}
1641
Chris Bienemanad070d02014-09-17 20:55:46 +00001642Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1643 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001644 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001645 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001647
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 // Constant fold.
1649 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1650 if (CI->isZero()) // ffs(0) -> 0.
1651 return B.getInt32(0);
1652 // ffs(c) -> cttz(c)+1
1653 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001654 }
Meador Inge7415f842012-11-25 20:45:27 +00001655
Chris Bienemanad070d02014-09-17 20:55:46 +00001656 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1657 Type *ArgType = Op->getType();
1658 Value *F =
1659 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001660 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1662 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001663
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1665 return B.CreateSelect(Cond, V, B.getInt32(0));
1666}
Meador Ingea0b6d872012-11-26 00:24:07 +00001667
Chris Bienemanad070d02014-09-17 20:55:46 +00001668Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1669 Function *Callee = CI->getCalledFunction();
1670 FunctionType *FT = Callee->getFunctionType();
1671 // We require integer(integer) where the types agree.
1672 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1673 FT->getParamType(0) != FT->getReturnType())
1674 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001675
Chris Bienemanad070d02014-09-17 20:55:46 +00001676 // abs(x) -> x >s -1 ? x : -x
1677 Value *Op = CI->getArgOperand(0);
1678 Value *Pos =
1679 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1680 Value *Neg = B.CreateNeg(Op, "neg");
1681 return B.CreateSelect(Pos, Op, Neg);
1682}
Meador Inge9a59ab62012-11-26 02:31:59 +00001683
Chris Bienemanad070d02014-09-17 20:55:46 +00001684Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001685 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001686 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001687
Chris Bienemanad070d02014-09-17 20:55:46 +00001688 // isdigit(c) -> (c-'0') <u 10
1689 Value *Op = CI->getArgOperand(0);
1690 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1691 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1692 return B.CreateZExt(Op, CI->getType());
1693}
Meador Ingea62a39e2012-11-26 03:10:07 +00001694
Chris Bienemanad070d02014-09-17 20:55:46 +00001695Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001696 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001697 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001698
Chris Bienemanad070d02014-09-17 20:55:46 +00001699 // isascii(c) -> c <u 128
1700 Value *Op = CI->getArgOperand(0);
1701 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1702 return B.CreateZExt(Op, CI->getType());
1703}
1704
1705Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001706 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001707 return nullptr;
1708
1709 // toascii(c) -> c & 0x7f
1710 return B.CreateAnd(CI->getArgOperand(0),
1711 ConstantInt::get(CI->getType(), 0x7F));
1712}
Meador Inge604937d2012-11-26 03:38:52 +00001713
Meador Inge08ca1152012-11-26 20:37:20 +00001714//===----------------------------------------------------------------------===//
1715// Formatting and IO Library Call Optimizations
1716//===----------------------------------------------------------------------===//
1717
Chris Bienemanad070d02014-09-17 20:55:46 +00001718static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001719
Chris Bienemanad070d02014-09-17 20:55:46 +00001720Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1721 int StreamArg) {
1722 // Error reporting calls should be cold, mark them as such.
1723 // This applies even to non-builtin calls: it is only a hint and applies to
1724 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001725
Chris Bienemanad070d02014-09-17 20:55:46 +00001726 // This heuristic was suggested in:
1727 // Improving Static Branch Prediction in a Compiler
1728 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1729 // Proceedings of PACT'98, Oct. 1998, IEEE
1730 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001731
Chris Bienemanad070d02014-09-17 20:55:46 +00001732 if (!CI->hasFnAttr(Attribute::Cold) &&
1733 isReportingError(Callee, CI, StreamArg)) {
1734 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1735 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001736
Chris Bienemanad070d02014-09-17 20:55:46 +00001737 return nullptr;
1738}
1739
1740static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001741 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001742 return false;
1743
1744 if (StreamArg < 0)
1745 return true;
1746
1747 // These functions might be considered cold, but only if their stream
1748 // argument is stderr.
1749
1750 if (StreamArg >= (int)CI->getNumArgOperands())
1751 return false;
1752 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1753 if (!LI)
1754 return false;
1755 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1756 if (!GV || !GV->isDeclaration())
1757 return false;
1758 return GV->getName() == "stderr";
1759}
1760
1761Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1762 // Check for a fixed format string.
1763 StringRef FormatStr;
1764 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001765 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001766
Chris Bienemanad070d02014-09-17 20:55:46 +00001767 // Empty format string -> noop.
1768 if (FormatStr.empty()) // Tolerate printf's declared void.
1769 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001770
Chris Bienemanad070d02014-09-17 20:55:46 +00001771 // Do not do any of the following transformations if the printf return value
1772 // is used, in general the printf return value is not compatible with either
1773 // putchar() or puts().
1774 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001775 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001776
1777 // printf("x") -> putchar('x'), even for '%'.
1778 if (FormatStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00001779 Value *Res = emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001780 if (CI->use_empty() || !Res)
1781 return Res;
1782 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001783 }
1784
Chris Bienemanad070d02014-09-17 20:55:46 +00001785 // printf("foo\n") --> puts("foo")
1786 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1787 FormatStr.find('%') == StringRef::npos) { // No format characters.
1788 // Create a string literal with no \n on it. We expect the constant merge
1789 // pass to be run after this pass, to merge duplicate strings.
1790 FormatStr = FormatStr.drop_back();
1791 Value *GV = B.CreateGlobalString(FormatStr, "str");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001792 Value *NewCI = emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 return (CI->use_empty() || !NewCI)
1794 ? NewCI
1795 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1796 }
Meador Inge08ca1152012-11-26 20:37:20 +00001797
Chris Bienemanad070d02014-09-17 20:55:46 +00001798 // Optimize specific format strings.
1799 // printf("%c", chr) --> putchar(chr)
1800 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1801 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00001802 Value *Res = emitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001803
Chris Bienemanad070d02014-09-17 20:55:46 +00001804 if (CI->use_empty() || !Res)
1805 return Res;
1806 return B.CreateIntCast(Res, CI->getType(), true);
1807 }
1808
1809 // printf("%s\n", str) --> puts(str)
1810 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1811 CI->getArgOperand(1)->getType()->isPointerTy()) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00001812 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001813 }
1814 return nullptr;
1815}
1816
1817Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1818
1819 Function *Callee = CI->getCalledFunction();
1820 // Require one fixed pointer argument and an integer/void result.
1821 FunctionType *FT = Callee->getFunctionType();
1822 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1823 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1824 return nullptr;
1825
1826 if (Value *V = optimizePrintFString(CI, B)) {
1827 return V;
1828 }
1829
1830 // printf(format, ...) -> iprintf(format, ...) if no floating point
1831 // arguments.
1832 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1833 Module *M = B.GetInsertBlock()->getParent()->getParent();
1834 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001835 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001836 CallInst *New = cast<CallInst>(CI->clone());
1837 New->setCalledFunction(IPrintFFn);
1838 B.Insert(New);
1839 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001840 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001841 return nullptr;
1842}
Meador Inge08ca1152012-11-26 20:37:20 +00001843
Chris Bienemanad070d02014-09-17 20:55:46 +00001844Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1845 // Check for a fixed format string.
1846 StringRef FormatStr;
1847 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001848 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001849
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 // If we just have a format string (nothing else crazy) transform it.
1851 if (CI->getNumArgOperands() == 2) {
1852 // Make sure there's no % in the constant array. We could try to handle
1853 // %% -> % in the future if we cared.
1854 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1855 if (FormatStr[i] == '%')
1856 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001857
Chris Bienemanad070d02014-09-17 20:55:46 +00001858 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001859 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1860 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1861 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001862 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001863 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001864 }
Meador Ingef8e72502012-11-29 15:45:43 +00001865
Chris Bienemanad070d02014-09-17 20:55:46 +00001866 // The remaining optimizations require the format string to be "%s" or "%c"
1867 // and have an extra operand.
1868 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1869 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001870 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001871
Chris Bienemanad070d02014-09-17 20:55:46 +00001872 // Decode the second character of the format string.
1873 if (FormatStr[1] == 'c') {
1874 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1875 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1876 return nullptr;
1877 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001878 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001879 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001880 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001881 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001882
Chris Bienemanad070d02014-09-17 20:55:46 +00001883 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001884 }
1885
Chris Bienemanad070d02014-09-17 20:55:46 +00001886 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001887 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1888 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1889 return nullptr;
1890
Sanjay Pateld3112a52016-01-19 19:46:10 +00001891 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001892 if (!Len)
1893 return nullptr;
1894 Value *IncLen =
1895 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper67cf9a72015-11-19 05:56:52 +00001896 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001897
1898 // The sprintf result is the unincremented number of bytes in the string.
1899 return B.CreateIntCast(Len, CI->getType(), false);
1900 }
1901 return nullptr;
1902}
1903
1904Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1905 Function *Callee = CI->getCalledFunction();
1906 // Require two fixed pointer arguments and an integer result.
1907 FunctionType *FT = Callee->getFunctionType();
1908 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1909 !FT->getParamType(1)->isPointerTy() ||
1910 !FT->getReturnType()->isIntegerTy())
1911 return nullptr;
1912
1913 if (Value *V = optimizeSPrintFString(CI, B)) {
1914 return V;
1915 }
1916
1917 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1918 // point arguments.
1919 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1920 Module *M = B.GetInsertBlock()->getParent()->getParent();
1921 Constant *SIPrintFFn =
1922 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1923 CallInst *New = cast<CallInst>(CI->clone());
1924 New->setCalledFunction(SIPrintFFn);
1925 B.Insert(New);
1926 return New;
1927 }
1928 return nullptr;
1929}
1930
1931Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1932 optimizeErrorReporting(CI, B, 0);
1933
1934 // All the optimizations depend on the format string.
1935 StringRef FormatStr;
1936 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1937 return nullptr;
1938
1939 // Do not do any of the following transformations if the fprintf return
1940 // value is used, in general the fprintf return value is not compatible
1941 // with fwrite(), fputc() or fputs().
1942 if (!CI->use_empty())
1943 return nullptr;
1944
1945 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1946 if (CI->getNumArgOperands() == 2) {
1947 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1948 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1949 return nullptr; // We found a format specifier.
1950
Sanjay Pateld3112a52016-01-19 19:46:10 +00001951 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001952 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001953 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001954 CI->getArgOperand(0), B, DL, TLI);
1955 }
1956
1957 // The remaining optimizations require the format string to be "%s" or "%c"
1958 // and have an extra operand.
1959 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1960 CI->getNumArgOperands() < 3)
1961 return nullptr;
1962
1963 // Decode the second character of the format string.
1964 if (FormatStr[1] == 'c') {
1965 // fprintf(F, "%c", chr) --> fputc(chr, F)
1966 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1967 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001968 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001969 }
1970
1971 if (FormatStr[1] == 's') {
1972 // fprintf(F, "%s", str) --> fputs(str, F)
1973 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1974 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001975 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001976 }
1977 return nullptr;
1978}
1979
1980Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1981 Function *Callee = CI->getCalledFunction();
1982 // Require two fixed paramters as pointers and integer result.
1983 FunctionType *FT = Callee->getFunctionType();
1984 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1985 !FT->getParamType(1)->isPointerTy() ||
1986 !FT->getReturnType()->isIntegerTy())
1987 return nullptr;
1988
1989 if (Value *V = optimizeFPrintFString(CI, B)) {
1990 return V;
1991 }
1992
1993 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1994 // floating point arguments.
1995 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1996 Module *M = B.GetInsertBlock()->getParent()->getParent();
1997 Constant *FIPrintFFn =
1998 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1999 CallInst *New = cast<CallInst>(CI->clone());
2000 New->setCalledFunction(FIPrintFFn);
2001 B.Insert(New);
2002 return New;
2003 }
2004 return nullptr;
2005}
2006
2007Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2008 optimizeErrorReporting(CI, B, 3);
2009
2010 Function *Callee = CI->getCalledFunction();
2011 // Require a pointer, an integer, an integer, a pointer, returning integer.
2012 FunctionType *FT = Callee->getFunctionType();
2013 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2014 !FT->getParamType(1)->isIntegerTy() ||
2015 !FT->getParamType(2)->isIntegerTy() ||
2016 !FT->getParamType(3)->isPointerTy() ||
2017 !FT->getReturnType()->isIntegerTy())
2018 return nullptr;
2019
2020 // Get the element size and count.
2021 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2022 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2023 if (!SizeC || !CountC)
2024 return nullptr;
2025 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2026
2027 // If this is writing zero records, remove the call (it's a noop).
2028 if (Bytes == 0)
2029 return ConstantInt::get(CI->getType(), 0);
2030
2031 // If this is writing one byte, turn it into fputc.
2032 // This optimisation is only valid, if the return value is unused.
2033 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00002034 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2035 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002036 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2037 }
2038
2039 return nullptr;
2040}
2041
2042Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2043 optimizeErrorReporting(CI, B, 1);
2044
2045 Function *Callee = CI->getCalledFunction();
2046
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 // Require two pointers. Also, we can't optimize if return value is used.
2048 FunctionType *FT = Callee->getFunctionType();
2049 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2050 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2051 return nullptr;
2052
2053 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2054 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2055 if (!Len)
2056 return nullptr;
2057
2058 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002059 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002060 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002061 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002062 CI->getArgOperand(1), B, DL, TLI);
2063}
2064
2065Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2066 Function *Callee = CI->getCalledFunction();
2067 // Require one fixed pointer argument and an integer/void result.
2068 FunctionType *FT = Callee->getFunctionType();
2069 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2070 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2071 return nullptr;
2072
2073 // Check for a constant string.
2074 StringRef Str;
2075 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2076 return nullptr;
2077
2078 if (Str.empty() && CI->use_empty()) {
2079 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002080 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002081 if (CI->use_empty() || !Res)
2082 return Res;
2083 return B.CreateIntCast(Res, CI->getType(), true);
2084 }
2085
2086 return nullptr;
2087}
2088
2089bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002090 LibFunc::Func Func;
2091 SmallString<20> FloatFuncName = FuncName;
2092 FloatFuncName += 'f';
2093 if (TLI->getLibFunc(FloatFuncName, Func))
2094 return TLI->has(Func);
2095 return false;
2096}
Meador Inge7fb2f732012-10-13 16:45:32 +00002097
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002098Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2099 IRBuilder<> &Builder) {
2100 LibFunc::Func Func;
2101 Function *Callee = CI->getCalledFunction();
2102 StringRef FuncName = Callee->getName();
2103
2104 // Check for string/memory library functions.
2105 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2106 // Make sure we never change the calling convention.
2107 assert((ignoreCallingConv(Func) ||
2108 CI->getCallingConv() == llvm::CallingConv::C) &&
2109 "Optimizing string/memory libcall would change the calling convention");
2110 switch (Func) {
2111 case LibFunc::strcat:
2112 return optimizeStrCat(CI, Builder);
2113 case LibFunc::strncat:
2114 return optimizeStrNCat(CI, Builder);
2115 case LibFunc::strchr:
2116 return optimizeStrChr(CI, Builder);
2117 case LibFunc::strrchr:
2118 return optimizeStrRChr(CI, Builder);
2119 case LibFunc::strcmp:
2120 return optimizeStrCmp(CI, Builder);
2121 case LibFunc::strncmp:
2122 return optimizeStrNCmp(CI, Builder);
2123 case LibFunc::strcpy:
2124 return optimizeStrCpy(CI, Builder);
2125 case LibFunc::stpcpy:
2126 return optimizeStpCpy(CI, Builder);
2127 case LibFunc::strncpy:
2128 return optimizeStrNCpy(CI, Builder);
2129 case LibFunc::strlen:
2130 return optimizeStrLen(CI, Builder);
2131 case LibFunc::strpbrk:
2132 return optimizeStrPBrk(CI, Builder);
2133 case LibFunc::strtol:
2134 case LibFunc::strtod:
2135 case LibFunc::strtof:
2136 case LibFunc::strtoul:
2137 case LibFunc::strtoll:
2138 case LibFunc::strtold:
2139 case LibFunc::strtoull:
2140 return optimizeStrTo(CI, Builder);
2141 case LibFunc::strspn:
2142 return optimizeStrSpn(CI, Builder);
2143 case LibFunc::strcspn:
2144 return optimizeStrCSpn(CI, Builder);
2145 case LibFunc::strstr:
2146 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002147 case LibFunc::memchr:
2148 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002149 case LibFunc::memcmp:
2150 return optimizeMemCmp(CI, Builder);
2151 case LibFunc::memcpy:
2152 return optimizeMemCpy(CI, Builder);
2153 case LibFunc::memmove:
2154 return optimizeMemMove(CI, Builder);
2155 case LibFunc::memset:
2156 return optimizeMemSet(CI, Builder);
2157 default:
2158 break;
2159 }
2160 }
2161 return nullptr;
2162}
2163
Chris Bienemanad070d02014-09-17 20:55:46 +00002164Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2165 if (CI->isNoBuiltin())
2166 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002167
Meador Inge20255ef2013-03-12 00:08:29 +00002168 LibFunc::Func Func;
2169 Function *Callee = CI->getCalledFunction();
2170 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002171
2172 SmallVector<OperandBundleDef, 2> OpBundles;
2173 CI->getOperandBundlesAsDefs(OpBundles);
2174 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Chris Bienemanad070d02014-09-17 20:55:46 +00002175 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002176
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002177 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002178 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2179 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002180 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002181 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002182
Sanjay Patel848309d2014-10-23 21:52:45 +00002183 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002184 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002185 if (!isCallingConvC)
2186 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002187 switch (II->getIntrinsicID()) {
2188 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002189 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002190 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002191 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002192 case Intrinsic::fabs:
2193 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002194 case Intrinsic::log:
2195 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002196 case Intrinsic::sqrt:
2197 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002198 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002199 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002200 }
2201 }
2202
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002203 // Also try to simplify calls to fortified library functions.
2204 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2205 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002206 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002207 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2208 // Use an IR Builder from SimplifiedCI if available instead of CI
2209 // to guarantee we reach all uses we might replace later on.
2210 IRBuilder<> TmpBuilder(SimplifiedCI);
2211 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002212 // If we were able to further simplify, remove the now redundant call.
2213 SimplifiedCI->replaceAllUsesWith(V);
2214 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002215 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002216 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002217 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002218 return SimplifiedFortifiedCI;
2219 }
2220
Meador Inge20255ef2013-03-12 00:08:29 +00002221 // Then check for known library functions.
2222 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002223 // We never change the calling convention.
2224 if (!ignoreCallingConv(Func) && !isCallingConvC)
2225 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002226 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2227 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002228 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002229 case LibFunc::cosf:
2230 case LibFunc::cos:
2231 case LibFunc::cosl:
2232 return optimizeCos(CI, Builder);
2233 case LibFunc::sinpif:
2234 case LibFunc::sinpi:
2235 case LibFunc::cospif:
2236 case LibFunc::cospi:
2237 return optimizeSinCosPi(CI, Builder);
2238 case LibFunc::powf:
2239 case LibFunc::pow:
2240 case LibFunc::powl:
2241 return optimizePow(CI, Builder);
2242 case LibFunc::exp2l:
2243 case LibFunc::exp2:
2244 case LibFunc::exp2f:
2245 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002246 case LibFunc::fabsf:
2247 case LibFunc::fabs:
2248 case LibFunc::fabsl:
2249 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002250 case LibFunc::sqrtf:
2251 case LibFunc::sqrt:
2252 case LibFunc::sqrtl:
2253 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002254 case LibFunc::ffs:
2255 case LibFunc::ffsl:
2256 case LibFunc::ffsll:
2257 return optimizeFFS(CI, Builder);
2258 case LibFunc::abs:
2259 case LibFunc::labs:
2260 case LibFunc::llabs:
2261 return optimizeAbs(CI, Builder);
2262 case LibFunc::isdigit:
2263 return optimizeIsDigit(CI, Builder);
2264 case LibFunc::isascii:
2265 return optimizeIsAscii(CI, Builder);
2266 case LibFunc::toascii:
2267 return optimizeToAscii(CI, Builder);
2268 case LibFunc::printf:
2269 return optimizePrintF(CI, Builder);
2270 case LibFunc::sprintf:
2271 return optimizeSPrintF(CI, Builder);
2272 case LibFunc::fprintf:
2273 return optimizeFPrintF(CI, Builder);
2274 case LibFunc::fwrite:
2275 return optimizeFWrite(CI, Builder);
2276 case LibFunc::fputs:
2277 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002278 case LibFunc::log:
2279 case LibFunc::log10:
2280 case LibFunc::log1p:
2281 case LibFunc::log2:
2282 case LibFunc::logb:
2283 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002284 case LibFunc::puts:
2285 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002286 case LibFunc::tan:
2287 case LibFunc::tanf:
2288 case LibFunc::tanl:
2289 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002290 case LibFunc::perror:
2291 return optimizeErrorReporting(CI, Builder);
2292 case LibFunc::vfprintf:
2293 case LibFunc::fiprintf:
2294 return optimizeErrorReporting(CI, Builder, 0);
2295 case LibFunc::fputc:
2296 return optimizeErrorReporting(CI, Builder, 1);
2297 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002298 case LibFunc::floor:
2299 case LibFunc::rint:
2300 case LibFunc::round:
2301 case LibFunc::nearbyint:
2302 case LibFunc::trunc:
2303 if (hasFloatVersion(FuncName))
2304 return optimizeUnaryDoubleFP(CI, Builder, false);
2305 return nullptr;
2306 case LibFunc::acos:
2307 case LibFunc::acosh:
2308 case LibFunc::asin:
2309 case LibFunc::asinh:
2310 case LibFunc::atan:
2311 case LibFunc::atanh:
2312 case LibFunc::cbrt:
2313 case LibFunc::cosh:
2314 case LibFunc::exp:
2315 case LibFunc::exp10:
2316 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002317 case LibFunc::sin:
2318 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002319 case LibFunc::tanh:
2320 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2321 return optimizeUnaryDoubleFP(CI, Builder, true);
2322 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002323 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002324 if (hasFloatVersion(FuncName))
2325 return optimizeBinaryDoubleFP(CI, Builder);
2326 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002327 case LibFunc::fminf:
2328 case LibFunc::fmin:
2329 case LibFunc::fminl:
2330 case LibFunc::fmaxf:
2331 case LibFunc::fmax:
2332 case LibFunc::fmaxl:
2333 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002334 default:
2335 return nullptr;
2336 }
Meador Inge20255ef2013-03-12 00:08:29 +00002337 }
Craig Topperf40110f2014-04-25 05:29:35 +00002338 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002339}
2340
Chandler Carruth92803822015-01-21 02:11:59 +00002341LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002342 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002343 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002344 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002345 Replacer(Replacer) {}
2346
2347void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2348 // Indirect through the replacer used in this instance.
2349 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002350}
2351
Meador Ingedfb08a22013-06-20 19:48:07 +00002352// TODO:
2353// Additional cases that we need to add to this file:
2354//
2355// cbrt:
2356// * cbrt(expN(X)) -> expN(x/3)
2357// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002358// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002359//
2360// exp, expf, expl:
2361// * exp(log(x)) -> x
2362//
2363// log, logf, logl:
2364// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002365// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002366// * log(exp10(y)) -> y*log(10)
2367// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002368//
2369// lround, lroundf, lroundl:
2370// * lround(cnst) -> cnst'
2371//
2372// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002373// * pow(sqrt(x),y) -> pow(x,y*0.5)
2374// * pow(pow(x,y),z)-> pow(x,y*z)
2375//
2376// round, roundf, roundl:
2377// * round(cnst) -> cnst'
2378//
2379// signbit:
2380// * signbit(cnst) -> cnst'
2381// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2382//
2383// sqrt, sqrtf, sqrtl:
2384// * sqrt(expN(x)) -> expN(x*0.5)
2385// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2386// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2387//
Meador Ingedfb08a22013-06-20 19:48:07 +00002388// trunc, truncf, truncl:
2389// * trunc(cnst) -> cnst'
2390//
2391//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002392
2393//===----------------------------------------------------------------------===//
2394// Fortified Library Call Optimizations
2395//===----------------------------------------------------------------------===//
2396
2397bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2398 unsigned ObjSizeOp,
2399 unsigned SizeOp,
2400 bool isString) {
2401 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2402 return true;
2403 if (ConstantInt *ObjSizeCI =
2404 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2405 if (ObjSizeCI->isAllOnesValue())
2406 return true;
2407 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2408 if (OnlyLowerUnknownSize)
2409 return false;
2410 if (isString) {
2411 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2412 // If the length is 0 we don't know how long it is and so we can't
2413 // remove the check.
2414 if (Len == 0)
2415 return false;
2416 return ObjSizeCI->getZExtValue() >= Len;
2417 }
2418 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2419 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2420 }
2421 return false;
2422}
2423
Sanjay Pateld707db92015-12-31 16:10:49 +00002424Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2425 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002426 Function *Callee = CI->getCalledFunction();
2427
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002428 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002429 return nullptr;
2430
2431 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2432 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002433 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002434 return CI->getArgOperand(0);
2435 }
2436 return nullptr;
2437}
2438
Sanjay Pateld707db92015-12-31 16:10:49 +00002439Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2440 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002441 Function *Callee = CI->getCalledFunction();
2442
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002443 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002444 return nullptr;
2445
2446 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2447 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002448 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002449 return CI->getArgOperand(0);
2450 }
2451 return nullptr;
2452}
2453
Sanjay Pateld707db92015-12-31 16:10:49 +00002454Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2455 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002456 Function *Callee = CI->getCalledFunction();
2457
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002458 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002459 return nullptr;
2460
2461 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2462 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2463 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2464 return CI->getArgOperand(0);
2465 }
2466 return nullptr;
2467}
2468
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002469Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2470 IRBuilder<> &B,
2471 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002472 Function *Callee = CI->getCalledFunction();
2473 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002474 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002475
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002476 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002477 return nullptr;
2478
2479 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2480 *ObjSize = CI->getArgOperand(2);
2481
2482 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002483 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002484 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002485 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002486 }
2487
2488 // If a) we don't have any length information, or b) we know this will
2489 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2490 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2491 // TODO: It might be nice to get a maximum length out of the possible
2492 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002493 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002494 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002495
David Blaikie65fab6d2015-04-03 21:32:06 +00002496 if (OnlyLowerUnknownSize)
2497 return nullptr;
2498
2499 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2500 uint64_t Len = GetStringLength(Src);
2501 if (Len == 0)
2502 return nullptr;
2503
2504 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2505 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002506 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002507 // If the function was an __stpcpy_chk, and we were able to fold it into
2508 // a __memcpy_chk, we still need to return the correct end pointer.
2509 if (Ret && Func == LibFunc::stpcpy_chk)
2510 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2511 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002512}
2513
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002514Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2515 IRBuilder<> &B,
2516 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002517 Function *Callee = CI->getCalledFunction();
2518 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002519
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002520 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002521 return nullptr;
2522 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002523 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002524 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002525 return Ret;
2526 }
2527 return nullptr;
2528}
2529
2530Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002531 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2532 // Some clang users checked for _chk libcall availability using:
2533 // __has_builtin(__builtin___memcpy_chk)
2534 // When compiling with -fno-builtin, this is always true.
2535 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2536 // end up with fortified libcalls, which isn't acceptable in a freestanding
2537 // environment which only provides their non-fortified counterparts.
2538 //
2539 // Until we change clang and/or teach external users to check for availability
2540 // differently, disregard the "nobuiltin" attribute and TLI::has.
2541 //
2542 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002543
2544 LibFunc::Func Func;
2545 Function *Callee = CI->getCalledFunction();
2546 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002547
2548 SmallVector<OperandBundleDef, 2> OpBundles;
2549 CI->getOperandBundlesAsDefs(OpBundles);
2550 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002551 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2552
2553 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002554 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002555 return nullptr;
2556
2557 // We never change the calling convention.
2558 if (!ignoreCallingConv(Func) && !isCallingConvC)
2559 return nullptr;
2560
2561 switch (Func) {
2562 case LibFunc::memcpy_chk:
2563 return optimizeMemCpyChk(CI, Builder);
2564 case LibFunc::memmove_chk:
2565 return optimizeMemMoveChk(CI, Builder);
2566 case LibFunc::memset_chk:
2567 return optimizeMemSetChk(CI, Builder);
2568 case LibFunc::stpcpy_chk:
2569 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002570 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002571 case LibFunc::stpncpy_chk:
2572 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002573 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002574 default:
2575 break;
2576 }
2577 return nullptr;
2578}
2579
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002580FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2581 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2582 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}