blob: 104a82ce2a5b9af55ca15266f3093975ca022d61 [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"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000034#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000040 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000042
Sanjay Patela92fa442014-10-22 15:29:23 +000043static cl::opt<bool>
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
45 cl::init(false),
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
48
49
Meador Ingedf796f82012-10-13 16:45:24 +000050//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000051// Helper Functions
52//===----------------------------------------------------------------------===//
53
Chris Bienemanad070d02014-09-17 20:55:46 +000054static bool ignoreCallingConv(LibFunc::Func Func) {
Davide Italianob883b012015-11-12 23:39:00 +000055 return Func == LibFunc::abs || Func == LibFunc::labs ||
56 Func == LibFunc::llabs || Func == LibFunc::strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000057}
58
Sanjay Pateld707db92015-12-31 16:10:49 +000059/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000060static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000061 for (User *U : V->users()) {
62 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000063 if (IC->isEquality())
64 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
65 if (C->isNullValue())
66 continue;
67 // Unknown instruction.
68 return false;
69 }
70 return true;
71}
72
Sanjay Pateld707db92015-12-31 16:10:49 +000073/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000074static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000075 for (User *U : V->users()) {
76 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000077 if (IC->isEquality() && IC->getOperand(1) == With)
78 continue;
79 // Unknown instruction.
80 return false;
81 }
82 return true;
83}
84
Meador Inge08ca1152012-11-26 20:37:20 +000085static bool callHasFloatingPointArgument(const CallInst *CI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +000086 return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
87 return OI->getType()->isFloatingPointTy();
88 });
Meador Inge08ca1152012-11-26 20:37:20 +000089}
90
Benjamin Kramer2702caa2013-08-31 18:19:35 +000091/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000092/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000093static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
94 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
95 LibFunc::Func LongDoubleFn) {
96 switch (Ty->getTypeID()) {
97 case Type::FloatTyID:
98 return TLI->has(FloatFn);
99 case Type::DoubleTyID:
100 return TLI->has(DoubleFn);
101 default:
102 return TLI->has(LongDoubleFn);
103 }
104}
105
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000106/// \brief Returns whether \p F matches the signature expected for the
107/// string/memory copying library function \p Func.
108/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
109/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000110static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
111 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000112 FunctionType *FT = F->getFunctionType();
113 LLVMContext &Context = F->getContext();
114 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000115 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000116 unsigned NumParams = FT->getNumParams();
117
118 // All string libfuncs return the same type as the first parameter.
119 if (FT->getReturnType() != FT->getParamType(0))
120 return false;
121
122 switch (Func) {
123 default:
124 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
125 case LibFunc::stpncpy_chk:
126 case LibFunc::strncpy_chk:
127 --NumParams; // fallthrough
128 case LibFunc::stpncpy:
129 case LibFunc::strncpy: {
130 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
131 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
132 return false;
133 break;
134 }
135 case LibFunc::strcpy_chk:
136 case LibFunc::stpcpy_chk:
137 --NumParams; // fallthrough
138 case LibFunc::stpcpy:
139 case LibFunc::strcpy: {
140 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
141 FT->getParamType(0) != PCharTy)
142 return false;
143 break;
144 }
145 case LibFunc::memmove_chk:
146 case LibFunc::memcpy_chk:
147 --NumParams; // fallthrough
148 case LibFunc::memmove:
149 case LibFunc::memcpy: {
150 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
151 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
152 return false;
153 break;
154 }
155 case LibFunc::memset_chk:
156 --NumParams; // fallthrough
157 case LibFunc::memset: {
158 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
159 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
160 return false;
161 break;
162 }
163 }
164 // If this is a fortified libcall, the last parameter is a size_t.
165 if (NumParams == FT->getNumParams() - 1)
166 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
167 return true;
168}
169
Meador Inged589ac62012-10-31 03:33:06 +0000170//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000171// String and Memory Library Call Optimizations
172//===----------------------------------------------------------------------===//
173
Chris Bienemanad070d02014-09-17 20:55:46 +0000174Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
175 Function *Callee = CI->getCalledFunction();
176 // Verify the "strcat" function prototype.
177 FunctionType *FT = Callee->getFunctionType();
178 if (FT->getNumParams() != 2||
179 FT->getReturnType() != B.getInt8PtrTy() ||
180 FT->getParamType(0) != FT->getReturnType() ||
181 FT->getParamType(1) != FT->getReturnType())
182 return nullptr;
183
184 // Extract some information from the instruction
185 Value *Dst = CI->getArgOperand(0);
186 Value *Src = CI->getArgOperand(1);
187
188 // See if we can get the length of the input string.
189 uint64_t Len = GetStringLength(Src);
190 if (Len == 0)
191 return nullptr;
192 --Len; // Unbias length.
193
194 // Handle the simple, do-nothing case: strcat(x, "") -> x
195 if (Len == 0)
196 return Dst;
197
Chris Bienemanad070d02014-09-17 20:55:46 +0000198 return emitStrLenMemCpy(Src, Dst, Len, B);
199}
200
201Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
202 IRBuilder<> &B) {
203 // We need to find the end of the destination string. That's where the
204 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000205 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000206 if (!DstLen)
207 return nullptr;
208
209 // Now that we have the destination's length, we must index into the
210 // destination's pointer to get the actual memcpy destination (end of
211 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000212 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000213
214 // We have enough information to now generate the memcpy call to do the
215 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000216 B.CreateMemCpy(CpyDst, Src,
217 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000218 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000219 return Dst;
220}
221
222Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
223 Function *Callee = CI->getCalledFunction();
224 // Verify the "strncat" function prototype.
225 FunctionType *FT = Callee->getFunctionType();
226 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
227 FT->getParamType(0) != FT->getReturnType() ||
228 FT->getParamType(1) != FT->getReturnType() ||
229 !FT->getParamType(2)->isIntegerTy())
230 return nullptr;
231
Sanjay Pateld707db92015-12-31 16:10:49 +0000232 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000233 Value *Dst = CI->getArgOperand(0);
234 Value *Src = CI->getArgOperand(1);
235 uint64_t Len;
236
Sanjay Pateld707db92015-12-31 16:10:49 +0000237 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000238 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
239 Len = LengthArg->getZExtValue();
240 else
241 return nullptr;
242
243 // See if we can get the length of the input string.
244 uint64_t SrcLen = GetStringLength(Src);
245 if (SrcLen == 0)
246 return nullptr;
247 --SrcLen; // Unbias length.
248
249 // Handle the simple, do-nothing cases:
250 // strncat(x, "", c) -> x
251 // strncat(x, c, 0) -> x
252 if (SrcLen == 0 || Len == 0)
253 return Dst;
254
Sanjay Pateld707db92015-12-31 16:10:49 +0000255 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000256 if (Len < SrcLen)
257 return nullptr;
258
259 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000260 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000261 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
262}
263
264Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
265 Function *Callee = CI->getCalledFunction();
266 // Verify the "strchr" function prototype.
267 FunctionType *FT = Callee->getFunctionType();
268 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
269 FT->getParamType(0) != FT->getReturnType() ||
270 !FT->getParamType(1)->isIntegerTy(32))
271 return nullptr;
272
273 Value *SrcStr = CI->getArgOperand(0);
274
275 // If the second operand is non-constant, see if we can compute the length
276 // of the input string and turn this into memchr.
277 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
278 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000279 uint64_t Len = GetStringLength(SrcStr);
280 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
281 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000282
Sanjay Pateld3112a52016-01-19 19:46:10 +0000283 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000284 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
285 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000286 }
287
Chris Bienemanad070d02014-09-17 20:55:46 +0000288 // Otherwise, the character is a constant, see if the first argument is
289 // a string literal. If so, we can constant fold.
290 StringRef Str;
291 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000292 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000293 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000294 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000295 return nullptr;
296 }
297
298 // Compute the offset, make sure to handle the case when we're searching for
299 // zero (a weird way to spell strlen).
300 size_t I = (0xFF & CharC->getSExtValue()) == 0
301 ? Str.size()
302 : Str.find(CharC->getSExtValue());
303 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
304 return Constant::getNullValue(CI->getType());
305
306 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000307 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000308}
309
310Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
311 Function *Callee = CI->getCalledFunction();
312 // Verify the "strrchr" function prototype.
313 FunctionType *FT = Callee->getFunctionType();
314 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
315 FT->getParamType(0) != FT->getReturnType() ||
316 !FT->getParamType(1)->isIntegerTy(32))
317 return nullptr;
318
319 Value *SrcStr = CI->getArgOperand(0);
320 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
321
322 // Cannot fold anything if we're not looking for a constant.
323 if (!CharC)
324 return nullptr;
325
326 StringRef Str;
327 if (!getConstantStringInfo(SrcStr, Str)) {
328 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000329 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000330 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000331 return nullptr;
332 }
333
334 // Compute the offset.
335 size_t I = (0xFF & CharC->getSExtValue()) == 0
336 ? Str.size()
337 : Str.rfind(CharC->getSExtValue());
338 if (I == StringRef::npos) // Didn't find the char. Return null.
339 return Constant::getNullValue(CI->getType());
340
341 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000342 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000343}
344
345Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
346 Function *Callee = CI->getCalledFunction();
347 // Verify the "strcmp" function prototype.
348 FunctionType *FT = Callee->getFunctionType();
349 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
350 FT->getParamType(0) != FT->getParamType(1) ||
351 FT->getParamType(0) != B.getInt8PtrTy())
352 return nullptr;
353
354 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
355 if (Str1P == Str2P) // strcmp(x,x) -> 0
356 return ConstantInt::get(CI->getType(), 0);
357
358 StringRef Str1, Str2;
359 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
360 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
361
362 // strcmp(x, y) -> cnst (if both x and y are constant strings)
363 if (HasStr1 && HasStr2)
364 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
365
366 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
367 return B.CreateNeg(
368 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
369
370 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
371 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
372
373 // strcmp(P, "x") -> memcmp(P, "x", 2)
374 uint64_t Len1 = GetStringLength(Str1P);
375 uint64_t Len2 = GetStringLength(Str2P);
376 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000377 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000378 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000379 std::min(Len1, Len2)),
380 B, DL, TLI);
381 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000382
Chris Bienemanad070d02014-09-17 20:55:46 +0000383 return nullptr;
384}
385
386Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
387 Function *Callee = CI->getCalledFunction();
388 // Verify the "strncmp" function prototype.
389 FunctionType *FT = Callee->getFunctionType();
390 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
391 FT->getParamType(0) != FT->getParamType(1) ||
392 FT->getParamType(0) != B.getInt8PtrTy() ||
393 !FT->getParamType(2)->isIntegerTy())
394 return nullptr;
395
396 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
397 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
398 return ConstantInt::get(CI->getType(), 0);
399
400 // Get the length argument if it is constant.
401 uint64_t Length;
402 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
403 Length = LengthArg->getZExtValue();
404 else
405 return nullptr;
406
407 if (Length == 0) // strncmp(x,y,0) -> 0
408 return ConstantInt::get(CI->getType(), 0);
409
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000410 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000411 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000412
413 StringRef Str1, Str2;
414 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
415 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
416
417 // strncmp(x, y) -> cnst (if both x and y are constant strings)
418 if (HasStr1 && HasStr2) {
419 StringRef SubStr1 = Str1.substr(0, Length);
420 StringRef SubStr2 = Str2.substr(0, Length);
421 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
422 }
423
424 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
425 return B.CreateNeg(
426 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
427
428 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
429 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
430
431 return nullptr;
432}
433
434Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
435 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000436
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000437 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000438 return nullptr;
439
440 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
441 if (Dst == Src) // strcpy(x,x) -> x
442 return Src;
443
Chris Bienemanad070d02014-09-17 20:55:46 +0000444 // See if we can get the length of the input string.
445 uint64_t Len = GetStringLength(Src);
446 if (Len == 0)
447 return nullptr;
448
449 // We have enough information to now generate the memcpy call to do the
450 // copy for us. Make a memcpy to copy the nul byte with align = 1.
451 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000452 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000453 return Dst;
454}
455
456Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
457 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000458 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000459 return nullptr;
460
461 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
462 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000463 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000464 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000465 }
466
467 // See if we can get the length of the input string.
468 uint64_t Len = GetStringLength(Src);
469 if (Len == 0)
470 return nullptr;
471
Davide Italianob7487e62015-11-02 23:07:14 +0000472 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000473 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000474 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
475 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000476
477 // We have enough information to now generate the memcpy call to do the
478 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000479 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000480 return DstEnd;
481}
482
483Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
484 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000486 return nullptr;
487
488 Value *Dst = CI->getArgOperand(0);
489 Value *Src = CI->getArgOperand(1);
490 Value *LenOp = CI->getArgOperand(2);
491
492 // See if we can get the length of the input string.
493 uint64_t SrcLen = GetStringLength(Src);
494 if (SrcLen == 0)
495 return nullptr;
496 --SrcLen;
497
498 if (SrcLen == 0) {
499 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
500 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000501 return Dst;
502 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000503
Chris Bienemanad070d02014-09-17 20:55:46 +0000504 uint64_t Len;
505 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
506 Len = LengthArg->getZExtValue();
507 else
508 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000509
Chris Bienemanad070d02014-09-17 20:55:46 +0000510 if (Len == 0)
511 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000512
Chris Bienemanad070d02014-09-17 20:55:46 +0000513 // Let strncpy handle the zero padding
514 if (Len > SrcLen + 1)
515 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000516
Davide Italianob7487e62015-11-02 23:07:14 +0000517 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000518 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000519 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000520
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 return Dst;
522}
Meador Inge7fb2f732012-10-13 16:45:32 +0000523
Chris Bienemanad070d02014-09-17 20:55:46 +0000524Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
525 Function *Callee = CI->getCalledFunction();
526 FunctionType *FT = Callee->getFunctionType();
527 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
528 !FT->getReturnType()->isIntegerTy())
529 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000530
Chris Bienemanad070d02014-09-17 20:55:46 +0000531 Value *Src = CI->getArgOperand(0);
532
533 // Constant folding: strlen("xyz") -> 3
534 if (uint64_t Len = GetStringLength(Src))
535 return ConstantInt::get(CI->getType(), Len - 1);
536
David L Kreitzer752c1442016-04-13 14:31:06 +0000537 // If s is a constant pointer pointing to a string literal, we can fold
538 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
539 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
540 // We only try to simplify strlen when the pointer s points to an array
541 // of i8. Otherwise, we would need to scale the offset x before doing the
542 // subtraction. This will make the optimization more complex, and it's not
543 // very useful because calling strlen for a pointer of other types is
544 // very uncommon.
545 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
546 if (!isGEPBasedOnPointerToString(GEP))
547 return nullptr;
548
549 StringRef Str;
550 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
551 size_t NullTermIdx = Str.find('\0');
552
553 // If the string does not have '\0', leave it to strlen to compute
554 // its length.
555 if (NullTermIdx == StringRef::npos)
556 return nullptr;
557
558 Value *Offset = GEP->getOperand(2);
559 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
560 APInt KnownZero(BitWidth, 0);
561 APInt KnownOne(BitWidth, 0);
562 computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
563 nullptr);
564 KnownZero.flipAllBits();
565 size_t ArrSize =
566 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
567
568 // KnownZero's bits are flipped, so zeros in KnownZero now represent
569 // bits known to be zeros in Offset, and ones in KnowZero represent
570 // bits unknown in Offset. Therefore, Offset is known to be in range
571 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
572 // unsigned-less-than NullTermIdx.
573 //
574 // If Offset is not provably in the range [0, NullTermIdx], we can still
575 // optimize if we can prove that the program has undefined behavior when
576 // Offset is outside that range. That is the case when GEP->getOperand(0)
577 // is a pointer to an object whose memory extent is NullTermIdx+1.
578 if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
579 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
580 NullTermIdx == ArrSize - 1))
581 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
582 Offset);
583 }
584
585 return nullptr;
586 }
587
Chris Bienemanad070d02014-09-17 20:55:46 +0000588 // strlen(x?"foo":"bars") --> x ? 3 : 4
589 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
590 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
591 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
592 if (LenTrue && LenFalse) {
593 Function *Caller = CI->getParent()->getParent();
594 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
595 SI->getDebugLoc(),
596 "folded strlen(select) to select of constants");
597 return B.CreateSelect(SI->getCondition(),
598 ConstantInt::get(CI->getType(), LenTrue - 1),
599 ConstantInt::get(CI->getType(), LenFalse - 1));
600 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000601 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000602
Chris Bienemanad070d02014-09-17 20:55:46 +0000603 // strlen(x) != 0 --> *x != 0
604 // strlen(x) == 0 --> *x == 0
605 if (isOnlyUsedInZeroEqualityComparison(CI))
606 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000607
Chris Bienemanad070d02014-09-17 20:55:46 +0000608 return nullptr;
609}
Meador Inge17418502012-10-13 16:45:37 +0000610
Chris Bienemanad070d02014-09-17 20:55:46 +0000611Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
612 Function *Callee = CI->getCalledFunction();
613 FunctionType *FT = Callee->getFunctionType();
614 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
615 FT->getParamType(1) != FT->getParamType(0) ||
616 FT->getReturnType() != FT->getParamType(0))
617 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000618
Chris Bienemanad070d02014-09-17 20:55:46 +0000619 StringRef S1, S2;
620 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
621 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000622
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000623 // strpbrk(s, "") -> nullptr
624 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000625 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
626 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000627
Chris Bienemanad070d02014-09-17 20:55:46 +0000628 // Constant folding.
629 if (HasS1 && HasS2) {
630 size_t I = S1.find_first_of(S2);
631 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000632 return Constant::getNullValue(CI->getType());
633
Sanjay Pateld707db92015-12-31 16:10:49 +0000634 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
635 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000636 }
Meador Inge17418502012-10-13 16:45:37 +0000637
Chris Bienemanad070d02014-09-17 20:55:46 +0000638 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000639 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000640 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000641
642 return nullptr;
643}
644
645Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
646 Function *Callee = CI->getCalledFunction();
647 FunctionType *FT = Callee->getFunctionType();
648 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
649 !FT->getParamType(0)->isPointerTy() ||
650 !FT->getParamType(1)->isPointerTy())
651 return nullptr;
652
653 Value *EndPtr = CI->getArgOperand(1);
654 if (isa<ConstantPointerNull>(EndPtr)) {
655 // With a null EndPtr, this function won't capture the main argument.
656 // It would be readonly too, except that it still may write to errno.
657 CI->addAttribute(1, Attribute::NoCapture);
658 }
659
660 return nullptr;
661}
662
663Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
664 Function *Callee = CI->getCalledFunction();
665 FunctionType *FT = Callee->getFunctionType();
666 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
667 FT->getParamType(1) != FT->getParamType(0) ||
668 !FT->getReturnType()->isIntegerTy())
669 return nullptr;
670
671 StringRef S1, S2;
672 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
673 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
674
675 // strspn(s, "") -> 0
676 // strspn("", s) -> 0
677 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
678 return Constant::getNullValue(CI->getType());
679
680 // Constant folding.
681 if (HasS1 && HasS2) {
682 size_t Pos = S1.find_first_not_of(S2);
683 if (Pos == StringRef::npos)
684 Pos = S1.size();
685 return ConstantInt::get(CI->getType(), Pos);
686 }
687
688 return nullptr;
689}
690
691Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
692 Function *Callee = CI->getCalledFunction();
693 FunctionType *FT = Callee->getFunctionType();
694 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
695 FT->getParamType(1) != FT->getParamType(0) ||
696 !FT->getReturnType()->isIntegerTy())
697 return nullptr;
698
699 StringRef S1, S2;
700 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
701 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
702
703 // strcspn("", s) -> 0
704 if (HasS1 && S1.empty())
705 return Constant::getNullValue(CI->getType());
706
707 // Constant folding.
708 if (HasS1 && HasS2) {
709 size_t Pos = S1.find_first_of(S2);
710 if (Pos == StringRef::npos)
711 Pos = S1.size();
712 return ConstantInt::get(CI->getType(), Pos);
713 }
714
715 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000716 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000717 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000718
719 return nullptr;
720}
721
722Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
723 Function *Callee = CI->getCalledFunction();
724 FunctionType *FT = Callee->getFunctionType();
725 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
726 !FT->getParamType(1)->isPointerTy() ||
727 !FT->getReturnType()->isPointerTy())
728 return nullptr;
729
730 // fold strstr(x, x) -> x.
731 if (CI->getArgOperand(0) == CI->getArgOperand(1))
732 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
733
734 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000735 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000736 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000737 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000738 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000739 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000740 StrLen, B, DL, TLI);
741 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000742 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
744 ICmpInst *Old = cast<ICmpInst>(*UI++);
745 Value *Cmp =
746 B.CreateICmp(Old->getPredicate(), StrNCmp,
747 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
748 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000749 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000750 return CI;
751 }
Meador Inge17418502012-10-13 16:45:37 +0000752
Chris Bienemanad070d02014-09-17 20:55:46 +0000753 // See if either input string is a constant string.
754 StringRef SearchStr, ToFindStr;
755 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
756 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
757
758 // fold strstr(x, "") -> x.
759 if (HasStr2 && ToFindStr.empty())
760 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
761
762 // If both strings are known, constant fold it.
763 if (HasStr1 && HasStr2) {
764 size_t Offset = SearchStr.find(ToFindStr);
765
766 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000767 return Constant::getNullValue(CI->getType());
768
Chris Bienemanad070d02014-09-17 20:55:46 +0000769 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000770 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000771 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
772 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000773 }
Meador Inge17418502012-10-13 16:45:37 +0000774
Chris Bienemanad070d02014-09-17 20:55:46 +0000775 // fold strstr(x, "y") -> strchr(x, 'y').
776 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000777 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000778 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
779 }
780 return nullptr;
781}
Meador Inge40b6fac2012-10-15 03:47:37 +0000782
Benjamin Kramer691363e2015-03-21 15:36:21 +0000783Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
784 Function *Callee = CI->getCalledFunction();
785 FunctionType *FT = Callee->getFunctionType();
786 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
787 !FT->getParamType(1)->isIntegerTy(32) ||
788 !FT->getParamType(2)->isIntegerTy() ||
789 !FT->getReturnType()->isPointerTy())
790 return nullptr;
791
792 Value *SrcStr = CI->getArgOperand(0);
793 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
794 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
795
796 // memchr(x, y, 0) -> null
797 if (LenC && LenC->isNullValue())
798 return Constant::getNullValue(CI->getType());
799
Benjamin Kramer7857d722015-03-21 21:09:33 +0000800 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000801 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000802 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000803 return nullptr;
804
805 // Truncate the string to LenC. If Str is smaller than LenC we will still only
806 // scan the string, as reading past the end of it is undefined and we can just
807 // return null if we don't find the char.
808 Str = Str.substr(0, LenC->getZExtValue());
809
Benjamin Kramer7857d722015-03-21 21:09:33 +0000810 // If the char is variable but the input str and length are not we can turn
811 // this memchr call into a simple bit field test. Of course this only works
812 // when the return value is only checked against null.
813 //
814 // It would be really nice to reuse switch lowering here but we can't change
815 // the CFG at this point.
816 //
817 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
818 // after bounds check.
819 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000820 unsigned char Max =
821 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
822 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000823
824 // Make sure the bit field we're about to create fits in a register on the
825 // target.
826 // FIXME: On a 64 bit architecture this prevents us from using the
827 // interesting range of alpha ascii chars. We could do better by emitting
828 // two bitfields or shifting the range by 64 if no lower chars are used.
829 if (!DL.fitsInLegalInteger(Max + 1))
830 return nullptr;
831
832 // For the bit field use a power-of-2 type with at least 8 bits to avoid
833 // creating unnecessary illegal types.
834 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
835
836 // Now build the bit field.
837 APInt Bitfield(Width, 0);
838 for (char C : Str)
839 Bitfield.setBit((unsigned char)C);
840 Value *BitfieldC = B.getInt(Bitfield);
841
842 // First check that the bit field access is within bounds.
843 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
844 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
845 "memchr.bounds");
846
847 // Create code that checks if the given bit is set in the field.
848 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
849 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
850
851 // Finally merge both checks and cast to pointer type. The inttoptr
852 // implicitly zexts the i1 to intptr type.
853 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
854 }
855
856 // Check if all arguments are constants. If so, we can constant fold.
857 if (!CharC)
858 return nullptr;
859
Benjamin Kramer691363e2015-03-21 15:36:21 +0000860 // Compute the offset.
861 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
862 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
863 return Constant::getNullValue(CI->getType());
864
865 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000866 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000867}
868
Chris Bienemanad070d02014-09-17 20:55:46 +0000869Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
870 Function *Callee = CI->getCalledFunction();
871 FunctionType *FT = Callee->getFunctionType();
872 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
873 !FT->getParamType(1)->isPointerTy() ||
874 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000875 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000876
Chris Bienemanad070d02014-09-17 20:55:46 +0000877 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000878
Chris Bienemanad070d02014-09-17 20:55:46 +0000879 if (LHS == RHS) // memcmp(s,s,x) -> 0
880 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000881
Chris Bienemanad070d02014-09-17 20:55:46 +0000882 // Make sure we have a constant length.
883 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
884 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000885 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000886 uint64_t Len = LenC->getZExtValue();
887
888 if (Len == 0) // memcmp(s1,s2,0) -> 0
889 return Constant::getNullValue(CI->getType());
890
891 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
892 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000893 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000894 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000895 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000896 CI->getType(), "rhsv");
897 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000898 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000899
Chad Rosierdc655322015-08-28 18:30:18 +0000900 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
901 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
902
903 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
904 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
905
906 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
907 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
908
909 Type *LHSPtrTy =
910 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
911 Type *RHSPtrTy =
912 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
913
Sanjay Pateld707db92015-12-31 16:10:49 +0000914 Value *LHSV =
915 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
916 Value *RHSV =
917 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000918
919 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
920 }
921 }
922
Chris Bienemanad070d02014-09-17 20:55:46 +0000923 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
924 StringRef LHSStr, RHSStr;
925 if (getConstantStringInfo(LHS, LHSStr) &&
926 getConstantStringInfo(RHS, RHSStr)) {
927 // Make sure we're not reading out-of-bounds memory.
928 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000929 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000930 // Fold the memcmp and normalize the result. This way we get consistent
931 // results across multiple platforms.
932 uint64_t Ret = 0;
933 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
934 if (Cmp < 0)
935 Ret = -1;
936 else if (Cmp > 0)
937 Ret = 1;
938 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000939 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000940
Chris Bienemanad070d02014-09-17 20:55:46 +0000941 return nullptr;
942}
Meador Inge9a6a1902012-10-31 00:20:56 +0000943
Chris Bienemanad070d02014-09-17 20:55:46 +0000944Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
945 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000946
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000948 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000949
Chris Bienemanad070d02014-09-17 20:55:46 +0000950 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
951 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000952 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000953 return CI->getArgOperand(0);
954}
Meador Inge05a625a2012-10-31 14:58:26 +0000955
Chris Bienemanad070d02014-09-17 20:55:46 +0000956Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
957 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000958
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000960 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000961
Chris Bienemanad070d02014-09-17 20:55:46 +0000962 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
963 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000964 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000965 return CI->getArgOperand(0);
966}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000967
Sanjay Patel980b2802016-01-26 16:17:24 +0000968// TODO: Does this belong in BuildLibCalls or should all of those similar
969// functions be moved here?
970static Value *emitCalloc(Value *Num, Value *Size, const AttributeSet &Attrs,
971 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
972 LibFunc::Func Func;
973 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
974 return nullptr;
975
976 Module *M = B.GetInsertBlock()->getModule();
977 const DataLayout &DL = M->getDataLayout();
978 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
979 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
980 PtrType, PtrType, nullptr);
981 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
982
983 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
984 CI->setCallingConv(F->getCallingConv());
985
986 return CI;
987}
988
989/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
990static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
991 const TargetLibraryInfo &TLI) {
992 // This has to be a memset of zeros (bzero).
993 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
994 if (!FillValue || FillValue->getZExtValue() != 0)
995 return nullptr;
996
997 // TODO: We should handle the case where the malloc has more than one use.
998 // This is necessary to optimize common patterns such as when the result of
999 // the malloc is checked against null or when a memset intrinsic is used in
1000 // place of a memset library call.
1001 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
1002 if (!Malloc || !Malloc->hasOneUse())
1003 return nullptr;
1004
1005 // Is the inner call really malloc()?
1006 Function *InnerCallee = Malloc->getCalledFunction();
1007 LibFunc::Func Func;
1008 if (!TLI.getLibFunc(InnerCallee->getName(), Func) || !TLI.has(Func) ||
1009 Func != LibFunc::malloc)
1010 return nullptr;
1011
1012 // Matching the name is not good enough. Make sure the parameter and return
1013 // type match the standard library signature.
1014 FunctionType *FT = InnerCallee->getFunctionType();
1015 if (FT->getNumParams() != 1 || !FT->getParamType(0)->isIntegerTy())
1016 return nullptr;
1017
1018 auto *RetType = dyn_cast<PointerType>(FT->getReturnType());
1019 if (!RetType || !RetType->getPointerElementType()->isIntegerTy(8))
1020 return nullptr;
1021
1022 // The memset must cover the same number of bytes that are malloc'd.
1023 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
1024 return nullptr;
1025
1026 // Replace the malloc with a calloc. We need the data layout to know what the
1027 // actual size of a 'size_t' parameter is.
1028 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1029 const DataLayout &DL = Malloc->getModule()->getDataLayout();
1030 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
1031 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1032 Malloc->getArgOperand(0), Malloc->getAttributes(),
1033 B, TLI);
1034 if (!Calloc)
1035 return nullptr;
1036
1037 Malloc->replaceAllUsesWith(Calloc);
1038 Malloc->eraseFromParent();
1039
1040 return Calloc;
1041}
1042
Chris Bienemanad070d02014-09-17 20:55:46 +00001043Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1044 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +00001045
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001046 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +00001047 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +00001048
Sanjay Patel980b2802016-01-26 16:17:24 +00001049 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
1050 return Calloc;
1051
Chris Bienemanad070d02014-09-17 20:55:46 +00001052 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1053 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1054 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1055 return CI->getArgOperand(0);
1056}
Meador Inged4825782012-11-11 06:49:03 +00001057
Meador Inge193e0352012-11-13 04:16:17 +00001058//===----------------------------------------------------------------------===//
1059// Math Library Optimizations
1060//===----------------------------------------------------------------------===//
1061
Matthias Braund34e4d22014-12-03 21:46:33 +00001062/// Return a variant of Val with float type.
1063/// Currently this works in two cases: If Val is an FPExtension of a float
1064/// value to something bigger, simply return the operand.
1065/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1066/// loss of precision do so.
1067static Value *valueHasFloatPrecision(Value *Val) {
1068 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1069 Value *Op = Cast->getOperand(0);
1070 if (Op->getType()->isFloatTy())
1071 return Op;
1072 }
1073 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1074 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001075 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +00001076 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001077 &losesInfo);
1078 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001079 return ConstantFP::get(Const->getContext(), F);
1080 }
1081 return nullptr;
1082}
1083
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001084/// Any floating-point library function that we're trying to simplify will have
1085/// a signature of the form: fptype foo(fptype param1, fptype param2, ...).
1086/// CheckDoubleTy indicates that 'fptype' must be 'double'.
1087static bool matchesFPLibFunctionSignature(const Function *F, unsigned NumParams,
1088 bool CheckDoubleTy) {
1089 FunctionType *FT = F->getFunctionType();
1090 if (FT->getNumParams() != NumParams)
1091 return false;
1092
1093 // The return type must match what we're looking for.
1094 Type *RetTy = FT->getReturnType();
1095 if (CheckDoubleTy ? !RetTy->isDoubleTy() : !RetTy->isFloatingPointTy())
1096 return false;
1097
1098 // Each parameter must match the return type, and therefore, match every other
1099 // parameter too.
1100 for (const Type *ParamTy : FT->params())
1101 if (ParamTy != RetTy)
1102 return false;
1103
1104 return true;
1105}
1106
Sanjay Patel4e971da2016-01-21 18:01:57 +00001107/// Shrink double -> float for unary functions like 'floor'.
1108static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1109 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001110 Function *Callee = CI->getCalledFunction();
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001111 if (!matchesFPLibFunctionSignature(Callee, 1, true))
Chris Bienemanad070d02014-09-17 20:55:46 +00001112 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001113
Chris Bienemanad070d02014-09-17 20:55:46 +00001114 if (CheckRetType) {
1115 // Check if all the uses for function like 'sin' are converted to float.
1116 for (User *U : CI->users()) {
1117 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1118 if (!Cast || !Cast->getType()->isFloatTy())
1119 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001120 }
Meador Inge193e0352012-11-13 04:16:17 +00001121 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001122
1123 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +00001124 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1125 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +00001126 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +00001127
1128 // Propagate fast-math flags from the existing call to the new call.
1129 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001130 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001131
1132 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001133 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001134 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001135 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001136 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1137 V = B.CreateCall(F, V);
1138 } else {
1139 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001140 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +00001141 }
1142
Chris Bienemanad070d02014-09-17 20:55:46 +00001143 return B.CreateFPExt(V, B.getDoubleTy());
1144}
Meador Inge193e0352012-11-13 04:16:17 +00001145
Sanjay Patel4e971da2016-01-21 18:01:57 +00001146/// Shrink double -> float for binary functions like 'fmin/fmax'.
1147static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001148 Function *Callee = CI->getCalledFunction();
Sanjay Patelfcc7c1a2016-01-21 20:19:54 +00001149 if (!matchesFPLibFunctionSignature(Callee, 2, true))
Craig Topperf40110f2014-04-25 05:29:35 +00001150 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001151
Chris Bienemanad070d02014-09-17 20:55:46 +00001152 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001153 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1154 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1155 if (V1 == nullptr)
1156 return nullptr;
1157 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1158 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001159 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001160
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001161 // Propagate fast-math flags from the existing call to the new call.
1162 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001163 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001164
Chris Bienemanad070d02014-09-17 20:55:46 +00001165 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001166 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001167 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001168 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001169 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001170 return B.CreateFPExt(V, B.getDoubleTy());
1171}
1172
1173Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1174 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001175 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1176 return nullptr;
1177
Chris Bienemanad070d02014-09-17 20:55:46 +00001178 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001179 StringRef Name = Callee->getName();
1180 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001181 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001182
Chris Bienemanad070d02014-09-17 20:55:46 +00001183 // cos(-x) -> cos(x)
1184 Value *Op1 = CI->getArgOperand(0);
1185 if (BinaryOperator::isFNeg(Op1)) {
1186 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1187 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1188 }
1189 return Ret;
1190}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001191
Weiming Zhao82130722015-12-04 22:00:47 +00001192static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1193 // Multiplications calculated using Addition Chains.
1194 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1195
1196 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1197
1198 if (InnerChain[Exp])
1199 return InnerChain[Exp];
1200
1201 static const unsigned AddChain[33][2] = {
1202 {0, 0}, // Unused.
1203 {0, 0}, // Unused (base case = pow1).
1204 {1, 1}, // Unused (pre-computed).
1205 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1206 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1207 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1208 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1209 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1210 };
1211
1212 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1213 getPow(InnerChain, AddChain[Exp][1], B));
1214 return InnerChain[Exp];
1215}
1216
Chris Bienemanad070d02014-09-17 20:55:46 +00001217Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1218 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001219 if (!matchesFPLibFunctionSignature(Callee, 2, false))
1220 return nullptr;
1221
Chris Bienemanad070d02014-09-17 20:55:46 +00001222 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001223 StringRef Name = Callee->getName();
1224 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001225 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001226
Chris Bienemanad070d02014-09-17 20:55:46 +00001227 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1228 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1229 // pow(1.0, x) -> 1.0
1230 if (Op1C->isExactlyValue(1.0))
1231 return Op1C;
1232 // pow(2.0, x) -> exp2(x)
1233 if (Op1C->isExactlyValue(2.0) &&
1234 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1235 LibFunc::exp2l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001236 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
Davide Italianod9f87b42015-11-06 21:05:07 +00001237 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001238 // pow(10.0, x) -> exp10(x)
1239 if (Op1C->isExactlyValue(10.0) &&
1240 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1241 LibFunc::exp10l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001242 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001243 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001244 }
1245
Sanjay Patel6002e782016-01-12 17:30:37 +00001246 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001247 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001248 // We enable these only with fast-math. Besides rounding differences, the
1249 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001250 // Example: x = 1000, y = 0.001.
1251 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001252 auto *OpC = dyn_cast<CallInst>(Op1);
1253 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1254 LibFunc::Func Func;
1255 Function *OpCCallee = OpC->getCalledFunction();
1256 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1257 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001258 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001259 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001260 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001261 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001262 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001263 }
1264 }
1265
Chris Bienemanad070d02014-09-17 20:55:46 +00001266 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1267 if (!Op2C)
1268 return Ret;
1269
1270 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1271 return ConstantFP::get(CI->getType(), 1.0);
1272
1273 if (Op2C->isExactlyValue(0.5) &&
1274 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1275 LibFunc::sqrtl) &&
1276 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1277 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001278
1279 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001280 if (CI->hasUnsafeAlgebra()) {
1281 IRBuilder<>::FastMathFlagGuard Guard(B);
1282 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Pateld3112a52016-01-19 19:46:10 +00001283 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
Davide Italianoc5cedd12015-11-18 23:21:32 +00001284 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001285 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001286
Chris Bienemanad070d02014-09-17 20:55:46 +00001287 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1288 // This is faster than calling pow, and still handles negative zero
1289 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001290 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1291 Value *Inf = ConstantFP::getInfinity(CI->getType());
1292 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Sanjay Pateld3112a52016-01-19 19:46:10 +00001293 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001294 Value *FAbs =
Sanjay Pateld3112a52016-01-19 19:46:10 +00001295 emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001296 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1297 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1298 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001299 }
1300
Chris Bienemanad070d02014-09-17 20:55:46 +00001301 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1302 return Op1;
1303 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1304 return B.CreateFMul(Op1, Op1, "pow2");
1305 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1306 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001307
1308 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001309 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001310 APFloat V = abs(Op2C->getValueAPF());
1311 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1312 // This transformation applies to integer exponents only.
1313 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1314 !V.isInteger())
1315 return nullptr;
1316
1317 // We will memoize intermediate products of the Addition Chain.
1318 Value *InnerChain[33] = {nullptr};
1319 InnerChain[1] = Op1;
1320 InnerChain[2] = B.CreateFMul(Op1, Op1);
1321
1322 // We cannot readily convert a non-double type (like float) to a double.
1323 // So we first convert V to something which could be converted to double.
1324 bool ignored;
1325 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001326
1327 // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
Weiming Zhao82130722015-12-04 22:00:47 +00001328 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1329 // For negative exponents simply compute the reciprocal.
1330 if (Op2C->isNegative())
1331 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1332 return FMul;
1333 }
1334
Chris Bienemanad070d02014-09-17 20:55:46 +00001335 return nullptr;
1336}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001337
Chris Bienemanad070d02014-09-17 20:55:46 +00001338Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1339 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001340 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1341 return nullptr;
1342
Chris Bienemanad070d02014-09-17 20:55:46 +00001343 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001344 StringRef Name = Callee->getName();
1345 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001346 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001347
Chris Bienemanad070d02014-09-17 20:55:46 +00001348 Value *Op = CI->getArgOperand(0);
1349 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1350 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1351 LibFunc::Func LdExp = LibFunc::ldexpl;
1352 if (Op->getType()->isFloatTy())
1353 LdExp = LibFunc::ldexpf;
1354 else if (Op->getType()->isDoubleTy())
1355 LdExp = LibFunc::ldexp;
1356
1357 if (TLI->has(LdExp)) {
1358 Value *LdExpArg = nullptr;
1359 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1360 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1361 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1362 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1363 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1364 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1365 }
1366
1367 if (LdExpArg) {
1368 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1369 if (!Op->getType()->isFloatTy())
1370 One = ConstantExpr::getFPExtend(One, Op->getType());
1371
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001372 Module *M = CI->getModule();
Sanjay Patel042aed902016-01-21 22:41:16 +00001373 Value *NewCallee =
Chris Bienemanad070d02014-09-17 20:55:46 +00001374 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001375 Op->getType(), B.getInt32Ty(), nullptr);
Sanjay Patel042aed902016-01-21 22:41:16 +00001376 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001377 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1378 CI->setCallingConv(F->getCallingConv());
1379
1380 return CI;
1381 }
1382 }
1383 return Ret;
1384}
1385
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001386Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1387 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001388 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1389 return nullptr;
1390
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001391 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001392 StringRef Name = Callee->getName();
1393 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001394 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001395
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001396 Value *Op = CI->getArgOperand(0);
1397 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1398 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1399 if (I->getOpcode() == Instruction::FMul)
1400 if (I->getOperand(0) == I->getOperand(1))
1401 return Op;
1402 }
1403 return Ret;
1404}
1405
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001406Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001407 Function *Callee = CI->getCalledFunction();
1408 if (!matchesFPLibFunctionSignature(Callee, 2, false))
1409 return nullptr;
1410
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001411 // If we can shrink the call to a float function rather than a double
1412 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001413 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001414 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1415 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001416 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001417
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001418 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001419 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001420 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001421 // Unsafe algebra sets all fast-math-flags to true.
1422 FMF.setUnsafeAlgebra();
1423 } else {
1424 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001425 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001426 return nullptr;
1427 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1428 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001429 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001430 // might be impractical."
1431 FMF.setNoSignedZeros();
1432 FMF.setNoNaNs();
1433 }
Sanjay Patela2528152016-01-12 18:03:37 +00001434 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001435
1436 // We have a relaxed floating-point environment. We can ignore NaN-handling
1437 // and transform to a compare and select. We do not have to consider errno or
1438 // exceptions, because fmin/fmax do not have those.
1439 Value *Op0 = CI->getArgOperand(0);
1440 Value *Op1 = CI->getArgOperand(1);
1441 Value *Cmp = Callee->getName().startswith("fmin") ?
1442 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1443 return B.CreateSelect(Cmp, Op0, Op1);
1444}
1445
Davide Italianob8b71332015-11-29 20:58:04 +00001446Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1447 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001448 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1449 return nullptr;
1450
Davide Italianob8b71332015-11-29 20:58:04 +00001451 Value *Ret = nullptr;
1452 StringRef Name = Callee->getName();
1453 if (UnsafeFPShrink && hasFloatVersion(Name))
1454 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001455
Sanjay Patele896ede2016-01-11 23:31:48 +00001456 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001457 return Ret;
1458 Value *Op1 = CI->getArgOperand(0);
1459 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001460
1461 // The earlier call must also be unsafe in order to do these transforms.
1462 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001463 return Ret;
1464
1465 // log(pow(x,y)) -> y*log(x)
1466 // This is only applicable to log, log2, log10.
1467 if (Name != "log" && Name != "log2" && Name != "log10")
1468 return Ret;
1469
1470 IRBuilder<>::FastMathFlagGuard Guard(B);
1471 FastMathFlags FMF;
1472 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001473 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001474
1475 LibFunc::Func Func;
1476 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001477 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1478 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001479 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001480 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001481 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001482
1483 // log(exp2(y)) -> y*log(2)
1484 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1485 TLI->has(Func) && Func == LibFunc::exp2)
1486 return B.CreateFMul(
1487 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001488 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001489 Callee->getName(), B, Callee->getAttributes()),
1490 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001491 return Ret;
1492}
1493
Sanjay Patelc699a612014-10-16 18:48:17 +00001494Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1495 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001496 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1497 return nullptr;
Sanjay Patelbd2dc672016-01-20 17:41:14 +00001498
Sanjay Patelc699a612014-10-16 18:48:17 +00001499 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001500 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1501 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001502 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001503
1504 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001505 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001506
Sanjay Patelc2d64612016-01-06 20:52:21 +00001507 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1508 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1509 return Ret;
1510
1511 // We're looking for a repeated factor in a multiplication tree,
1512 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001513 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001514 Value *Op0 = I->getOperand(0);
1515 Value *Op1 = I->getOperand(1);
1516 Value *RepeatOp = nullptr;
1517 Value *OtherOp = nullptr;
1518 if (Op0 == Op1) {
1519 // Simple match: the operands of the multiply are identical.
1520 RepeatOp = Op0;
1521 } else {
1522 // Look for a more complicated pattern: one of the operands is itself
1523 // a multiply, so search for a common factor in that multiply.
1524 // Note: We don't bother looking any deeper than this first level or for
1525 // variations of this pattern because instcombine's visitFMUL and/or the
1526 // reassociation pass should give us this form.
1527 Value *OtherMul0, *OtherMul1;
1528 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1529 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001530 if (OtherMul0 == OtherMul1 &&
1531 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001532 // Matched: sqrt((x * x) * z)
1533 RepeatOp = OtherMul0;
1534 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001535 }
1536 }
1537 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001538 if (!RepeatOp)
1539 return Ret;
1540
1541 // Fast math flags for any created instructions should match the sqrt
1542 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001543 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001544 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001545
Sanjay Patelc2d64612016-01-06 20:52:21 +00001546 // If we found a repeated factor, hoist it out of the square root and
1547 // replace it with the fabs of that factor.
1548 Module *M = Callee->getParent();
1549 Type *ArgType = I->getType();
1550 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1551 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1552 if (OtherOp) {
1553 // If we found a non-repeated factor, we still need to get its square
1554 // root. We then multiply that by the value that was simplified out
1555 // of the square root calculation.
1556 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1557 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1558 return B.CreateFMul(FabsCall, SqrtCall);
1559 }
1560 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001561}
1562
Sanjay Patelcddcd722016-01-06 19:23:35 +00001563// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001564Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1565 Function *Callee = CI->getCalledFunction();
Sanjay Patel9beec212016-01-21 22:58:01 +00001566 if (!matchesFPLibFunctionSignature(Callee, 1, false))
1567 return nullptr;
1568
Davide Italiano51507d22015-11-04 23:36:56 +00001569 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001570 StringRef Name = Callee->getName();
1571 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001572 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001573
Davide Italiano51507d22015-11-04 23:36:56 +00001574 Value *Op1 = CI->getArgOperand(0);
1575 auto *OpC = dyn_cast<CallInst>(Op1);
1576 if (!OpC)
1577 return Ret;
1578
Sanjay Patelcddcd722016-01-06 19:23:35 +00001579 // Both calls must allow unsafe optimizations in order to remove them.
1580 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1581 return Ret;
1582
Davide Italiano51507d22015-11-04 23:36:56 +00001583 // tan(atan(x)) -> x
1584 // tanf(atanf(x)) -> x
1585 // tanl(atanl(x)) -> x
1586 LibFunc::Func Func;
1587 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001588 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001589 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1590 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1591 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1592 Ret = OpC->getArgOperand(0);
1593 return Ret;
1594}
1595
Sanjay Patel57747212016-01-21 23:38:43 +00001596static bool isTrigLibCall(CallInst *CI) {
1597 Function *Callee = CI->getCalledFunction();
1598 FunctionType *FT = Callee->getFunctionType();
1599
1600 // We can only hope to do anything useful if we can ignore things like errno
1601 // and floating-point exceptions.
1602 bool AttributesSafe =
1603 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1604
1605 // Other than that we need float(float) or double(double)
1606 return AttributesSafe && FT->getNumParams() == 1 &&
1607 FT->getReturnType() == FT->getParamType(0) &&
1608 (FT->getParamType(0)->isFloatTy() ||
1609 FT->getParamType(0)->isDoubleTy());
1610}
1611
Chris Bienemanad070d02014-09-17 20:55:46 +00001612static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1613 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001614 Value *&SinCos) {
1615 Type *ArgTy = Arg->getType();
1616 Type *ResTy;
1617 StringRef Name;
1618
1619 Triple T(OrigCallee->getParent()->getTargetTriple());
1620 if (UseFloat) {
1621 Name = "__sincospif_stret";
1622
1623 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1624 // x86_64 can't use {float, float} since that would be returned in both
1625 // xmm0 and xmm1, which isn't what a real struct would do.
1626 ResTy = T.getArch() == Triple::x86_64
1627 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1628 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1629 } else {
1630 Name = "__sincospi_stret";
1631 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1632 }
1633
1634 Module *M = OrigCallee->getParent();
1635 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1636 ResTy, ArgTy, nullptr);
1637
1638 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1639 // If the argument is an instruction, it must dominate all uses so put our
1640 // sincos call there.
1641 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1642 } else {
1643 // Otherwise (e.g. for a constant) the beginning of the function is as
1644 // good a place as any.
1645 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1646 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1647 }
1648
1649 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1650
1651 if (SinCos->getType()->isStructTy()) {
1652 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1653 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1654 } else {
1655 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1656 "sinpi");
1657 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1658 "cospi");
1659 }
1660}
Chris Bienemanad070d02014-09-17 20:55:46 +00001661
1662Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001663 // Make sure the prototype is as expected, otherwise the rest of the
1664 // function is probably invalid and likely to abort.
1665 if (!isTrigLibCall(CI))
1666 return nullptr;
1667
1668 Value *Arg = CI->getArgOperand(0);
1669 SmallVector<CallInst *, 1> SinCalls;
1670 SmallVector<CallInst *, 1> CosCalls;
1671 SmallVector<CallInst *, 1> SinCosCalls;
1672
1673 bool IsFloat = Arg->getType()->isFloatTy();
1674
1675 // Look for all compatible sinpi, cospi and sincospi calls with the same
1676 // argument. If there are enough (in some sense) we can make the
1677 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001678 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001680 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001681
1682 // It's only worthwhile if both sinpi and cospi are actually used.
1683 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1684 return nullptr;
1685
1686 Value *Sin, *Cos, *SinCos;
1687 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1688
1689 replaceTrigInsts(SinCalls, Sin);
1690 replaceTrigInsts(CosCalls, Cos);
1691 replaceTrigInsts(SinCosCalls, SinCos);
1692
1693 return nullptr;
1694}
1695
David Majnemerabae6b52016-03-19 04:53:02 +00001696void LibCallSimplifier::classifyArgUse(
1697 Value *Val, Function *F, bool IsFloat,
1698 SmallVectorImpl<CallInst *> &SinCalls,
1699 SmallVectorImpl<CallInst *> &CosCalls,
1700 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001701 CallInst *CI = dyn_cast<CallInst>(Val);
1702
1703 if (!CI)
1704 return;
1705
David Majnemerabae6b52016-03-19 04:53:02 +00001706 // Don't consider calls in other functions.
1707 if (CI->getFunction() != F)
1708 return;
1709
Chris Bienemanad070d02014-09-17 20:55:46 +00001710 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001712 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1713 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001714 return;
1715
1716 if (IsFloat) {
1717 if (Func == LibFunc::sinpif)
1718 SinCalls.push_back(CI);
1719 else if (Func == LibFunc::cospif)
1720 CosCalls.push_back(CI);
1721 else if (Func == LibFunc::sincospif_stret)
1722 SinCosCalls.push_back(CI);
1723 } else {
1724 if (Func == LibFunc::sinpi)
1725 SinCalls.push_back(CI);
1726 else if (Func == LibFunc::cospi)
1727 CosCalls.push_back(CI);
1728 else if (Func == LibFunc::sincospi_stret)
1729 SinCosCalls.push_back(CI);
1730 }
1731}
1732
1733void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1734 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001735 for (CallInst *C : Calls)
1736 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001737}
1738
Meador Inge7415f842012-11-25 20:45:27 +00001739//===----------------------------------------------------------------------===//
1740// Integer Library Call Optimizations
1741//===----------------------------------------------------------------------===//
1742
Davide Italiano396f3ee2015-10-31 23:17:45 +00001743static bool checkIntUnaryReturnAndParam(Function *Callee) {
1744 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001745 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1746 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001747}
1748
Chris Bienemanad070d02014-09-17 20:55:46 +00001749Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1750 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001751 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001753 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001754
Chris Bienemanad070d02014-09-17 20:55:46 +00001755 // Constant fold.
1756 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1757 if (CI->isZero()) // ffs(0) -> 0.
1758 return B.getInt32(0);
1759 // ffs(c) -> cttz(c)+1
1760 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001761 }
Meador Inge7415f842012-11-25 20:45:27 +00001762
Chris Bienemanad070d02014-09-17 20:55:46 +00001763 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1764 Type *ArgType = Op->getType();
1765 Value *F =
1766 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001767 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1769 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001770
Chris Bienemanad070d02014-09-17 20:55:46 +00001771 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1772 return B.CreateSelect(Cond, V, B.getInt32(0));
1773}
Meador Ingea0b6d872012-11-26 00:24:07 +00001774
Chris Bienemanad070d02014-09-17 20:55:46 +00001775Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1776 Function *Callee = CI->getCalledFunction();
1777 FunctionType *FT = Callee->getFunctionType();
1778 // We require integer(integer) where the types agree.
1779 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1780 FT->getParamType(0) != FT->getReturnType())
1781 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001782
Chris Bienemanad070d02014-09-17 20:55:46 +00001783 // abs(x) -> x >s -1 ? x : -x
1784 Value *Op = CI->getArgOperand(0);
1785 Value *Pos =
1786 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1787 Value *Neg = B.CreateNeg(Op, "neg");
1788 return B.CreateSelect(Pos, Op, Neg);
1789}
Meador Inge9a59ab62012-11-26 02:31:59 +00001790
Chris Bienemanad070d02014-09-17 20:55:46 +00001791Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001792 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001794
Chris Bienemanad070d02014-09-17 20:55:46 +00001795 // isdigit(c) -> (c-'0') <u 10
1796 Value *Op = CI->getArgOperand(0);
1797 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1798 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1799 return B.CreateZExt(Op, CI->getType());
1800}
Meador Ingea62a39e2012-11-26 03:10:07 +00001801
Chris Bienemanad070d02014-09-17 20:55:46 +00001802Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001803 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001804 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001805
Chris Bienemanad070d02014-09-17 20:55:46 +00001806 // isascii(c) -> c <u 128
1807 Value *Op = CI->getArgOperand(0);
1808 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1809 return B.CreateZExt(Op, CI->getType());
1810}
1811
1812Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001813 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 return nullptr;
1815
1816 // toascii(c) -> c & 0x7f
1817 return B.CreateAnd(CI->getArgOperand(0),
1818 ConstantInt::get(CI->getType(), 0x7F));
1819}
Meador Inge604937d2012-11-26 03:38:52 +00001820
Meador Inge08ca1152012-11-26 20:37:20 +00001821//===----------------------------------------------------------------------===//
1822// Formatting and IO Library Call Optimizations
1823//===----------------------------------------------------------------------===//
1824
Chris Bienemanad070d02014-09-17 20:55:46 +00001825static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001826
Chris Bienemanad070d02014-09-17 20:55:46 +00001827Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1828 int StreamArg) {
1829 // Error reporting calls should be cold, mark them as such.
1830 // This applies even to non-builtin calls: it is only a hint and applies to
1831 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001832
Chris Bienemanad070d02014-09-17 20:55:46 +00001833 // This heuristic was suggested in:
1834 // Improving Static Branch Prediction in a Compiler
1835 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1836 // Proceedings of PACT'98, Oct. 1998, IEEE
1837 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001838
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 if (!CI->hasFnAttr(Attribute::Cold) &&
1840 isReportingError(Callee, CI, StreamArg)) {
1841 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1842 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001843
Chris Bienemanad070d02014-09-17 20:55:46 +00001844 return nullptr;
1845}
1846
1847static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001848 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001849 return false;
1850
1851 if (StreamArg < 0)
1852 return true;
1853
1854 // These functions might be considered cold, but only if their stream
1855 // argument is stderr.
1856
1857 if (StreamArg >= (int)CI->getNumArgOperands())
1858 return false;
1859 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1860 if (!LI)
1861 return false;
1862 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1863 if (!GV || !GV->isDeclaration())
1864 return false;
1865 return GV->getName() == "stderr";
1866}
1867
1868Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1869 // Check for a fixed format string.
1870 StringRef FormatStr;
1871 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001872 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001873
Chris Bienemanad070d02014-09-17 20:55:46 +00001874 // Empty format string -> noop.
1875 if (FormatStr.empty()) // Tolerate printf's declared void.
1876 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001877
Chris Bienemanad070d02014-09-17 20:55:46 +00001878 // Do not do any of the following transformations if the printf return value
1879 // is used, in general the printf return value is not compatible with either
1880 // putchar() or puts().
1881 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001882 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001883
1884 // printf("x") -> putchar('x'), even for '%'.
Davide Italianod4f5a052016-04-03 01:46:52 +00001885 if (FormatStr.size() == 1)
1886 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001887
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001888 // printf("%s", "a") --> putchar('a')
1889 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1890 StringRef ChrStr;
1891 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1892 return nullptr;
1893 if (ChrStr.size() != 1)
1894 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001895 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001896 }
1897
Chris Bienemanad070d02014-09-17 20:55:46 +00001898 // printf("foo\n") --> puts("foo")
1899 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1900 FormatStr.find('%') == StringRef::npos) { // No format characters.
1901 // Create a string literal with no \n on it. We expect the constant merge
1902 // pass to be run after this pass, to merge duplicate strings.
1903 FormatStr = FormatStr.drop_back();
1904 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001905 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001906 }
Meador Inge08ca1152012-11-26 20:37:20 +00001907
Chris Bienemanad070d02014-09-17 20:55:46 +00001908 // Optimize specific format strings.
1909 // printf("%c", chr) --> putchar(chr)
1910 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001911 CI->getArgOperand(1)->getType()->isIntegerTy())
1912 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001913
1914 // printf("%s\n", str) --> puts(str)
1915 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001916 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001917 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001918 return nullptr;
1919}
1920
1921Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1922
1923 Function *Callee = CI->getCalledFunction();
1924 // Require one fixed pointer argument and an integer/void result.
1925 FunctionType *FT = Callee->getFunctionType();
1926 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1927 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1928 return nullptr;
1929
1930 if (Value *V = optimizePrintFString(CI, B)) {
1931 return V;
1932 }
1933
1934 // printf(format, ...) -> iprintf(format, ...) if no floating point
1935 // arguments.
1936 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1937 Module *M = B.GetInsertBlock()->getParent()->getParent();
1938 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001939 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001940 CallInst *New = cast<CallInst>(CI->clone());
1941 New->setCalledFunction(IPrintFFn);
1942 B.Insert(New);
1943 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001944 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001945 return nullptr;
1946}
Meador Inge08ca1152012-11-26 20:37:20 +00001947
Chris Bienemanad070d02014-09-17 20:55:46 +00001948Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1949 // Check for a fixed format string.
1950 StringRef FormatStr;
1951 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001952 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001953
Chris Bienemanad070d02014-09-17 20:55:46 +00001954 // If we just have a format string (nothing else crazy) transform it.
1955 if (CI->getNumArgOperands() == 2) {
1956 // Make sure there's no % in the constant array. We could try to handle
1957 // %% -> % in the future if we cared.
1958 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1959 if (FormatStr[i] == '%')
1960 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001961
Chris Bienemanad070d02014-09-17 20:55:46 +00001962 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001963 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1964 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1965 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001966 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001967 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001968 }
Meador Ingef8e72502012-11-29 15:45:43 +00001969
Chris Bienemanad070d02014-09-17 20:55:46 +00001970 // The remaining optimizations require the format string to be "%s" or "%c"
1971 // and have an extra operand.
1972 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1973 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001974 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001975
Chris Bienemanad070d02014-09-17 20:55:46 +00001976 // Decode the second character of the format string.
1977 if (FormatStr[1] == 'c') {
1978 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1979 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1980 return nullptr;
1981 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001982 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001983 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001984 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001985 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001986
Chris Bienemanad070d02014-09-17 20:55:46 +00001987 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001988 }
1989
Chris Bienemanad070d02014-09-17 20:55:46 +00001990 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001991 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1992 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1993 return nullptr;
1994
Sanjay Pateld3112a52016-01-19 19:46:10 +00001995 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001996 if (!Len)
1997 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001998 Value *IncLen =
1999 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
2000 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002001
2002 // The sprintf result is the unincremented number of bytes in the string.
2003 return B.CreateIntCast(Len, CI->getType(), false);
2004 }
2005 return nullptr;
2006}
2007
2008Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2009 Function *Callee = CI->getCalledFunction();
2010 // Require two fixed pointer arguments and an integer result.
2011 FunctionType *FT = Callee->getFunctionType();
2012 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2013 !FT->getParamType(1)->isPointerTy() ||
2014 !FT->getReturnType()->isIntegerTy())
2015 return nullptr;
2016
2017 if (Value *V = optimizeSPrintFString(CI, B)) {
2018 return V;
2019 }
2020
2021 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2022 // point arguments.
2023 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
2024 Module *M = B.GetInsertBlock()->getParent()->getParent();
2025 Constant *SIPrintFFn =
2026 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2027 CallInst *New = cast<CallInst>(CI->clone());
2028 New->setCalledFunction(SIPrintFFn);
2029 B.Insert(New);
2030 return New;
2031 }
2032 return nullptr;
2033}
2034
2035Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2036 optimizeErrorReporting(CI, B, 0);
2037
2038 // All the optimizations depend on the format string.
2039 StringRef FormatStr;
2040 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2041 return nullptr;
2042
2043 // Do not do any of the following transformations if the fprintf return
2044 // value is used, in general the fprintf return value is not compatible
2045 // with fwrite(), fputc() or fputs().
2046 if (!CI->use_empty())
2047 return nullptr;
2048
2049 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2050 if (CI->getNumArgOperands() == 2) {
2051 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
2052 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
2053 return nullptr; // We found a format specifier.
2054
Sanjay Pateld3112a52016-01-19 19:46:10 +00002055 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002056 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002057 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002058 CI->getArgOperand(0), B, DL, TLI);
2059 }
2060
2061 // The remaining optimizations require the format string to be "%s" or "%c"
2062 // and have an extra operand.
2063 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2064 CI->getNumArgOperands() < 3)
2065 return nullptr;
2066
2067 // Decode the second character of the format string.
2068 if (FormatStr[1] == 'c') {
2069 // fprintf(F, "%c", chr) --> fputc(chr, F)
2070 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2071 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002072 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002073 }
2074
2075 if (FormatStr[1] == 's') {
2076 // fprintf(F, "%s", str) --> fputs(str, F)
2077 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2078 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002079 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002080 }
2081 return nullptr;
2082}
2083
2084Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2085 Function *Callee = CI->getCalledFunction();
2086 // Require two fixed paramters as pointers and integer result.
2087 FunctionType *FT = Callee->getFunctionType();
2088 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2089 !FT->getParamType(1)->isPointerTy() ||
2090 !FT->getReturnType()->isIntegerTy())
2091 return nullptr;
2092
2093 if (Value *V = optimizeFPrintFString(CI, B)) {
2094 return V;
2095 }
2096
2097 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2098 // floating point arguments.
2099 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
2100 Module *M = B.GetInsertBlock()->getParent()->getParent();
2101 Constant *FIPrintFFn =
2102 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2103 CallInst *New = cast<CallInst>(CI->clone());
2104 New->setCalledFunction(FIPrintFFn);
2105 B.Insert(New);
2106 return New;
2107 }
2108 return nullptr;
2109}
2110
2111Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2112 optimizeErrorReporting(CI, B, 3);
2113
2114 Function *Callee = CI->getCalledFunction();
2115 // Require a pointer, an integer, an integer, a pointer, returning integer.
2116 FunctionType *FT = Callee->getFunctionType();
2117 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
2118 !FT->getParamType(1)->isIntegerTy() ||
2119 !FT->getParamType(2)->isIntegerTy() ||
2120 !FT->getParamType(3)->isPointerTy() ||
2121 !FT->getReturnType()->isIntegerTy())
2122 return nullptr;
2123
2124 // Get the element size and count.
2125 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2126 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
2127 if (!SizeC || !CountC)
2128 return nullptr;
2129 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
2130
2131 // If this is writing zero records, remove the call (it's a noop).
2132 if (Bytes == 0)
2133 return ConstantInt::get(CI->getType(), 0);
2134
2135 // If this is writing one byte, turn it into fputc.
2136 // This optimisation is only valid, if the return value is unused.
2137 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00002138 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2139 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002140 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2141 }
2142
2143 return nullptr;
2144}
2145
2146Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2147 optimizeErrorReporting(CI, B, 1);
2148
2149 Function *Callee = CI->getCalledFunction();
2150
Chris Bienemanad070d02014-09-17 20:55:46 +00002151 // Require two pointers. Also, we can't optimize if return value is used.
2152 FunctionType *FT = Callee->getFunctionType();
2153 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
2154 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
2155 return nullptr;
2156
2157 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2158 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2159 if (!Len)
2160 return nullptr;
2161
2162 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002163 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002164 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002165 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002166 CI->getArgOperand(1), B, DL, TLI);
2167}
2168
2169Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2170 Function *Callee = CI->getCalledFunction();
2171 // Require one fixed pointer argument and an integer/void result.
2172 FunctionType *FT = Callee->getFunctionType();
2173 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2174 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2175 return nullptr;
2176
2177 // Check for a constant string.
2178 StringRef Str;
2179 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2180 return nullptr;
2181
2182 if (Str.empty() && CI->use_empty()) {
2183 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002184 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002185 if (CI->use_empty() || !Res)
2186 return Res;
2187 return B.CreateIntCast(Res, CI->getType(), true);
2188 }
2189
2190 return nullptr;
2191}
2192
2193bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002194 LibFunc::Func Func;
2195 SmallString<20> FloatFuncName = FuncName;
2196 FloatFuncName += 'f';
2197 if (TLI->getLibFunc(FloatFuncName, Func))
2198 return TLI->has(Func);
2199 return false;
2200}
Meador Inge7fb2f732012-10-13 16:45:32 +00002201
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002202Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2203 IRBuilder<> &Builder) {
2204 LibFunc::Func Func;
2205 Function *Callee = CI->getCalledFunction();
2206 StringRef FuncName = Callee->getName();
2207
2208 // Check for string/memory library functions.
2209 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2210 // Make sure we never change the calling convention.
2211 assert((ignoreCallingConv(Func) ||
2212 CI->getCallingConv() == llvm::CallingConv::C) &&
2213 "Optimizing string/memory libcall would change the calling convention");
2214 switch (Func) {
2215 case LibFunc::strcat:
2216 return optimizeStrCat(CI, Builder);
2217 case LibFunc::strncat:
2218 return optimizeStrNCat(CI, Builder);
2219 case LibFunc::strchr:
2220 return optimizeStrChr(CI, Builder);
2221 case LibFunc::strrchr:
2222 return optimizeStrRChr(CI, Builder);
2223 case LibFunc::strcmp:
2224 return optimizeStrCmp(CI, Builder);
2225 case LibFunc::strncmp:
2226 return optimizeStrNCmp(CI, Builder);
2227 case LibFunc::strcpy:
2228 return optimizeStrCpy(CI, Builder);
2229 case LibFunc::stpcpy:
2230 return optimizeStpCpy(CI, Builder);
2231 case LibFunc::strncpy:
2232 return optimizeStrNCpy(CI, Builder);
2233 case LibFunc::strlen:
2234 return optimizeStrLen(CI, Builder);
2235 case LibFunc::strpbrk:
2236 return optimizeStrPBrk(CI, Builder);
2237 case LibFunc::strtol:
2238 case LibFunc::strtod:
2239 case LibFunc::strtof:
2240 case LibFunc::strtoul:
2241 case LibFunc::strtoll:
2242 case LibFunc::strtold:
2243 case LibFunc::strtoull:
2244 return optimizeStrTo(CI, Builder);
2245 case LibFunc::strspn:
2246 return optimizeStrSpn(CI, Builder);
2247 case LibFunc::strcspn:
2248 return optimizeStrCSpn(CI, Builder);
2249 case LibFunc::strstr:
2250 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002251 case LibFunc::memchr:
2252 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002253 case LibFunc::memcmp:
2254 return optimizeMemCmp(CI, Builder);
2255 case LibFunc::memcpy:
2256 return optimizeMemCpy(CI, Builder);
2257 case LibFunc::memmove:
2258 return optimizeMemMove(CI, Builder);
2259 case LibFunc::memset:
2260 return optimizeMemSet(CI, Builder);
2261 default:
2262 break;
2263 }
2264 }
2265 return nullptr;
2266}
2267
Chris Bienemanad070d02014-09-17 20:55:46 +00002268Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2269 if (CI->isNoBuiltin())
2270 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002271
Meador Inge20255ef2013-03-12 00:08:29 +00002272 LibFunc::Func Func;
2273 Function *Callee = CI->getCalledFunction();
2274 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002275
2276 SmallVector<OperandBundleDef, 2> OpBundles;
2277 CI->getOperandBundlesAsDefs(OpBundles);
2278 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Chris Bienemanad070d02014-09-17 20:55:46 +00002279 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002280
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002281 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002282 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2283 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002284 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002285 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002286
Sanjay Patel848309d2014-10-23 21:52:45 +00002287 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002288 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002289 if (!isCallingConvC)
2290 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002291 switch (II->getIntrinsicID()) {
2292 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002293 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002294 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002295 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002296 case Intrinsic::fabs:
2297 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002298 case Intrinsic::log:
2299 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002300 case Intrinsic::sqrt:
2301 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002302 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002303 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002304 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002305 }
2306 }
2307
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002308 // Also try to simplify calls to fortified library functions.
2309 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2310 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002311 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002312 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2313 // Use an IR Builder from SimplifiedCI if available instead of CI
2314 // to guarantee we reach all uses we might replace later on.
2315 IRBuilder<> TmpBuilder(SimplifiedCI);
2316 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002317 // If we were able to further simplify, remove the now redundant call.
2318 SimplifiedCI->replaceAllUsesWith(V);
2319 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002320 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002321 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002322 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002323 return SimplifiedFortifiedCI;
2324 }
2325
Meador Inge20255ef2013-03-12 00:08:29 +00002326 // Then check for known library functions.
2327 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002328 // We never change the calling convention.
2329 if (!ignoreCallingConv(Func) && !isCallingConvC)
2330 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002331 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2332 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002333 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002334 case LibFunc::cosf:
2335 case LibFunc::cos:
2336 case LibFunc::cosl:
2337 return optimizeCos(CI, Builder);
2338 case LibFunc::sinpif:
2339 case LibFunc::sinpi:
2340 case LibFunc::cospif:
2341 case LibFunc::cospi:
2342 return optimizeSinCosPi(CI, Builder);
2343 case LibFunc::powf:
2344 case LibFunc::pow:
2345 case LibFunc::powl:
2346 return optimizePow(CI, Builder);
2347 case LibFunc::exp2l:
2348 case LibFunc::exp2:
2349 case LibFunc::exp2f:
2350 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002351 case LibFunc::fabsf:
2352 case LibFunc::fabs:
2353 case LibFunc::fabsl:
2354 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002355 case LibFunc::sqrtf:
2356 case LibFunc::sqrt:
2357 case LibFunc::sqrtl:
2358 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002359 case LibFunc::ffs:
2360 case LibFunc::ffsl:
2361 case LibFunc::ffsll:
2362 return optimizeFFS(CI, Builder);
2363 case LibFunc::abs:
2364 case LibFunc::labs:
2365 case LibFunc::llabs:
2366 return optimizeAbs(CI, Builder);
2367 case LibFunc::isdigit:
2368 return optimizeIsDigit(CI, Builder);
2369 case LibFunc::isascii:
2370 return optimizeIsAscii(CI, Builder);
2371 case LibFunc::toascii:
2372 return optimizeToAscii(CI, Builder);
2373 case LibFunc::printf:
2374 return optimizePrintF(CI, Builder);
2375 case LibFunc::sprintf:
2376 return optimizeSPrintF(CI, Builder);
2377 case LibFunc::fprintf:
2378 return optimizeFPrintF(CI, Builder);
2379 case LibFunc::fwrite:
2380 return optimizeFWrite(CI, Builder);
2381 case LibFunc::fputs:
2382 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002383 case LibFunc::log:
2384 case LibFunc::log10:
2385 case LibFunc::log1p:
2386 case LibFunc::log2:
2387 case LibFunc::logb:
2388 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002389 case LibFunc::puts:
2390 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002391 case LibFunc::tan:
2392 case LibFunc::tanf:
2393 case LibFunc::tanl:
2394 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002395 case LibFunc::perror:
2396 return optimizeErrorReporting(CI, Builder);
2397 case LibFunc::vfprintf:
2398 case LibFunc::fiprintf:
2399 return optimizeErrorReporting(CI, Builder, 0);
2400 case LibFunc::fputc:
2401 return optimizeErrorReporting(CI, Builder, 1);
2402 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002403 case LibFunc::floor:
2404 case LibFunc::rint:
2405 case LibFunc::round:
2406 case LibFunc::nearbyint:
2407 case LibFunc::trunc:
2408 if (hasFloatVersion(FuncName))
2409 return optimizeUnaryDoubleFP(CI, Builder, false);
2410 return nullptr;
2411 case LibFunc::acos:
2412 case LibFunc::acosh:
2413 case LibFunc::asin:
2414 case LibFunc::asinh:
2415 case LibFunc::atan:
2416 case LibFunc::atanh:
2417 case LibFunc::cbrt:
2418 case LibFunc::cosh:
2419 case LibFunc::exp:
2420 case LibFunc::exp10:
2421 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002422 case LibFunc::sin:
2423 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002424 case LibFunc::tanh:
2425 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2426 return optimizeUnaryDoubleFP(CI, Builder, true);
2427 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002428 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002429 if (hasFloatVersion(FuncName))
2430 return optimizeBinaryDoubleFP(CI, Builder);
2431 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002432 case LibFunc::fminf:
2433 case LibFunc::fmin:
2434 case LibFunc::fminl:
2435 case LibFunc::fmaxf:
2436 case LibFunc::fmax:
2437 case LibFunc::fmaxl:
2438 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002439 default:
2440 return nullptr;
2441 }
Meador Inge20255ef2013-03-12 00:08:29 +00002442 }
Craig Topperf40110f2014-04-25 05:29:35 +00002443 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002444}
2445
Chandler Carruth92803822015-01-21 02:11:59 +00002446LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002447 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002448 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002449 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002450 Replacer(Replacer) {}
2451
2452void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2453 // Indirect through the replacer used in this instance.
2454 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002455}
2456
Meador Ingedfb08a22013-06-20 19:48:07 +00002457// TODO:
2458// Additional cases that we need to add to this file:
2459//
2460// cbrt:
2461// * cbrt(expN(X)) -> expN(x/3)
2462// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002463// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002464//
2465// exp, expf, expl:
2466// * exp(log(x)) -> x
2467//
2468// log, logf, logl:
2469// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002470// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002471// * log(exp10(y)) -> y*log(10)
2472// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002473//
2474// lround, lroundf, lroundl:
2475// * lround(cnst) -> cnst'
2476//
2477// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002478// * pow(sqrt(x),y) -> pow(x,y*0.5)
2479// * pow(pow(x,y),z)-> pow(x,y*z)
2480//
2481// round, roundf, roundl:
2482// * round(cnst) -> cnst'
2483//
2484// signbit:
2485// * signbit(cnst) -> cnst'
2486// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2487//
2488// sqrt, sqrtf, sqrtl:
2489// * sqrt(expN(x)) -> expN(x*0.5)
2490// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2491// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2492//
Meador Ingedfb08a22013-06-20 19:48:07 +00002493// trunc, truncf, truncl:
2494// * trunc(cnst) -> cnst'
2495//
2496//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002497
2498//===----------------------------------------------------------------------===//
2499// Fortified Library Call Optimizations
2500//===----------------------------------------------------------------------===//
2501
2502bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2503 unsigned ObjSizeOp,
2504 unsigned SizeOp,
2505 bool isString) {
2506 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2507 return true;
2508 if (ConstantInt *ObjSizeCI =
2509 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2510 if (ObjSizeCI->isAllOnesValue())
2511 return true;
2512 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2513 if (OnlyLowerUnknownSize)
2514 return false;
2515 if (isString) {
2516 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2517 // If the length is 0 we don't know how long it is and so we can't
2518 // remove the check.
2519 if (Len == 0)
2520 return false;
2521 return ObjSizeCI->getZExtValue() >= Len;
2522 }
2523 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2524 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2525 }
2526 return false;
2527}
2528
Sanjay Pateld707db92015-12-31 16:10:49 +00002529Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2530 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002531 Function *Callee = CI->getCalledFunction();
2532
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002533 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002534 return nullptr;
2535
2536 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2537 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002538 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002539 return CI->getArgOperand(0);
2540 }
2541 return nullptr;
2542}
2543
Sanjay Pateld707db92015-12-31 16:10:49 +00002544Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2545 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002546 Function *Callee = CI->getCalledFunction();
2547
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002548 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002549 return nullptr;
2550
2551 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2552 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002553 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002554 return CI->getArgOperand(0);
2555 }
2556 return nullptr;
2557}
2558
Sanjay Pateld707db92015-12-31 16:10:49 +00002559Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2560 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002561 Function *Callee = CI->getCalledFunction();
2562
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002563 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002564 return nullptr;
2565
Sanjay Patel980b2802016-01-26 16:17:24 +00002566 // TODO: Try foldMallocMemset() here.
2567
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002568 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2569 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2570 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2571 return CI->getArgOperand(0);
2572 }
2573 return nullptr;
2574}
2575
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002576Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2577 IRBuilder<> &B,
2578 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002579 Function *Callee = CI->getCalledFunction();
2580 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002581 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002582
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002583 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002584 return nullptr;
2585
2586 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2587 *ObjSize = CI->getArgOperand(2);
2588
2589 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002590 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002591 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002592 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002593 }
2594
2595 // If a) we don't have any length information, or b) we know this will
2596 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2597 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2598 // TODO: It might be nice to get a maximum length out of the possible
2599 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002600 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002601 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002602
David Blaikie65fab6d2015-04-03 21:32:06 +00002603 if (OnlyLowerUnknownSize)
2604 return nullptr;
2605
2606 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2607 uint64_t Len = GetStringLength(Src);
2608 if (Len == 0)
2609 return nullptr;
2610
2611 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2612 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002613 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002614 // If the function was an __stpcpy_chk, and we were able to fold it into
2615 // a __memcpy_chk, we still need to return the correct end pointer.
2616 if (Ret && Func == LibFunc::stpcpy_chk)
2617 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2618 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002619}
2620
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002621Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2622 IRBuilder<> &B,
2623 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002624 Function *Callee = CI->getCalledFunction();
2625 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002626
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002627 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002628 return nullptr;
2629 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002630 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002631 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002632 return Ret;
2633 }
2634 return nullptr;
2635}
2636
2637Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002638 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2639 // Some clang users checked for _chk libcall availability using:
2640 // __has_builtin(__builtin___memcpy_chk)
2641 // When compiling with -fno-builtin, this is always true.
2642 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2643 // end up with fortified libcalls, which isn't acceptable in a freestanding
2644 // environment which only provides their non-fortified counterparts.
2645 //
2646 // Until we change clang and/or teach external users to check for availability
2647 // differently, disregard the "nobuiltin" attribute and TLI::has.
2648 //
2649 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002650
2651 LibFunc::Func Func;
2652 Function *Callee = CI->getCalledFunction();
2653 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002654
2655 SmallVector<OperandBundleDef, 2> OpBundles;
2656 CI->getOperandBundlesAsDefs(OpBundles);
2657 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002658 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2659
2660 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002661 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002662 return nullptr;
2663
2664 // We never change the calling convention.
2665 if (!ignoreCallingConv(Func) && !isCallingConvC)
2666 return nullptr;
2667
2668 switch (Func) {
2669 case LibFunc::memcpy_chk:
2670 return optimizeMemCpyChk(CI, Builder);
2671 case LibFunc::memmove_chk:
2672 return optimizeMemMoveChk(CI, Builder);
2673 case LibFunc::memset_chk:
2674 return optimizeMemSetChk(CI, Builder);
2675 case LibFunc::stpcpy_chk:
2676 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002677 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002678 case LibFunc::stpncpy_chk:
2679 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002680 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002681 default:
2682 break;
2683 }
2684 return nullptr;
2685}
2686
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002687FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2688 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2689 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}