blob: b0c8fc7f99781a5ffe4141223a4e82c664fa9b92 [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
David L Kreitzer752c1442016-04-13 14:31:06 +0000538 // If s is a constant pointer pointing to a string literal, we can fold
539 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
540 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
541 // We only try to simplify strlen when the pointer s points to an array
542 // of i8. Otherwise, we would need to scale the offset x before doing the
543 // subtraction. This will make the optimization more complex, and it's not
544 // very useful because calling strlen for a pointer of other types is
545 // very uncommon.
546 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
547 if (!isGEPBasedOnPointerToString(GEP))
548 return nullptr;
549
550 StringRef Str;
551 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
552 size_t NullTermIdx = Str.find('\0');
553
554 // If the string does not have '\0', leave it to strlen to compute
555 // its length.
556 if (NullTermIdx == StringRef::npos)
557 return nullptr;
558
559 Value *Offset = GEP->getOperand(2);
560 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
561 APInt KnownZero(BitWidth, 0);
562 APInt KnownOne(BitWidth, 0);
563 computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
564 nullptr);
565 KnownZero.flipAllBits();
566 size_t ArrSize =
567 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
568
569 // KnownZero's bits are flipped, so zeros in KnownZero now represent
570 // bits known to be zeros in Offset, and ones in KnowZero represent
571 // bits unknown in Offset. Therefore, Offset is known to be in range
572 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
573 // unsigned-less-than NullTermIdx.
574 //
575 // If Offset is not provably in the range [0, NullTermIdx], we can still
576 // optimize if we can prove that the program has undefined behavior when
577 // Offset is outside that range. That is the case when GEP->getOperand(0)
578 // is a pointer to an object whose memory extent is NullTermIdx+1.
579 if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
580 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
581 NullTermIdx == ArrSize - 1))
582 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
583 Offset);
584 }
585
586 return nullptr;
587 }
588
Chris Bienemanad070d02014-09-17 20:55:46 +0000589 // strlen(x?"foo":"bars") --> x ? 3 : 4
590 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
591 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
592 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
593 if (LenTrue && LenFalse) {
594 Function *Caller = CI->getParent()->getParent();
595 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
596 SI->getDebugLoc(),
597 "folded strlen(select) to select of constants");
598 return B.CreateSelect(SI->getCondition(),
599 ConstantInt::get(CI->getType(), LenTrue - 1),
600 ConstantInt::get(CI->getType(), LenFalse - 1));
601 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000602 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000603
Chris Bienemanad070d02014-09-17 20:55:46 +0000604 // strlen(x) != 0 --> *x != 0
605 // strlen(x) == 0 --> *x == 0
606 if (isOnlyUsedInZeroEqualityComparison(CI))
607 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000608
Chris Bienemanad070d02014-09-17 20:55:46 +0000609 return nullptr;
610}
Meador Inge17418502012-10-13 16:45:37 +0000611
Chris Bienemanad070d02014-09-17 20:55:46 +0000612Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
613 Function *Callee = CI->getCalledFunction();
614 FunctionType *FT = Callee->getFunctionType();
615 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
616 FT->getParamType(1) != FT->getParamType(0) ||
617 FT->getReturnType() != FT->getParamType(0))
618 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000619
Chris Bienemanad070d02014-09-17 20:55:46 +0000620 StringRef S1, S2;
621 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
622 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000623
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000624 // strpbrk(s, "") -> nullptr
625 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000626 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
627 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000628
Chris Bienemanad070d02014-09-17 20:55:46 +0000629 // Constant folding.
630 if (HasS1 && HasS2) {
631 size_t I = S1.find_first_of(S2);
632 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000633 return Constant::getNullValue(CI->getType());
634
Sanjay Pateld707db92015-12-31 16:10:49 +0000635 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
636 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000637 }
Meador Inge17418502012-10-13 16:45:37 +0000638
Chris Bienemanad070d02014-09-17 20:55:46 +0000639 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000640 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000641 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000642
643 return nullptr;
644}
645
646Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
647 Function *Callee = CI->getCalledFunction();
648 FunctionType *FT = Callee->getFunctionType();
649 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
650 !FT->getParamType(0)->isPointerTy() ||
651 !FT->getParamType(1)->isPointerTy())
652 return nullptr;
653
654 Value *EndPtr = CI->getArgOperand(1);
655 if (isa<ConstantPointerNull>(EndPtr)) {
656 // With a null EndPtr, this function won't capture the main argument.
657 // It would be readonly too, except that it still may write to errno.
658 CI->addAttribute(1, Attribute::NoCapture);
659 }
660
661 return nullptr;
662}
663
664Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
665 Function *Callee = CI->getCalledFunction();
666 FunctionType *FT = Callee->getFunctionType();
667 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
668 FT->getParamType(1) != FT->getParamType(0) ||
669 !FT->getReturnType()->isIntegerTy())
670 return nullptr;
671
672 StringRef S1, S2;
673 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
674 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
675
676 // strspn(s, "") -> 0
677 // strspn("", s) -> 0
678 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
679 return Constant::getNullValue(CI->getType());
680
681 // Constant folding.
682 if (HasS1 && HasS2) {
683 size_t Pos = S1.find_first_not_of(S2);
684 if (Pos == StringRef::npos)
685 Pos = S1.size();
686 return ConstantInt::get(CI->getType(), Pos);
687 }
688
689 return nullptr;
690}
691
692Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
693 Function *Callee = CI->getCalledFunction();
694 FunctionType *FT = Callee->getFunctionType();
695 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
696 FT->getParamType(1) != FT->getParamType(0) ||
697 !FT->getReturnType()->isIntegerTy())
698 return nullptr;
699
700 StringRef S1, S2;
701 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
702 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
703
704 // strcspn("", s) -> 0
705 if (HasS1 && S1.empty())
706 return Constant::getNullValue(CI->getType());
707
708 // Constant folding.
709 if (HasS1 && HasS2) {
710 size_t Pos = S1.find_first_of(S2);
711 if (Pos == StringRef::npos)
712 Pos = S1.size();
713 return ConstantInt::get(CI->getType(), Pos);
714 }
715
716 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000717 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000718 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000719
720 return nullptr;
721}
722
723Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
724 Function *Callee = CI->getCalledFunction();
725 FunctionType *FT = Callee->getFunctionType();
726 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
727 !FT->getParamType(1)->isPointerTy() ||
728 !FT->getReturnType()->isPointerTy())
729 return nullptr;
730
731 // fold strstr(x, x) -> x.
732 if (CI->getArgOperand(0) == CI->getArgOperand(1))
733 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
734
735 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000737 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000738 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000739 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000740 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 StrLen, B, DL, TLI);
742 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000743 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000744 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
745 ICmpInst *Old = cast<ICmpInst>(*UI++);
746 Value *Cmp =
747 B.CreateICmp(Old->getPredicate(), StrNCmp,
748 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
749 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000750 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000751 return CI;
752 }
Meador Inge17418502012-10-13 16:45:37 +0000753
Chris Bienemanad070d02014-09-17 20:55:46 +0000754 // See if either input string is a constant string.
755 StringRef SearchStr, ToFindStr;
756 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
757 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
758
759 // fold strstr(x, "") -> x.
760 if (HasStr2 && ToFindStr.empty())
761 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
762
763 // If both strings are known, constant fold it.
764 if (HasStr1 && HasStr2) {
765 size_t Offset = SearchStr.find(ToFindStr);
766
767 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000768 return Constant::getNullValue(CI->getType());
769
Chris Bienemanad070d02014-09-17 20:55:46 +0000770 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000771 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000772 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
773 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000774 }
Meador Inge17418502012-10-13 16:45:37 +0000775
Chris Bienemanad070d02014-09-17 20:55:46 +0000776 // fold strstr(x, "y") -> strchr(x, 'y').
777 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000778 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000779 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
780 }
781 return nullptr;
782}
Meador Inge40b6fac2012-10-15 03:47:37 +0000783
Benjamin Kramer691363e2015-03-21 15:36:21 +0000784Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
785 Function *Callee = CI->getCalledFunction();
786 FunctionType *FT = Callee->getFunctionType();
787 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
788 !FT->getParamType(1)->isIntegerTy(32) ||
789 !FT->getParamType(2)->isIntegerTy() ||
790 !FT->getReturnType()->isPointerTy())
791 return nullptr;
792
793 Value *SrcStr = CI->getArgOperand(0);
794 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
795 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
796
797 // memchr(x, y, 0) -> null
798 if (LenC && LenC->isNullValue())
799 return Constant::getNullValue(CI->getType());
800
Benjamin Kramer7857d722015-03-21 21:09:33 +0000801 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000802 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000803 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000804 return nullptr;
805
806 // Truncate the string to LenC. If Str is smaller than LenC we will still only
807 // scan the string, as reading past the end of it is undefined and we can just
808 // return null if we don't find the char.
809 Str = Str.substr(0, LenC->getZExtValue());
810
Benjamin Kramer7857d722015-03-21 21:09:33 +0000811 // If the char is variable but the input str and length are not we can turn
812 // this memchr call into a simple bit field test. Of course this only works
813 // when the return value is only checked against null.
814 //
815 // It would be really nice to reuse switch lowering here but we can't change
816 // the CFG at this point.
817 //
818 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
819 // after bounds check.
820 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000821 unsigned char Max =
822 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
823 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000824
825 // Make sure the bit field we're about to create fits in a register on the
826 // target.
827 // FIXME: On a 64 bit architecture this prevents us from using the
828 // interesting range of alpha ascii chars. We could do better by emitting
829 // two bitfields or shifting the range by 64 if no lower chars are used.
830 if (!DL.fitsInLegalInteger(Max + 1))
831 return nullptr;
832
833 // For the bit field use a power-of-2 type with at least 8 bits to avoid
834 // creating unnecessary illegal types.
835 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
836
837 // Now build the bit field.
838 APInt Bitfield(Width, 0);
839 for (char C : Str)
840 Bitfield.setBit((unsigned char)C);
841 Value *BitfieldC = B.getInt(Bitfield);
842
843 // First check that the bit field access is within bounds.
844 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
845 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
846 "memchr.bounds");
847
848 // Create code that checks if the given bit is set in the field.
849 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
850 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
851
852 // Finally merge both checks and cast to pointer type. The inttoptr
853 // implicitly zexts the i1 to intptr type.
854 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
855 }
856
857 // Check if all arguments are constants. If so, we can constant fold.
858 if (!CharC)
859 return nullptr;
860
Benjamin Kramer691363e2015-03-21 15:36:21 +0000861 // Compute the offset.
862 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
863 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
864 return Constant::getNullValue(CI->getType());
865
866 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000867 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000868}
869
Chris Bienemanad070d02014-09-17 20:55:46 +0000870Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
871 Function *Callee = CI->getCalledFunction();
872 FunctionType *FT = Callee->getFunctionType();
873 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
874 !FT->getParamType(1)->isPointerTy() ||
875 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000876 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000877
Chris Bienemanad070d02014-09-17 20:55:46 +0000878 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000879
Chris Bienemanad070d02014-09-17 20:55:46 +0000880 if (LHS == RHS) // memcmp(s,s,x) -> 0
881 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000882
Chris Bienemanad070d02014-09-17 20:55:46 +0000883 // Make sure we have a constant length.
884 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
885 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000886 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000887 uint64_t Len = LenC->getZExtValue();
888
889 if (Len == 0) // memcmp(s1,s2,0) -> 0
890 return Constant::getNullValue(CI->getType());
891
892 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
893 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000894 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000895 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000896 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000897 CI->getType(), "rhsv");
898 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000899 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000900
Chad Rosierdc655322015-08-28 18:30:18 +0000901 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
902 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
903
904 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
905 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
906
907 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
908 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
909
910 Type *LHSPtrTy =
911 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
912 Type *RHSPtrTy =
913 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
914
Sanjay Pateld707db92015-12-31 16:10:49 +0000915 Value *LHSV =
916 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
917 Value *RHSV =
918 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000919
920 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
921 }
922 }
923
Chris Bienemanad070d02014-09-17 20:55:46 +0000924 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
925 StringRef LHSStr, RHSStr;
926 if (getConstantStringInfo(LHS, LHSStr) &&
927 getConstantStringInfo(RHS, RHSStr)) {
928 // Make sure we're not reading out-of-bounds memory.
929 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000930 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000931 // Fold the memcmp and normalize the result. This way we get consistent
932 // results across multiple platforms.
933 uint64_t Ret = 0;
934 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
935 if (Cmp < 0)
936 Ret = -1;
937 else if (Cmp > 0)
938 Ret = 1;
939 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000940 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000941
Chris Bienemanad070d02014-09-17 20:55:46 +0000942 return nullptr;
943}
Meador Inge9a6a1902012-10-31 00:20:56 +0000944
Chris Bienemanad070d02014-09-17 20:55:46 +0000945Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
946 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000947
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000948 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000949 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000950
Chris Bienemanad070d02014-09-17 20:55:46 +0000951 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
952 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000953 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000954 return CI->getArgOperand(0);
955}
Meador Inge05a625a2012-10-31 14:58:26 +0000956
Chris Bienemanad070d02014-09-17 20:55:46 +0000957Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
958 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000959
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000960 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000961 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000962
Chris Bienemanad070d02014-09-17 20:55:46 +0000963 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
964 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000965 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000966 return CI->getArgOperand(0);
967}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000968
Sanjay Patel980b2802016-01-26 16:17:24 +0000969// TODO: Does this belong in BuildLibCalls or should all of those similar
970// functions be moved here?
971static Value *emitCalloc(Value *Num, Value *Size, const AttributeSet &Attrs,
972 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
973 LibFunc::Func Func;
974 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
975 return nullptr;
976
977 Module *M = B.GetInsertBlock()->getModule();
978 const DataLayout &DL = M->getDataLayout();
979 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
980 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
981 PtrType, PtrType, nullptr);
982 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
983
984 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
985 CI->setCallingConv(F->getCallingConv());
986
987 return CI;
988}
989
990/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
991static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
992 const TargetLibraryInfo &TLI) {
993 // This has to be a memset of zeros (bzero).
994 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
995 if (!FillValue || FillValue->getZExtValue() != 0)
996 return nullptr;
997
998 // TODO: We should handle the case where the malloc has more than one use.
999 // This is necessary to optimize common patterns such as when the result of
1000 // the malloc is checked against null or when a memset intrinsic is used in
1001 // place of a memset library call.
1002 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
1003 if (!Malloc || !Malloc->hasOneUse())
1004 return nullptr;
1005
1006 // Is the inner call really malloc()?
1007 Function *InnerCallee = Malloc->getCalledFunction();
1008 LibFunc::Func Func;
1009 if (!TLI.getLibFunc(InnerCallee->getName(), Func) || !TLI.has(Func) ||
1010 Func != LibFunc::malloc)
1011 return nullptr;
1012
1013 // Matching the name is not good enough. Make sure the parameter and return
1014 // type match the standard library signature.
1015 FunctionType *FT = InnerCallee->getFunctionType();
1016 if (FT->getNumParams() != 1 || !FT->getParamType(0)->isIntegerTy())
1017 return nullptr;
1018
1019 auto *RetType = dyn_cast<PointerType>(FT->getReturnType());
1020 if (!RetType || !RetType->getPointerElementType()->isIntegerTy(8))
1021 return nullptr;
1022
1023 // The memset must cover the same number of bytes that are malloc'd.
1024 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
1025 return nullptr;
1026
1027 // Replace the malloc with a calloc. We need the data layout to know what the
1028 // actual size of a 'size_t' parameter is.
1029 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1030 const DataLayout &DL = Malloc->getModule()->getDataLayout();
1031 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
1032 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1033 Malloc->getArgOperand(0), Malloc->getAttributes(),
1034 B, TLI);
1035 if (!Calloc)
1036 return nullptr;
1037
1038 Malloc->replaceAllUsesWith(Calloc);
1039 Malloc->eraseFromParent();
1040
1041 return Calloc;
1042}
1043
Chris Bienemanad070d02014-09-17 20:55:46 +00001044Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1045 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +00001046
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001047 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +00001048 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +00001049
Sanjay Patel980b2802016-01-26 16:17:24 +00001050 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
1051 return Calloc;
1052
Chris Bienemanad070d02014-09-17 20:55:46 +00001053 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1054 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1055 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1056 return CI->getArgOperand(0);
1057}
Meador Inged4825782012-11-11 06:49:03 +00001058
Meador Inge193e0352012-11-13 04:16:17 +00001059//===----------------------------------------------------------------------===//
1060// Math Library Optimizations
1061//===----------------------------------------------------------------------===//
1062
Matthias Braund34e4d22014-12-03 21:46:33 +00001063/// Return a variant of Val with float type.
1064/// Currently this works in two cases: If Val is an FPExtension of a float
1065/// value to something bigger, simply return the operand.
1066/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1067/// loss of precision do so.
1068static Value *valueHasFloatPrecision(Value *Val) {
1069 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1070 Value *Op = Cast->getOperand(0);
1071 if (Op->getType()->isFloatTy())
1072 return Op;
1073 }
1074 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1075 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001076 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +00001077 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001078 &losesInfo);
1079 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001080 return ConstantFP::get(Const->getContext(), F);
1081 }
1082 return nullptr;
1083}
1084
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001085/// Any floating-point library function that we're trying to simplify will have
1086/// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
1087/// CheckDoubleTy indicates that 'fptype' must be 'double'.
1088static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
1089 bool CheckDoubleTy) {
1090 FunctionType *FT = F->getFunctionType();
1091 if (FT->getNumParams() != NumParams)
1092 return false;
1093
1094 // The return type must match what we're looking for.
1095 Type *RetTy = FT->getReturnType();
1096 if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
1097 return false;
1098
1099 // Each parameter must match the return type, and therefore, match every other
1100 // parameter too.
1101 for (const Type *ParamTy : FT->params())
1102 if (ParamTy != RetTy)
1103 return false;
1104
1105 return true;
1106}
1107
Sanjay Patel4e971da2016-01-21 18:01:57 +00001108/// Shrink double -> float for unary functions like 'floor'.
1109static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1110 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001111 Function *Callee = CI->getCalledFunction();
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001112 if (!matchesFPLibFunctionSignature(Callee, 1, true))
Chris Bienemanad070d02014-09-17 20:55:46 +00001113 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001114
Chris Bienemanad070d02014-09-17 20:55:46 +00001115 if (CheckRetType) {
1116 // Check if all the uses for function like 'sin' are converted to float.
1117 for (User *U : CI->users()) {
1118 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1119 if (!Cast || !Cast->getType()->isFloatTy())
1120 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001121 }
Meador Inge193e0352012-11-13 04:16:17 +00001122 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001123
1124 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +00001125 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1126 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +00001127 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +00001128
1129 // Propagate fast-math flags from the existing call to the new call.
1130 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001131 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001132
1133 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001134 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001135 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001136 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001137 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1138 V = B.CreateCall(F, V);
1139 } else {
1140 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001141 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +00001142 }
1143
Chris Bienemanad070d02014-09-17 20:55:46 +00001144 return B.CreateFPExt(V, B.getDoubleTy());
1145}
Meador Inge193e0352012-11-13 04:16:17 +00001146
Sanjay Patel4e971da2016-01-21 18:01:57 +00001147/// Shrink double -> float for binary functions like 'fmin/fmax'.
1148static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001149 Function *Callee = CI->getCalledFunction();
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001150 if (!matchesFPLibFunctionSignature(Callee, 2, true))
Craig Topperf40110f2014-04-25 05:29:35 +00001151 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001152
Chris Bienemanad070d02014-09-17 20:55:46 +00001153 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001154 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1155 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1156 if (V1 == nullptr)
1157 return nullptr;
1158 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1159 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001160 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001161
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001162 // Propagate fast-math flags from the existing call to the new call.
1163 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001164 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001165
Chris Bienemanad070d02014-09-17 20:55:46 +00001166 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001167 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001168 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001169 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001170 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001171 return B.CreateFPExt(V, B.getDoubleTy());
1172}
1173
1174Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1175 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001176 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1177 return nullptr;
1178
Chris Bienemanad070d02014-09-17 20:55:46 +00001179 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001180 StringRef Name = Callee->getName();
1181 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001182 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001183
Chris Bienemanad070d02014-09-17 20:55:46 +00001184 // cos(-x) -> cos(x)
1185 Value *Op1 = CI->getArgOperand(0);
1186 if (BinaryOperator::isFNeg(Op1)) {
1187 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1188 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1189 }
1190 return Ret;
1191}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001192
Weiming Zhao82130722015-12-04 22:00:47 +00001193static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1194 // Multiplications calculated using Addition Chains.
1195 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1196
1197 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1198
1199 if (InnerChain[Exp])
1200 return InnerChain[Exp];
1201
1202 static const unsigned AddChain[33][2] = {
1203 {0, 0}, // Unused.
1204 {0, 0}, // Unused (base case = pow1).
1205 {1, 1}, // Unused (pre-computed).
1206 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1207 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1208 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1209 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1210 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1211 };
1212
1213 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1214 getPow(InnerChain, AddChain[Exp][1], B));
1215 return InnerChain[Exp];
1216}
1217
Chris Bienemanad070d02014-09-17 20:55:46 +00001218Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1219 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001220 if (!matchesFPLibFunctionSignature(Callee, 2, false))
1221 return nullptr;
1222
Chris Bienemanad070d02014-09-17 20:55:46 +00001223 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001224 StringRef Name = Callee->getName();
1225 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001226 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001227
Chris Bienemanad070d02014-09-17 20:55:46 +00001228 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1229 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1230 // pow(1.0, x) -> 1.0
1231 if (Op1C->isExactlyValue(1.0))
1232 return Op1C;
1233 // pow(2.0, x) -> exp2(x)
1234 if (Op1C->isExactlyValue(2.0) &&
1235 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1236 LibFunc::exp2l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001237 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
Davide Italianod9f87b42015-11-06 21:05:07 +00001238 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001239 // pow(10.0, x) -> exp10(x)
1240 if (Op1C->isExactlyValue(10.0) &&
1241 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1242 LibFunc::exp10l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001243 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001244 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001245 }
1246
Sanjay Patel6002e782016-01-12 17:30:37 +00001247 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001248 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001249 // We enable these only with fast-math. Besides rounding differences, the
1250 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001251 // Example: x = 1000, y = 0.001.
1252 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001253 auto *OpC = dyn_cast<CallInst>(Op1);
1254 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1255 LibFunc::Func Func;
1256 Function *OpCCallee = OpC->getCalledFunction();
1257 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1258 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001259 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001260 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001261 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001262 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001263 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001264 }
1265 }
1266
Chris Bienemanad070d02014-09-17 20:55:46 +00001267 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1268 if (!Op2C)
1269 return Ret;
1270
1271 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1272 return ConstantFP::get(CI->getType(), 1.0);
1273
1274 if (Op2C->isExactlyValue(0.5) &&
1275 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1276 LibFunc::sqrtl) &&
1277 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1278 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001279
1280 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001281 if (CI->hasUnsafeAlgebra()) {
1282 IRBuilder<>::FastMathFlagGuard Guard(B);
1283 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Pateld3112a52016-01-19 19:46:10 +00001284 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
Davide Italianoc5cedd12015-11-18 23:21:32 +00001285 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001286 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001287
Chris Bienemanad070d02014-09-17 20:55:46 +00001288 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1289 // This is faster than calling pow, and still handles negative zero
1290 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001291 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1292 Value *Inf = ConstantFP::getInfinity(CI->getType());
1293 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Sanjay Pateld3112a52016-01-19 19:46:10 +00001294 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001295 Value *FAbs =
Sanjay Pateld3112a52016-01-19 19:46:10 +00001296 emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001297 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1298 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1299 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001300 }
1301
Chris Bienemanad070d02014-09-17 20:55:46 +00001302 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1303 return Op1;
1304 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1305 return B.CreateFMul(Op1, Op1, "pow2");
1306 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1307 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001308
1309 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001310 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001311 APFloat V = abs(Op2C->getValueAPF());
1312 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1313 // This transformation applies to integer exponents only.
1314 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1315 !V.isInteger())
1316 return nullptr;
1317
1318 // We will memoize intermediate products of the Addition Chain.
1319 Value *InnerChain[33] = {nullptr};
1320 InnerChain[1] = Op1;
1321 InnerChain[2] = B.CreateFMul(Op1, Op1);
1322
1323 // We cannot readily convert a non-double type (like float) to a double.
1324 // So we first convert V to something which could be converted to double.
1325 bool ignored;
1326 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001327
1328 // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
Weiming Zhao82130722015-12-04 22:00:47 +00001329 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1330 // For negative exponents simply compute the reciprocal.
1331 if (Op2C->isNegative())
1332 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1333 return FMul;
1334 }
1335
Chris Bienemanad070d02014-09-17 20:55:46 +00001336 return nullptr;
1337}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001338
Chris Bienemanad070d02014-09-17 20:55:46 +00001339Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1340 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001341 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1342 return nullptr;
1343
Chris Bienemanad070d02014-09-17 20:55:46 +00001344 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001345 StringRef Name = Callee->getName();
1346 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001347 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001348
Chris Bienemanad070d02014-09-17 20:55:46 +00001349 Value *Op = CI->getArgOperand(0);
1350 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1351 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1352 LibFunc::Func LdExp = LibFunc::ldexpl;
1353 if (Op->getType()->isFloatTy())
1354 LdExp = LibFunc::ldexpf;
1355 else if (Op->getType()->isDoubleTy())
1356 LdExp = LibFunc::ldexp;
1357
1358 if (TLI->has(LdExp)) {
1359 Value *LdExpArg = nullptr;
1360 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1361 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1362 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1363 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1364 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1365 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1366 }
1367
1368 if (LdExpArg) {
1369 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1370 if (!Op->getType()->isFloatTy())
1371 One = ConstantExpr::getFPExtend(One, Op->getType());
1372
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001373 Module *M = CI->getModule();
Sanjay Patel042aed902016-01-21 22:41:16 +00001374 Value *NewCallee =
Chris Bienemanad070d02014-09-17 20:55:46 +00001375 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001376 Op->getType(), B.getInt32Ty(), nullptr);
Sanjay Patel042aed902016-01-21 22:41:16 +00001377 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001378 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1379 CI->setCallingConv(F->getCallingConv());
1380
1381 return CI;
1382 }
1383 }
1384 return Ret;
1385}
1386
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001387Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1388 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001389 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1390 return nullptr;
1391
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001392 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001393 StringRef Name = Callee->getName();
1394 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001395 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001396
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001397 Value *Op = CI->getArgOperand(0);
1398 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1399 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1400 if (I->getOpcode() == Instruction::FMul)
1401 if (I->getOperand(0) == I->getOperand(1))
1402 return Op;
1403 }
1404 return Ret;
1405}
1406
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001407Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001408 Function *Callee = CI->getCalledFunction();
1409 if (!matchesFPLibFunctionSignature(Callee, 2, false))
1410 return nullptr;
1411
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001412 // If we can shrink the call to a float function rather than a double
1413 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001414 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001415 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1416 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001417 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001418
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001419 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001420 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001421 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001422 // Unsafe algebra sets all fast-math-flags to true.
1423 FMF.setUnsafeAlgebra();
1424 } else {
1425 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001426 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001427 return nullptr;
1428 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1429 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001430 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001431 // might be impractical."
1432 FMF.setNoSignedZeros();
1433 FMF.setNoNaNs();
1434 }
Sanjay Patela2528152016-01-12 18:03:37 +00001435 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001436
1437 // We have a relaxed floating-point environment. We can ignore NaN-handling
1438 // and transform to a compare and select. We do not have to consider errno or
1439 // exceptions, because fmin/fmax do not have those.
1440 Value *Op0 = CI->getArgOperand(0);
1441 Value *Op1 = CI->getArgOperand(1);
1442 Value *Cmp = Callee->getName().startswith("fmin") ?
1443 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1444 return B.CreateSelect(Cmp, Op0, Op1);
1445}
1446
Davide Italianob8b71332015-11-29 20:58:04 +00001447Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1448 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001449 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1450 return nullptr;
1451
Davide Italianob8b71332015-11-29 20:58:04 +00001452 Value *Ret = nullptr;
1453 StringRef Name = Callee->getName();
1454 if (UnsafeFPShrink && hasFloatVersion(Name))
1455 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001456
Sanjay Patele896ede2016-01-11 23:31:48 +00001457 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001458 return Ret;
1459 Value *Op1 = CI->getArgOperand(0);
1460 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001461
1462 // The earlier call must also be unsafe in order to do these transforms.
1463 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001464 return Ret;
1465
1466 // log(pow(x,y)) -> y*log(x)
1467 // This is only applicable to log, log2, log10.
1468 if (Name != "log" && Name != "log2" && Name != "log10")
1469 return Ret;
1470
1471 IRBuilder<>::FastMathFlagGuard Guard(B);
1472 FastMathFlags FMF;
1473 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001474 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001475
1476 LibFunc::Func Func;
1477 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001478 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1479 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001480 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001481 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001482 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001483
1484 // log(exp2(y)) -> y*log(2)
1485 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1486 TLI->has(Func) && Func == LibFunc::exp2)
1487 return B.CreateFMul(
1488 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001489 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001490 Callee->getName(), B, Callee->getAttributes()),
1491 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001492 return Ret;
1493}
1494
Sanjay Patelc699a612014-10-16 18:48:17 +00001495Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1496 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001497 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1498 return nullptr;
Sanjay Patelbd2dc672016-01-20 17:41:14 +00001499
Sanjay Patelc699a612014-10-16 18:48:17 +00001500 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001501 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1502 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001503 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001504
1505 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001506 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001507
Sanjay Patelc2d64612016-01-06 20:52:21 +00001508 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1509 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1510 return Ret;
1511
1512 // We're looking for a repeated factor in a multiplication tree,
1513 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001514 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001515 Value *Op0 = I->getOperand(0);
1516 Value *Op1 = I->getOperand(1);
1517 Value *RepeatOp = nullptr;
1518 Value *OtherOp = nullptr;
1519 if (Op0 == Op1) {
1520 // Simple match: the operands of the multiply are identical.
1521 RepeatOp = Op0;
1522 } else {
1523 // Look for a more complicated pattern: one of the operands is itself
1524 // a multiply, so search for a common factor in that multiply.
1525 // Note: We don't bother looking any deeper than this first level or for
1526 // variations of this pattern because instcombine's visitFMUL and/or the
1527 // reassociation pass should give us this form.
1528 Value *OtherMul0, *OtherMul1;
1529 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1530 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001531 if (OtherMul0 == OtherMul1 &&
1532 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001533 // Matched: sqrt((x * x) * z)
1534 RepeatOp = OtherMul0;
1535 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001536 }
1537 }
1538 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001539 if (!RepeatOp)
1540 return Ret;
1541
1542 // Fast math flags for any created instructions should match the sqrt
1543 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001544 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001545 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001546
Sanjay Patelc2d64612016-01-06 20:52:21 +00001547 // If we found a repeated factor, hoist it out of the square root and
1548 // replace it with the fabs of that factor.
1549 Module *M = Callee->getParent();
1550 Type *ArgType = I->getType();
1551 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1552 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1553 if (OtherOp) {
1554 // If we found a non-repeated factor, we still need to get its square
1555 // root. We then multiply that by the value that was simplified out
1556 // of the square root calculation.
1557 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1558 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1559 return B.CreateFMul(FabsCall, SqrtCall);
1560 }
1561 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001562}
1563
Sanjay Patelcddcd722016-01-06 19:23:35 +00001564// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001565Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1566 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001567 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1568 return nullptr;
1569
Davide Italiano51507d22015-11-04 23:36:56 +00001570 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001571 StringRef Name = Callee->getName();
1572 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001573 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001574
Davide Italiano51507d22015-11-04 23:36:56 +00001575 Value *Op1 = CI->getArgOperand(0);
1576 auto *OpC = dyn_cast<CallInst>(Op1);
1577 if (!OpC)
1578 return Ret;
1579
Sanjay Patelcddcd722016-01-06 19:23:35 +00001580 // Both calls must allow unsafe optimizations in order to remove them.
1581 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1582 return Ret;
1583
Davide Italiano51507d22015-11-04 23:36:56 +00001584 // tan(atan(x)) -> x
1585 // tanf(atanf(x)) -> x
1586 // tanl(atanl(x)) -> x
1587 LibFunc::Func Func;
1588 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001589 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001590 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1591 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1592 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1593 Ret = OpC->getArgOperand(0);
1594 return Ret;
1595}
1596
Sanjay Patel57747212016-01-21 23:38:43 +00001597static bool isTrigLibCall(CallInst *CI) {
1598 Function *Callee = CI->getCalledFunction();
1599 FunctionType *FT = Callee->getFunctionType();
1600
1601 // We can only hope to do anything useful if we can ignore things like errno
1602 // and floating-point exceptions.
1603 bool AttributesSafe =
1604 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1605
1606 // Other than that we need float(float) or double(double)
1607 return AttributesSafe && FT->getNumParams() == 1 &&
1608 FT->getReturnType() == FT->getParamType(0) &&
1609 (FT->getParamType(0)->isFloatTy() ||
1610 FT->getParamType(0)->isDoubleTy());
1611}
1612
Chris Bienemanad070d02014-09-17 20:55:46 +00001613static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1614 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001615 Value *&SinCos) {
1616 Type *ArgTy = Arg->getType();
1617 Type *ResTy;
1618 StringRef Name;
1619
1620 Triple T(OrigCallee->getParent()->getTargetTriple());
1621 if (UseFloat) {
1622 Name = "__sincospif_stret";
1623
1624 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1625 // x86_64 can't use {float, float} since that would be returned in both
1626 // xmm0 and xmm1, which isn't what a real struct would do.
1627 ResTy = T.getArch() == Triple::x86_64
1628 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1629 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1630 } else {
1631 Name = "__sincospi_stret";
1632 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1633 }
1634
1635 Module *M = OrigCallee->getParent();
1636 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1637 ResTy, ArgTy, nullptr);
1638
1639 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1640 // If the argument is an instruction, it must dominate all uses so put our
1641 // sincos call there.
1642 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1643 } else {
1644 // Otherwise (e.g. for a constant) the beginning of the function is as
1645 // good a place as any.
1646 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1647 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1648 }
1649
1650 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1651
1652 if (SinCos->getType()->isStructTy()) {
1653 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1654 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1655 } else {
1656 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1657 "sinpi");
1658 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1659 "cospi");
1660 }
1661}
Chris Bienemanad070d02014-09-17 20:55:46 +00001662
1663Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 // Make sure the prototype is as expected, otherwise the rest of the
1665 // function is probably invalid and likely to abort.
1666 if (!isTrigLibCall(CI))
1667 return nullptr;
1668
1669 Value *Arg = CI->getArgOperand(0);
1670 SmallVector<CallInst *, 1> SinCalls;
1671 SmallVector<CallInst *, 1> CosCalls;
1672 SmallVector<CallInst *, 1> SinCosCalls;
1673
1674 bool IsFloat = Arg->getType()->isFloatTy();
1675
1676 // Look for all compatible sinpi, cospi and sincospi calls with the same
1677 // argument. If there are enough (in some sense) we can make the
1678 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001679 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001680 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001681 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001682
1683 // It's only worthwhile if both sinpi and cospi are actually used.
1684 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1685 return nullptr;
1686
1687 Value *Sin, *Cos, *SinCos;
1688 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1689
1690 replaceTrigInsts(SinCalls, Sin);
1691 replaceTrigInsts(CosCalls, Cos);
1692 replaceTrigInsts(SinCosCalls, SinCos);
1693
1694 return nullptr;
1695}
1696
David Majnemerabae6b52016-03-19 04:53:02 +00001697void LibCallSimplifier::classifyArgUse(
1698 Value *Val, Function *F, bool IsFloat,
1699 SmallVectorImpl<CallInst *> &SinCalls,
1700 SmallVectorImpl<CallInst *> &CosCalls,
1701 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 CallInst *CI = dyn_cast<CallInst>(Val);
1703
1704 if (!CI)
1705 return;
1706
David Majnemerabae6b52016-03-19 04:53:02 +00001707 // Don't consider calls in other functions.
1708 if (CI->getFunction() != F)
1709 return;
1710
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001712 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001713 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1714 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001715 return;
1716
1717 if (IsFloat) {
1718 if (Func == LibFunc::sinpif)
1719 SinCalls.push_back(CI);
1720 else if (Func == LibFunc::cospif)
1721 CosCalls.push_back(CI);
1722 else if (Func == LibFunc::sincospif_stret)
1723 SinCosCalls.push_back(CI);
1724 } else {
1725 if (Func == LibFunc::sinpi)
1726 SinCalls.push_back(CI);
1727 else if (Func == LibFunc::cospi)
1728 CosCalls.push_back(CI);
1729 else if (Func == LibFunc::sincospi_stret)
1730 SinCosCalls.push_back(CI);
1731 }
1732}
1733
1734void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1735 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001736 for (CallInst *C : Calls)
1737 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001738}
1739
Meador Inge7415f842012-11-25 20:45:27 +00001740//===----------------------------------------------------------------------===//
1741// Integer Library Call Optimizations
1742//===----------------------------------------------------------------------===//
1743
Davide Italiano396f3ee2015-10-31 23:17:45 +00001744static bool checkIntUnaryReturnAndParam(Function *Callee) {
1745 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001746 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1747 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001748}
1749
Chris Bienemanad070d02014-09-17 20:55:46 +00001750Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1751 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001752 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001753 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001754 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001755
Chris Bienemanad070d02014-09-17 20:55:46 +00001756 // Constant fold.
1757 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1758 if (CI->isZero()) // ffs(0) -> 0.
1759 return B.getInt32(0);
1760 // ffs(c) -> cttz(c)+1
1761 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001762 }
Meador Inge7415f842012-11-25 20:45:27 +00001763
Chris Bienemanad070d02014-09-17 20:55:46 +00001764 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1765 Type *ArgType = Op->getType();
1766 Value *F =
1767 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001768 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1770 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001771
Chris Bienemanad070d02014-09-17 20:55:46 +00001772 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1773 return B.CreateSelect(Cond, V, B.getInt32(0));
1774}
Meador Ingea0b6d872012-11-26 00:24:07 +00001775
Chris Bienemanad070d02014-09-17 20:55:46 +00001776Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1777 Function *Callee = CI->getCalledFunction();
1778 FunctionType *FT = Callee->getFunctionType();
1779 // We require integer(integer) where the types agree.
1780 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1781 FT->getParamType(0) != FT->getReturnType())
1782 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001783
Chris Bienemanad070d02014-09-17 20:55:46 +00001784 // abs(x) -> x >s -1 ? x : -x
1785 Value *Op = CI->getArgOperand(0);
1786 Value *Pos =
1787 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1788 Value *Neg = B.CreateNeg(Op, "neg");
1789 return B.CreateSelect(Pos, Op, Neg);
1790}
Meador Inge9a59ab62012-11-26 02:31:59 +00001791
Chris Bienemanad070d02014-09-17 20:55:46 +00001792Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001793 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001794 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001795
Chris Bienemanad070d02014-09-17 20:55:46 +00001796 // isdigit(c) -> (c-'0') <u 10
1797 Value *Op = CI->getArgOperand(0);
1798 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1799 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1800 return B.CreateZExt(Op, CI->getType());
1801}
Meador Ingea62a39e2012-11-26 03:10:07 +00001802
Chris Bienemanad070d02014-09-17 20:55:46 +00001803Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001804 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001805 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001806
Chris Bienemanad070d02014-09-17 20:55:46 +00001807 // isascii(c) -> c <u 128
1808 Value *Op = CI->getArgOperand(0);
1809 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1810 return B.CreateZExt(Op, CI->getType());
1811}
1812
1813Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001814 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001815 return nullptr;
1816
1817 // toascii(c) -> c & 0x7f
1818 return B.CreateAnd(CI->getArgOperand(0),
1819 ConstantInt::get(CI->getType(), 0x7F));
1820}
Meador Inge604937d2012-11-26 03:38:52 +00001821
Meador Inge08ca1152012-11-26 20:37:20 +00001822//===----------------------------------------------------------------------===//
1823// Formatting and IO Library Call Optimizations
1824//===----------------------------------------------------------------------===//
1825
Chris Bienemanad070d02014-09-17 20:55:46 +00001826static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001827
Chris Bienemanad070d02014-09-17 20:55:46 +00001828Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1829 int StreamArg) {
1830 // Error reporting calls should be cold, mark them as such.
1831 // This applies even to non-builtin calls: it is only a hint and applies to
1832 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001833
Chris Bienemanad070d02014-09-17 20:55:46 +00001834 // This heuristic was suggested in:
1835 // Improving Static Branch Prediction in a Compiler
1836 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1837 // Proceedings of PACT'98, Oct. 1998, IEEE
1838 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001839
Chris Bienemanad070d02014-09-17 20:55:46 +00001840 if (!CI->hasFnAttr(Attribute::Cold) &&
1841 isReportingError(Callee, CI, StreamArg)) {
1842 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1843 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001844
Chris Bienemanad070d02014-09-17 20:55:46 +00001845 return nullptr;
1846}
1847
1848static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001849 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 return false;
1851
1852 if (StreamArg < 0)
1853 return true;
1854
1855 // These functions might be considered cold, but only if their stream
1856 // argument is stderr.
1857
1858 if (StreamArg >= (int)CI->getNumArgOperands())
1859 return false;
1860 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1861 if (!LI)
1862 return false;
1863 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1864 if (!GV || !GV->isDeclaration())
1865 return false;
1866 return GV->getName() == "stderr";
1867}
1868
1869Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1870 // Check for a fixed format string.
1871 StringRef FormatStr;
1872 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001873 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001874
Chris Bienemanad070d02014-09-17 20:55:46 +00001875 // Empty format string -> noop.
1876 if (FormatStr.empty()) // Tolerate printf's declared void.
1877 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001878
Chris Bienemanad070d02014-09-17 20:55:46 +00001879 // Do not do any of the following transformations if the printf return value
1880 // is used, in general the printf return value is not compatible with either
1881 // putchar() or puts().
1882 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001883 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001884
1885 // printf("x") -> putchar('x'), even for '%'.
Davide Italianod4f5a052016-04-03 01:46:52 +00001886 if (FormatStr.size() == 1)
1887 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001888
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001889 // printf("%s", "a") --> putchar('a')
1890 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1891 StringRef ChrStr;
1892 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1893 return nullptr;
1894 if (ChrStr.size() != 1)
1895 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001896 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001897 }
1898
Chris Bienemanad070d02014-09-17 20:55:46 +00001899 // printf("foo\n") --> puts("foo")
1900 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1901 FormatStr.find('%') == StringRef::npos) { // No format characters.
1902 // Create a string literal with no \n on it. We expect the constant merge
1903 // pass to be run after this pass, to merge duplicate strings.
1904 FormatStr = FormatStr.drop_back();
1905 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001906 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001907 }
Meador Inge08ca1152012-11-26 20:37:20 +00001908
Chris Bienemanad070d02014-09-17 20:55:46 +00001909 // Optimize specific format strings.
1910 // printf("%c", chr) --> putchar(chr)
1911 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001912 CI->getArgOperand(1)->getType()->isIntegerTy())
1913 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001914
1915 // printf("%s\n", str) --> puts(str)
1916 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001917 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001918 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001919 return nullptr;
1920}
1921
1922Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1923
1924 Function *Callee = CI->getCalledFunction();
1925 // Require one fixed pointer argument and an integer/void result.
1926 FunctionType *FT = Callee->getFunctionType();
1927 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1928 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1929 return nullptr;
1930
1931 if (Value *V = optimizePrintFString(CI, B)) {
1932 return V;
1933 }
1934
1935 // printf(format, ...) -> iprintf(format, ...) if no floating point
1936 // arguments.
1937 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1938 Module *M = B.GetInsertBlock()->getParent()->getParent();
1939 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001940 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001941 CallInst *New = cast<CallInst>(CI->clone());
1942 New->setCalledFunction(IPrintFFn);
1943 B.Insert(New);
1944 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001945 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001946 return nullptr;
1947}
Meador Inge08ca1152012-11-26 20:37:20 +00001948
Chris Bienemanad070d02014-09-17 20:55:46 +00001949Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1950 // Check for a fixed format string.
1951 StringRef FormatStr;
1952 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001953 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001954
Chris Bienemanad070d02014-09-17 20:55:46 +00001955 // If we just have a format string (nothing else crazy) transform it.
1956 if (CI->getNumArgOperands() == 2) {
1957 // Make sure there's no % in the constant array. We could try to handle
1958 // %% -> % in the future if we cared.
1959 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1960 if (FormatStr[i] == '%')
1961 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001962
Chris Bienemanad070d02014-09-17 20:55:46 +00001963 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001964 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1965 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1966 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001967 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001968 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001969 }
Meador Ingef8e72502012-11-29 15:45:43 +00001970
Chris Bienemanad070d02014-09-17 20:55:46 +00001971 // The remaining optimizations require the format string to be "%s" or "%c"
1972 // and have an extra operand.
1973 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1974 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001975 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001976
Chris Bienemanad070d02014-09-17 20:55:46 +00001977 // Decode the second character of the format string.
1978 if (FormatStr[1] == 'c') {
1979 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1980 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1981 return nullptr;
1982 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001983 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001984 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001985 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001986 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001987
Chris Bienemanad070d02014-09-17 20:55:46 +00001988 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001989 }
1990
Chris Bienemanad070d02014-09-17 20:55:46 +00001991 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001992 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1993 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1994 return nullptr;
1995
Sanjay Pateld3112a52016-01-19 19:46:10 +00001996 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001997 if (!Len)
1998 return nullptr;
1999 Value *IncLen =
2000 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002001 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002002
2003 // The sprintf result is the unincremented number of bytes in the string.
2004 return B.CreateIntCast(Len, CI->getType(), false);
2005 }
2006 return nullptr;
2007}
2008
2009Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2010 Function *Callee = CI->getCalledFunction();
2011 // Require two fixed pointer arguments and an integer result.
2012 FunctionType *FT = Callee->getFunctionType();
2013 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2014 !FT->getParamType(1)->isPointerTy() ||
2015 !FT->getReturnType()->isIntegerTy())
2016 return nullptr;
2017
2018 if (Value *V = optimizeSPrintFString(CI, B)) {
2019 return V;
2020 }
2021
2022 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2023 // point arguments.
2024 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
2025 Module *M = B.GetInsertBlock()->getParent()->getParent();
2026 Constant *SIPrintFFn =
2027 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2028 CallInst *New = cast<CallInst>(CI->clone());
2029 New->setCalledFunction(SIPrintFFn);
2030 B.Insert(New);
2031 return New;
2032 }
2033 return nullptr;
2034}
2035
2036Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2037 optimizeErrorReporting(CI, B, 0);
2038
2039 // All the optimizations depend on the format string.
2040 StringRef FormatStr;
2041 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2042 return nullptr;
2043
2044 // Do not do any of the following transformations if the fprintf return
2045 // value is used, in general the fprintf return value is not compatible
2046 // with fwrite(), fputc() or fputs().
2047 if (!CI->use_empty())
2048 return nullptr;
2049
2050 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2051 if (CI->getNumArgOperands() == 2) {
2052 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
2053 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
2054 return nullptr; // We found a format specifier.
2055
Sanjay Pateld3112a52016-01-19 19:46:10 +00002056 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002057 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002058 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002059 CI->getArgOperand(0), B, DL, TLI);
2060 }
2061
2062 // The remaining optimizations require the format string to be "%s" or "%c"
2063 // and have an extra operand.
2064 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2065 CI->getNumArgOperands() < 3)
2066 return nullptr;
2067
2068 // Decode the second character of the format string.
2069 if (FormatStr[1] == 'c') {
2070 // fprintf(F, "%c", chr) --> fputc(chr, F)
2071 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2072 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002073 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002074 }
2075
2076 if (FormatStr[1] == 's') {
2077 // fprintf(F, "%s", str) --> fputs(str, F)
2078 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2079 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002080 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002081 }
2082 return nullptr;
2083}
2084
2085Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2086 Function *Callee = CI->getCalledFunction();
2087 // Require two fixed paramters as pointers and integer result.
2088 FunctionType *FT = Callee->getFunctionType();
2089 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2090 !FT->getParamType(1)->isPointerTy() ||
2091 !FT->getReturnType()->isIntegerTy())
2092 return nullptr;
2093
2094 if (Value *V = optimizeFPrintFString(CI, B)) {
2095 return V;
2096 }
2097
2098 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2099 // floating point arguments.
2100 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2101 Module *M = B.GetInsertBlock()->getParent()->getParent();
2102 Constant *FIPrintFFn =
2103 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2104 CallInst *New = cast<CallInst>(CI->clone());
2105 New->setCalledFunction(FIPrintFFn);
2106 B.Insert(New);
2107 return New;
2108 }
2109 return nullptr;
2110}
2111
2112Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2113 optimizeErrorReporting(CI, B, 3);
2114
2115 Function *Callee = CI->getCalledFunction();
2116 // Require a pointer, an integer, an integer, a pointer, returning integer.
2117 FunctionType *FT = Callee->getFunctionType();
2118 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2119 !FT->getParamType(1)->isIntegerTy() ||
2120 !FT->getParamType(2)->isIntegerTy() ||
2121 !FT->getParamType(3)->isPointerTy() ||
2122 !FT->getReturnType()->isIntegerTy())
2123 return nullptr;
2124
2125 // Get the element size and count.
2126 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2127 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2128 if (!SizeC || !CountC)
2129 return nullptr;
2130 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2131
2132 // If this is writing zero records, remove the call (it's a noop).
2133 if (Bytes == 0)
2134 return ConstantInt::get(CI->getType(), 0);
2135
2136 // If this is writing one byte, turn it into fputc.
2137 // This optimisation is only valid, if the return value is unused.
2138 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00002139 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2140 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002141 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2142 }
2143
2144 return nullptr;
2145}
2146
2147Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2148 optimizeErrorReporting(CI, B, 1);
2149
2150 Function *Callee = CI->getCalledFunction();
2151
Chris Bienemanad070d02014-09-17 20:55:46 +00002152 // Require two pointers. Also, we can't optimize if return value is used.
2153 FunctionType *FT = Callee->getFunctionType();
2154 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2155 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2156 return nullptr;
2157
2158 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2159 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2160 if (!Len)
2161 return nullptr;
2162
2163 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002164 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002165 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002166 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002167 CI->getArgOperand(1), B, DL, TLI);
2168}
2169
2170Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2171 Function *Callee = CI->getCalledFunction();
2172 // Require one fixed pointer argument and an integer/void result.
2173 FunctionType *FT = Callee->getFunctionType();
2174 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2175 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2176 return nullptr;
2177
2178 // Check for a constant string.
2179 StringRef Str;
2180 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2181 return nullptr;
2182
2183 if (Str.empty() && CI->use_empty()) {
2184 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002185 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002186 if (CI->use_empty() || !Res)
2187 return Res;
2188 return B.CreateIntCast(Res, CI->getType(), true);
2189 }
2190
2191 return nullptr;
2192}
2193
2194bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002195 LibFunc::Func Func;
2196 SmallString<20> FloatFuncName = FuncName;
2197 FloatFuncName += 'f';
2198 if (TLI->getLibFunc(FloatFuncName, Func))
2199 return TLI->has(Func);
2200 return false;
2201}
Meador Inge7fb2f732012-10-13 16:45:32 +00002202
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002203Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2204 IRBuilder<> &Builder) {
2205 LibFunc::Func Func;
2206 Function *Callee = CI->getCalledFunction();
2207 StringRef FuncName = Callee->getName();
2208
2209 // Check for string/memory library functions.
2210 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2211 // Make sure we never change the calling convention.
2212 assert((ignoreCallingConv(Func) ||
2213 CI->getCallingConv() == llvm::CallingConv::C) &&
2214 "Optimizing string/memory libcall would change the calling convention");
2215 switch (Func) {
2216 case LibFunc::strcat:
2217 return optimizeStrCat(CI, Builder);
2218 case LibFunc::strncat:
2219 return optimizeStrNCat(CI, Builder);
2220 case LibFunc::strchr:
2221 return optimizeStrChr(CI, Builder);
2222 case LibFunc::strrchr:
2223 return optimizeStrRChr(CI, Builder);
2224 case LibFunc::strcmp:
2225 return optimizeStrCmp(CI, Builder);
2226 case LibFunc::strncmp:
2227 return optimizeStrNCmp(CI, Builder);
2228 case LibFunc::strcpy:
2229 return optimizeStrCpy(CI, Builder);
2230 case LibFunc::stpcpy:
2231 return optimizeStpCpy(CI, Builder);
2232 case LibFunc::strncpy:
2233 return optimizeStrNCpy(CI, Builder);
2234 case LibFunc::strlen:
2235 return optimizeStrLen(CI, Builder);
2236 case LibFunc::strpbrk:
2237 return optimizeStrPBrk(CI, Builder);
2238 case LibFunc::strtol:
2239 case LibFunc::strtod:
2240 case LibFunc::strtof:
2241 case LibFunc::strtoul:
2242 case LibFunc::strtoll:
2243 case LibFunc::strtold:
2244 case LibFunc::strtoull:
2245 return optimizeStrTo(CI, Builder);
2246 case LibFunc::strspn:
2247 return optimizeStrSpn(CI, Builder);
2248 case LibFunc::strcspn:
2249 return optimizeStrCSpn(CI, Builder);
2250 case LibFunc::strstr:
2251 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002252 case LibFunc::memchr:
2253 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002254 case LibFunc::memcmp:
2255 return optimizeMemCmp(CI, Builder);
2256 case LibFunc::memcpy:
2257 return optimizeMemCpy(CI, Builder);
2258 case LibFunc::memmove:
2259 return optimizeMemMove(CI, Builder);
2260 case LibFunc::memset:
2261 return optimizeMemSet(CI, Builder);
2262 default:
2263 break;
2264 }
2265 }
2266 return nullptr;
2267}
2268
Chris Bienemanad070d02014-09-17 20:55:46 +00002269Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2270 if (CI->isNoBuiltin())
2271 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002272
Meador Inge20255ef2013-03-12 00:08:29 +00002273 LibFunc::Func Func;
2274 Function *Callee = CI->getCalledFunction();
2275 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002276
2277 SmallVector<OperandBundleDef, 2> OpBundles;
2278 CI->getOperandBundlesAsDefs(OpBundles);
2279 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Chris Bienemanad070d02014-09-17 20:55:46 +00002280 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002281
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002282 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002283 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2284 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002285 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002286 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002287
Sanjay Patel848309d2014-10-23 21:52:45 +00002288 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002289 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002290 if (!isCallingConvC)
2291 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002292 switch (II->getIntrinsicID()) {
2293 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002294 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002295 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002296 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002297 case Intrinsic::fabs:
2298 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002299 case Intrinsic::log:
2300 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002301 case Intrinsic::sqrt:
2302 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002303 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002304 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002305 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002306 }
2307 }
2308
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002309 // Also try to simplify calls to fortified library functions.
2310 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2311 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002312 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002313 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2314 // Use an IR Builder from SimplifiedCI if available instead of CI
2315 // to guarantee we reach all uses we might replace later on.
2316 IRBuilder<> TmpBuilder(SimplifiedCI);
2317 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002318 // If we were able to further simplify, remove the now redundant call.
2319 SimplifiedCI->replaceAllUsesWith(V);
2320 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002321 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002322 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002323 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002324 return SimplifiedFortifiedCI;
2325 }
2326
Meador Inge20255ef2013-03-12 00:08:29 +00002327 // Then check for known library functions.
2328 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002329 // We never change the calling convention.
2330 if (!ignoreCallingConv(Func) && !isCallingConvC)
2331 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002332 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2333 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002334 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002335 case LibFunc::cosf:
2336 case LibFunc::cos:
2337 case LibFunc::cosl:
2338 return optimizeCos(CI, Builder);
2339 case LibFunc::sinpif:
2340 case LibFunc::sinpi:
2341 case LibFunc::cospif:
2342 case LibFunc::cospi:
2343 return optimizeSinCosPi(CI, Builder);
2344 case LibFunc::powf:
2345 case LibFunc::pow:
2346 case LibFunc::powl:
2347 return optimizePow(CI, Builder);
2348 case LibFunc::exp2l:
2349 case LibFunc::exp2:
2350 case LibFunc::exp2f:
2351 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002352 case LibFunc::fabsf:
2353 case LibFunc::fabs:
2354 case LibFunc::fabsl:
2355 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002356 case LibFunc::sqrtf:
2357 case LibFunc::sqrt:
2358 case LibFunc::sqrtl:
2359 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002360 case LibFunc::ffs:
2361 case LibFunc::ffsl:
2362 case LibFunc::ffsll:
2363 return optimizeFFS(CI, Builder);
2364 case LibFunc::abs:
2365 case LibFunc::labs:
2366 case LibFunc::llabs:
2367 return optimizeAbs(CI, Builder);
2368 case LibFunc::isdigit:
2369 return optimizeIsDigit(CI, Builder);
2370 case LibFunc::isascii:
2371 return optimizeIsAscii(CI, Builder);
2372 case LibFunc::toascii:
2373 return optimizeToAscii(CI, Builder);
2374 case LibFunc::printf:
2375 return optimizePrintF(CI, Builder);
2376 case LibFunc::sprintf:
2377 return optimizeSPrintF(CI, Builder);
2378 case LibFunc::fprintf:
2379 return optimizeFPrintF(CI, Builder);
2380 case LibFunc::fwrite:
2381 return optimizeFWrite(CI, Builder);
2382 case LibFunc::fputs:
2383 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002384 case LibFunc::log:
2385 case LibFunc::log10:
2386 case LibFunc::log1p:
2387 case LibFunc::log2:
2388 case LibFunc::logb:
2389 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002390 case LibFunc::puts:
2391 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002392 case LibFunc::tan:
2393 case LibFunc::tanf:
2394 case LibFunc::tanl:
2395 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002396 case LibFunc::perror:
2397 return optimizeErrorReporting(CI, Builder);
2398 case LibFunc::vfprintf:
2399 case LibFunc::fiprintf:
2400 return optimizeErrorReporting(CI, Builder, 0);
2401 case LibFunc::fputc:
2402 return optimizeErrorReporting(CI, Builder, 1);
2403 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002404 case LibFunc::floor:
2405 case LibFunc::rint:
2406 case LibFunc::round:
2407 case LibFunc::nearbyint:
2408 case LibFunc::trunc:
2409 if (hasFloatVersion(FuncName))
2410 return optimizeUnaryDoubleFP(CI, Builder, false);
2411 return nullptr;
2412 case LibFunc::acos:
2413 case LibFunc::acosh:
2414 case LibFunc::asin:
2415 case LibFunc::asinh:
2416 case LibFunc::atan:
2417 case LibFunc::atanh:
2418 case LibFunc::cbrt:
2419 case LibFunc::cosh:
2420 case LibFunc::exp:
2421 case LibFunc::exp10:
2422 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002423 case LibFunc::sin:
2424 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002425 case LibFunc::tanh:
2426 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2427 return optimizeUnaryDoubleFP(CI, Builder, true);
2428 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002429 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002430 if (hasFloatVersion(FuncName))
2431 return optimizeBinaryDoubleFP(CI, Builder);
2432 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002433 case LibFunc::fminf:
2434 case LibFunc::fmin:
2435 case LibFunc::fminl:
2436 case LibFunc::fmaxf:
2437 case LibFunc::fmax:
2438 case LibFunc::fmaxl:
2439 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002440 default:
2441 return nullptr;
2442 }
Meador Inge20255ef2013-03-12 00:08:29 +00002443 }
Craig Topperf40110f2014-04-25 05:29:35 +00002444 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002445}
2446
Chandler Carruth92803822015-01-21 02:11:59 +00002447LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002448 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002449 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002450 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002451 Replacer(Replacer) {}
2452
2453void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2454 // Indirect through the replacer used in this instance.
2455 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002456}
2457
Meador Ingedfb08a22013-06-20 19:48:07 +00002458// TODO:
2459// Additional cases that we need to add to this file:
2460//
2461// cbrt:
2462// * cbrt(expN(X)) -> expN(x/3)
2463// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002464// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002465//
2466// exp, expf, expl:
2467// * exp(log(x)) -> x
2468//
2469// log, logf, logl:
2470// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002471// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002472// * log(exp10(y)) -> y*log(10)
2473// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002474//
2475// lround, lroundf, lroundl:
2476// * lround(cnst) -> cnst'
2477//
2478// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002479// * pow(sqrt(x),y) -> pow(x,y*0.5)
2480// * pow(pow(x,y),z)-> pow(x,y*z)
2481//
2482// round, roundf, roundl:
2483// * round(cnst) -> cnst'
2484//
2485// signbit:
2486// * signbit(cnst) -> cnst'
2487// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2488//
2489// sqrt, sqrtf, sqrtl:
2490// * sqrt(expN(x)) -> expN(x*0.5)
2491// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2492// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2493//
Meador Ingedfb08a22013-06-20 19:48:07 +00002494// trunc, truncf, truncl:
2495// * trunc(cnst) -> cnst'
2496//
2497//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002498
2499//===----------------------------------------------------------------------===//
2500// Fortified Library Call Optimizations
2501//===----------------------------------------------------------------------===//
2502
2503bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2504 unsigned ObjSizeOp,
2505 unsigned SizeOp,
2506 bool isString) {
2507 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2508 return true;
2509 if (ConstantInt *ObjSizeCI =
2510 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2511 if (ObjSizeCI->isAllOnesValue())
2512 return true;
2513 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2514 if (OnlyLowerUnknownSize)
2515 return false;
2516 if (isString) {
2517 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2518 // If the length is 0 we don't know how long it is and so we can't
2519 // remove the check.
2520 if (Len == 0)
2521 return false;
2522 return ObjSizeCI->getZExtValue() >= Len;
2523 }
2524 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2525 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2526 }
2527 return false;
2528}
2529
Sanjay Pateld707db92015-12-31 16:10:49 +00002530Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2531 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002532 Function *Callee = CI->getCalledFunction();
2533
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002534 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002535 return nullptr;
2536
2537 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2538 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002539 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002540 return CI->getArgOperand(0);
2541 }
2542 return nullptr;
2543}
2544
Sanjay Pateld707db92015-12-31 16:10:49 +00002545Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2546 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002547 Function *Callee = CI->getCalledFunction();
2548
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002549 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002550 return nullptr;
2551
2552 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2553 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002554 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002555 return CI->getArgOperand(0);
2556 }
2557 return nullptr;
2558}
2559
Sanjay Pateld707db92015-12-31 16:10:49 +00002560Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2561 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002562 Function *Callee = CI->getCalledFunction();
2563
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002564 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002565 return nullptr;
2566
Sanjay Patel980b2802016-01-26 16:17:24 +00002567 // TODO: Try foldMallocMemset() here.
2568
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002569 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2570 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2571 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2572 return CI->getArgOperand(0);
2573 }
2574 return nullptr;
2575}
2576
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002577Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2578 IRBuilder<> &B,
2579 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002580 Function *Callee = CI->getCalledFunction();
2581 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002582 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002583
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002584 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002585 return nullptr;
2586
2587 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2588 *ObjSize = CI->getArgOperand(2);
2589
2590 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002591 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002592 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002593 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002594 }
2595
2596 // If a) we don't have any length information, or b) we know this will
2597 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2598 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2599 // TODO: It might be nice to get a maximum length out of the possible
2600 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002601 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002602 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002603
David Blaikie65fab6d2015-04-03 21:32:06 +00002604 if (OnlyLowerUnknownSize)
2605 return nullptr;
2606
2607 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2608 uint64_t Len = GetStringLength(Src);
2609 if (Len == 0)
2610 return nullptr;
2611
2612 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2613 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002614 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002615 // If the function was an __stpcpy_chk, and we were able to fold it into
2616 // a __memcpy_chk, we still need to return the correct end pointer.
2617 if (Ret && Func == LibFunc::stpcpy_chk)
2618 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2619 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002620}
2621
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002622Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2623 IRBuilder<> &B,
2624 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002625 Function *Callee = CI->getCalledFunction();
2626 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002627
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002628 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002629 return nullptr;
2630 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002631 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002632 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002633 return Ret;
2634 }
2635 return nullptr;
2636}
2637
2638Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002639 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2640 // Some clang users checked for _chk libcall availability using:
2641 // __has_builtin(__builtin___memcpy_chk)
2642 // When compiling with -fno-builtin, this is always true.
2643 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2644 // end up with fortified libcalls, which isn't acceptable in a freestanding
2645 // environment which only provides their non-fortified counterparts.
2646 //
2647 // Until we change clang and/or teach external users to check for availability
2648 // differently, disregard the "nobuiltin" attribute and TLI::has.
2649 //
2650 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002651
2652 LibFunc::Func Func;
2653 Function *Callee = CI->getCalledFunction();
2654 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002655
2656 SmallVector<OperandBundleDef, 2> OpBundles;
2657 CI->getOperandBundlesAsDefs(OpBundles);
2658 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002659 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2660
2661 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002662 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002663 return nullptr;
2664
2665 // We never change the calling convention.
2666 if (!ignoreCallingConv(Func) && !isCallingConvC)
2667 return nullptr;
2668
2669 switch (Func) {
2670 case LibFunc::memcpy_chk:
2671 return optimizeMemCpyChk(CI, Builder);
2672 case LibFunc::memmove_chk:
2673 return optimizeMemMoveChk(CI, Builder);
2674 case LibFunc::memset_chk:
2675 return optimizeMemSetChk(CI, Builder);
2676 case LibFunc::stpcpy_chk:
2677 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002678 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002679 case LibFunc::stpncpy_chk:
2680 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002681 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002682 default:
2683 break;
2684 }
2685 return nullptr;
2686}
2687
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002688FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2689 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2690 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}