blob: 763e3c05a9daeb6a91c536421800838292e9587c [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"
Meador Ingedf796f82012-10-13 16:45:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000030#include "llvm/IR/PatternMatch.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000031#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000041 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000043
Sanjay Patela92fa442014-10-22 15:29:23 +000044static cl::opt<bool>
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
Chris Bienemanad070d02014-09-17 20:55:46 +000055static bool ignoreCallingConv(LibFunc::Func Func) {
56 switch (Func) {
57 case LibFunc::abs:
58 case LibFunc::labs:
59 case LibFunc::llabs:
60 case LibFunc::strlen:
61 return true;
62 default:
63 return false;
64 }
Chris Bienemancf93cbb2014-09-17 21:06:59 +000065 llvm_unreachable("All cases should be covered in the switch.");
Chris Bienemanad070d02014-09-17 20:55:46 +000066}
67
Meador Inged589ac62012-10-31 03:33:06 +000068/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
69/// value is equal or not-equal to zero.
70static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000071 for (User *U : V->users()) {
72 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000073 if (IC->isEquality())
74 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
75 if (C->isNullValue())
76 continue;
77 // Unknown instruction.
78 return false;
79 }
80 return true;
81}
82
Meador Inge56edbc92012-11-11 03:51:48 +000083/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
84/// comparisons with With.
85static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000086 for (User *U : V->users()) {
87 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000088 if (IC->isEquality() && IC->getOperand(1) == With)
89 continue;
90 // Unknown instruction.
91 return false;
92 }
93 return true;
94}
95
Meador Inge08ca1152012-11-26 20:37:20 +000096static bool callHasFloatingPointArgument(const CallInst *CI) {
97 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
98 it != e; ++it) {
99 if ((*it)->getType()->isFloatingPointTy())
100 return true;
101 }
102 return false;
103}
104
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000105/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000106/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000107static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
108 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
109 LibFunc::Func LongDoubleFn) {
110 switch (Ty->getTypeID()) {
111 case Type::FloatTyID:
112 return TLI->has(FloatFn);
113 case Type::DoubleTyID:
114 return TLI->has(DoubleFn);
115 default:
116 return TLI->has(LongDoubleFn);
117 }
118}
119
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000120/// \brief Returns whether \p F matches the signature expected for the
121/// string/memory copying library function \p Func.
122/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
123/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000124static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
125 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000126 FunctionType *FT = F->getFunctionType();
127 LLVMContext &Context = F->getContext();
128 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000129 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000130 unsigned NumParams = FT->getNumParams();
131
132 // All string libfuncs return the same type as the first parameter.
133 if (FT->getReturnType() != FT->getParamType(0))
134 return false;
135
136 switch (Func) {
137 default:
138 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
139 case LibFunc::stpncpy_chk:
140 case LibFunc::strncpy_chk:
141 --NumParams; // fallthrough
142 case LibFunc::stpncpy:
143 case LibFunc::strncpy: {
144 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
145 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
146 return false;
147 break;
148 }
149 case LibFunc::strcpy_chk:
150 case LibFunc::stpcpy_chk:
151 --NumParams; // fallthrough
152 case LibFunc::stpcpy:
153 case LibFunc::strcpy: {
154 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
155 FT->getParamType(0) != PCharTy)
156 return false;
157 break;
158 }
159 case LibFunc::memmove_chk:
160 case LibFunc::memcpy_chk:
161 --NumParams; // fallthrough
162 case LibFunc::memmove:
163 case LibFunc::memcpy: {
164 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
165 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
166 return false;
167 break;
168 }
169 case LibFunc::memset_chk:
170 --NumParams; // fallthrough
171 case LibFunc::memset: {
172 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
173 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
174 return false;
175 break;
176 }
177 }
178 // If this is a fortified libcall, the last parameter is a size_t.
179 if (NumParams == FT->getNumParams() - 1)
180 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
181 return true;
182}
183
Meador Inged589ac62012-10-31 03:33:06 +0000184//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000185// String and Memory Library Call Optimizations
186//===----------------------------------------------------------------------===//
187
Chris Bienemanad070d02014-09-17 20:55:46 +0000188Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
189 Function *Callee = CI->getCalledFunction();
190 // Verify the "strcat" function prototype.
191 FunctionType *FT = Callee->getFunctionType();
192 if (FT->getNumParams() != 2||
193 FT->getReturnType() != B.getInt8PtrTy() ||
194 FT->getParamType(0) != FT->getReturnType() ||
195 FT->getParamType(1) != FT->getReturnType())
196 return nullptr;
197
198 // Extract some information from the instruction
199 Value *Dst = CI->getArgOperand(0);
200 Value *Src = CI->getArgOperand(1);
201
202 // See if we can get the length of the input string.
203 uint64_t Len = GetStringLength(Src);
204 if (Len == 0)
205 return nullptr;
206 --Len; // Unbias length.
207
208 // Handle the simple, do-nothing case: strcat(x, "") -> x
209 if (Len == 0)
210 return Dst;
211
Chris Bienemanad070d02014-09-17 20:55:46 +0000212 return emitStrLenMemCpy(Src, Dst, Len, B);
213}
214
215Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
216 IRBuilder<> &B) {
217 // We need to find the end of the destination string. That's where the
218 // memory is to be moved to. We just generate a call to strlen.
219 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
220 if (!DstLen)
221 return nullptr;
222
223 // Now that we have the destination's length, we must index into the
224 // destination's pointer to get the actual memcpy destination (end of
225 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000226 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000227
228 // We have enough information to now generate the memcpy call to do the
229 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 B.CreateMemCpy(CpyDst, Src,
231 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
232 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000233 return Dst;
234}
235
236Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
237 Function *Callee = CI->getCalledFunction();
238 // Verify the "strncat" function prototype.
239 FunctionType *FT = Callee->getFunctionType();
240 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
241 FT->getParamType(0) != FT->getReturnType() ||
242 FT->getParamType(1) != FT->getReturnType() ||
243 !FT->getParamType(2)->isIntegerTy())
244 return nullptr;
245
246 // Extract some information from the instruction
247 Value *Dst = CI->getArgOperand(0);
248 Value *Src = CI->getArgOperand(1);
249 uint64_t Len;
250
251 // We don't do anything if length is not constant
252 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
253 Len = LengthArg->getZExtValue();
254 else
255 return nullptr;
256
257 // See if we can get the length of the input string.
258 uint64_t SrcLen = GetStringLength(Src);
259 if (SrcLen == 0)
260 return nullptr;
261 --SrcLen; // Unbias length.
262
263 // Handle the simple, do-nothing cases:
264 // strncat(x, "", c) -> x
265 // strncat(x, c, 0) -> x
266 if (SrcLen == 0 || Len == 0)
267 return Dst;
268
Chris Bienemanad070d02014-09-17 20:55:46 +0000269 // We don't optimize this case
270 if (Len < SrcLen)
271 return nullptr;
272
273 // strncat(x, s, c) -> strcat(x, s)
274 // s is constant so the strcat can be optimized further
275 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
276}
277
278Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
279 Function *Callee = CI->getCalledFunction();
280 // Verify the "strchr" function prototype.
281 FunctionType *FT = Callee->getFunctionType();
282 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
283 FT->getParamType(0) != FT->getReturnType() ||
284 !FT->getParamType(1)->isIntegerTy(32))
285 return nullptr;
286
287 Value *SrcStr = CI->getArgOperand(0);
288
289 // If the second operand is non-constant, see if we can compute the length
290 // of the input string and turn this into memchr.
291 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
292 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000293 uint64_t Len = GetStringLength(SrcStr);
294 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
295 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000296
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
298 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
299 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000300 }
301
Chris Bienemanad070d02014-09-17 20:55:46 +0000302 // Otherwise, the character is a constant, see if the first argument is
303 // a string literal. If so, we can constant fold.
304 StringRef Str;
305 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000307 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000308 return nullptr;
309 }
310
311 // Compute the offset, make sure to handle the case when we're searching for
312 // zero (a weird way to spell strlen).
313 size_t I = (0xFF & CharC->getSExtValue()) == 0
314 ? Str.size()
315 : Str.find(CharC->getSExtValue());
316 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
317 return Constant::getNullValue(CI->getType());
318
319 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000320 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000321}
322
323Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
324 Function *Callee = CI->getCalledFunction();
325 // Verify the "strrchr" function prototype.
326 FunctionType *FT = Callee->getFunctionType();
327 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
328 FT->getParamType(0) != FT->getReturnType() ||
329 !FT->getParamType(1)->isIntegerTy(32))
330 return nullptr;
331
332 Value *SrcStr = CI->getArgOperand(0);
333 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
334
335 // Cannot fold anything if we're not looking for a constant.
336 if (!CharC)
337 return nullptr;
338
339 StringRef Str;
340 if (!getConstantStringInfo(SrcStr, Str)) {
341 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000342 if (CharC->isZero())
343 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000344 return nullptr;
345 }
346
347 // Compute the offset.
348 size_t I = (0xFF & CharC->getSExtValue()) == 0
349 ? Str.size()
350 : Str.rfind(CharC->getSExtValue());
351 if (I == StringRef::npos) // Didn't find the char. Return null.
352 return Constant::getNullValue(CI->getType());
353
354 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000355 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000356}
357
358Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
359 Function *Callee = CI->getCalledFunction();
360 // Verify the "strcmp" function prototype.
361 FunctionType *FT = Callee->getFunctionType();
362 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
363 FT->getParamType(0) != FT->getParamType(1) ||
364 FT->getParamType(0) != B.getInt8PtrTy())
365 return nullptr;
366
367 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
368 if (Str1P == Str2P) // strcmp(x,x) -> 0
369 return ConstantInt::get(CI->getType(), 0);
370
371 StringRef Str1, Str2;
372 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
373 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
374
375 // strcmp(x, y) -> cnst (if both x and y are constant strings)
376 if (HasStr1 && HasStr2)
377 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
378
379 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
380 return B.CreateNeg(
381 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
382
383 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
384 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
385
386 // strcmp(P, "x") -> memcmp(P, "x", 2)
387 uint64_t Len1 = GetStringLength(Str1P);
388 uint64_t Len2 = GetStringLength(Str2P);
389 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000390 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000392 std::min(Len1, Len2)),
393 B, DL, TLI);
394 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000395
Chris Bienemanad070d02014-09-17 20:55:46 +0000396 return nullptr;
397}
398
399Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
400 Function *Callee = CI->getCalledFunction();
401 // Verify the "strncmp" function prototype.
402 FunctionType *FT = Callee->getFunctionType();
403 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
404 FT->getParamType(0) != FT->getParamType(1) ||
405 FT->getParamType(0) != B.getInt8PtrTy() ||
406 !FT->getParamType(2)->isIntegerTy())
407 return nullptr;
408
409 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
410 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
411 return ConstantInt::get(CI->getType(), 0);
412
413 // Get the length argument if it is constant.
414 uint64_t Length;
415 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
416 Length = LengthArg->getZExtValue();
417 else
418 return nullptr;
419
420 if (Length == 0) // strncmp(x,y,0) -> 0
421 return ConstantInt::get(CI->getType(), 0);
422
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000423 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000424 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
425
426 StringRef Str1, Str2;
427 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
428 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
429
430 // strncmp(x, y) -> cnst (if both x and y are constant strings)
431 if (HasStr1 && HasStr2) {
432 StringRef SubStr1 = Str1.substr(0, Length);
433 StringRef SubStr2 = Str2.substr(0, Length);
434 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
435 }
436
437 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
438 return B.CreateNeg(
439 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
440
441 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
442 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
443
444 return nullptr;
445}
446
447Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
448 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000449
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000450 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000451 return nullptr;
452
453 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
454 if (Dst == Src) // strcpy(x,x) -> x
455 return Src;
456
Chris Bienemanad070d02014-09-17 20:55:46 +0000457 // See if we can get the length of the input string.
458 uint64_t Len = GetStringLength(Src);
459 if (Len == 0)
460 return nullptr;
461
462 // We have enough information to now generate the memcpy call to do the
463 // copy for us. Make a memcpy to copy the nul byte with align = 1.
464 B.CreateMemCpy(Dst, Src,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000465 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000466 return Dst;
467}
468
469Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
470 Function *Callee = CI->getCalledFunction();
471 // Verify the "stpcpy" function prototype.
472 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000473
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000475 return nullptr;
476
477 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
478 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
479 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000480 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000481 }
482
483 // See if we can get the length of the input string.
484 uint64_t Len = GetStringLength(Src);
485 if (Len == 0)
486 return nullptr;
487
488 Type *PT = FT->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000490 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000491 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000492
493 // We have enough information to now generate the memcpy call to do the
494 // copy for us. Make a memcpy to copy the nul byte with align = 1.
495 B.CreateMemCpy(Dst, Src, LenV, 1);
496 return DstEnd;
497}
498
499Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
500 Function *Callee = CI->getCalledFunction();
501 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000502
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000504 return nullptr;
505
506 Value *Dst = CI->getArgOperand(0);
507 Value *Src = CI->getArgOperand(1);
508 Value *LenOp = CI->getArgOperand(2);
509
510 // See if we can get the length of the input string.
511 uint64_t SrcLen = GetStringLength(Src);
512 if (SrcLen == 0)
513 return nullptr;
514 --SrcLen;
515
516 if (SrcLen == 0) {
517 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
518 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000519 return Dst;
520 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000521
Chris Bienemanad070d02014-09-17 20:55:46 +0000522 uint64_t Len;
523 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
524 Len = LengthArg->getZExtValue();
525 else
526 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000527
Chris Bienemanad070d02014-09-17 20:55:46 +0000528 if (Len == 0)
529 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000530
Chris Bienemanad070d02014-09-17 20:55:46 +0000531 // Let strncpy handle the zero padding
532 if (Len > SrcLen + 1)
533 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000534
Chris Bienemanad070d02014-09-17 20:55:46 +0000535 Type *PT = FT->getParamType(0);
536 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000537 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000538
Chris Bienemanad070d02014-09-17 20:55:46 +0000539 return Dst;
540}
Meador Inge7fb2f732012-10-13 16:45:32 +0000541
Chris Bienemanad070d02014-09-17 20:55:46 +0000542Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
543 Function *Callee = CI->getCalledFunction();
544 FunctionType *FT = Callee->getFunctionType();
545 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
546 !FT->getReturnType()->isIntegerTy())
547 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000548
Chris Bienemanad070d02014-09-17 20:55:46 +0000549 Value *Src = CI->getArgOperand(0);
550
551 // Constant folding: strlen("xyz") -> 3
552 if (uint64_t Len = GetStringLength(Src))
553 return ConstantInt::get(CI->getType(), Len - 1);
554
555 // strlen(x?"foo":"bars") --> x ? 3 : 4
556 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
557 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
558 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
559 if (LenTrue && LenFalse) {
560 Function *Caller = CI->getParent()->getParent();
561 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
562 SI->getDebugLoc(),
563 "folded strlen(select) to select of constants");
564 return B.CreateSelect(SI->getCondition(),
565 ConstantInt::get(CI->getType(), LenTrue - 1),
566 ConstantInt::get(CI->getType(), LenFalse - 1));
567 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000568 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000569
Chris Bienemanad070d02014-09-17 20:55:46 +0000570 // strlen(x) != 0 --> *x != 0
571 // strlen(x) == 0 --> *x == 0
572 if (isOnlyUsedInZeroEqualityComparison(CI))
573 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000574
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 return nullptr;
576}
Meador Inge17418502012-10-13 16:45:37 +0000577
Chris Bienemanad070d02014-09-17 20:55:46 +0000578Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
579 Function *Callee = CI->getCalledFunction();
580 FunctionType *FT = Callee->getFunctionType();
581 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
582 FT->getParamType(1) != FT->getParamType(0) ||
583 FT->getReturnType() != FT->getParamType(0))
584 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000585
Chris Bienemanad070d02014-09-17 20:55:46 +0000586 StringRef S1, S2;
587 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
588 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000589
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000590 // strpbrk(s, "") -> nullptr
591 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000592 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
593 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000594
Chris Bienemanad070d02014-09-17 20:55:46 +0000595 // Constant folding.
596 if (HasS1 && HasS2) {
597 size_t I = S1.find_first_of(S2);
598 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000599 return Constant::getNullValue(CI->getType());
600
David Blaikie3909da72015-03-30 20:42:56 +0000601 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000602 }
Meador Inge17418502012-10-13 16:45:37 +0000603
Chris Bienemanad070d02014-09-17 20:55:46 +0000604 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 if (HasS2 && S2.size() == 1)
606 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000607
608 return nullptr;
609}
610
611Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
612 Function *Callee = CI->getCalledFunction();
613 FunctionType *FT = Callee->getFunctionType();
614 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
615 !FT->getParamType(0)->isPointerTy() ||
616 !FT->getParamType(1)->isPointerTy())
617 return nullptr;
618
619 Value *EndPtr = CI->getArgOperand(1);
620 if (isa<ConstantPointerNull>(EndPtr)) {
621 // With a null EndPtr, this function won't capture the main argument.
622 // It would be readonly too, except that it still may write to errno.
623 CI->addAttribute(1, Attribute::NoCapture);
624 }
625
626 return nullptr;
627}
628
629Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
630 Function *Callee = CI->getCalledFunction();
631 FunctionType *FT = Callee->getFunctionType();
632 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
633 FT->getParamType(1) != FT->getParamType(0) ||
634 !FT->getReturnType()->isIntegerTy())
635 return nullptr;
636
637 StringRef S1, S2;
638 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
639 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
640
641 // strspn(s, "") -> 0
642 // strspn("", s) -> 0
643 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
644 return Constant::getNullValue(CI->getType());
645
646 // Constant folding.
647 if (HasS1 && HasS2) {
648 size_t Pos = S1.find_first_not_of(S2);
649 if (Pos == StringRef::npos)
650 Pos = S1.size();
651 return ConstantInt::get(CI->getType(), Pos);
652 }
653
654 return nullptr;
655}
656
657Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
658 Function *Callee = CI->getCalledFunction();
659 FunctionType *FT = Callee->getFunctionType();
660 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
661 FT->getParamType(1) != FT->getParamType(0) ||
662 !FT->getReturnType()->isIntegerTy())
663 return nullptr;
664
665 StringRef S1, S2;
666 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
667 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
668
669 // strcspn("", s) -> 0
670 if (HasS1 && S1.empty())
671 return Constant::getNullValue(CI->getType());
672
673 // Constant folding.
674 if (HasS1 && HasS2) {
675 size_t Pos = S1.find_first_of(S2);
676 if (Pos == StringRef::npos)
677 Pos = S1.size();
678 return ConstantInt::get(CI->getType(), Pos);
679 }
680
681 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000682 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000683 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
684
685 return nullptr;
686}
687
688Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
689 Function *Callee = CI->getCalledFunction();
690 FunctionType *FT = Callee->getFunctionType();
691 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
692 !FT->getParamType(1)->isPointerTy() ||
693 !FT->getReturnType()->isPointerTy())
694 return nullptr;
695
696 // fold strstr(x, x) -> x.
697 if (CI->getArgOperand(0) == CI->getArgOperand(1))
698 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
699
700 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000702 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
703 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000704 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000705 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
706 StrLen, B, DL, TLI);
707 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000708 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000709 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
710 ICmpInst *Old = cast<ICmpInst>(*UI++);
711 Value *Cmp =
712 B.CreateICmp(Old->getPredicate(), StrNCmp,
713 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
714 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000715 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000716 return CI;
717 }
Meador Inge17418502012-10-13 16:45:37 +0000718
Chris Bienemanad070d02014-09-17 20:55:46 +0000719 // See if either input string is a constant string.
720 StringRef SearchStr, ToFindStr;
721 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
722 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
723
724 // fold strstr(x, "") -> x.
725 if (HasStr2 && ToFindStr.empty())
726 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
727
728 // If both strings are known, constant fold it.
729 if (HasStr1 && HasStr2) {
730 size_t Offset = SearchStr.find(ToFindStr);
731
732 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000733 return Constant::getNullValue(CI->getType());
734
Chris Bienemanad070d02014-09-17 20:55:46 +0000735 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
736 Value *Result = CastToCStr(CI->getArgOperand(0), B);
737 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
738 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000739 }
Meador Inge17418502012-10-13 16:45:37 +0000740
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 // fold strstr(x, "y") -> strchr(x, 'y').
742 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000743 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000744 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
745 }
746 return nullptr;
747}
Meador Inge40b6fac2012-10-15 03:47:37 +0000748
Benjamin Kramer691363e2015-03-21 15:36:21 +0000749Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
750 Function *Callee = CI->getCalledFunction();
751 FunctionType *FT = Callee->getFunctionType();
752 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
753 !FT->getParamType(1)->isIntegerTy(32) ||
754 !FT->getParamType(2)->isIntegerTy() ||
755 !FT->getReturnType()->isPointerTy())
756 return nullptr;
757
758 Value *SrcStr = CI->getArgOperand(0);
759 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
760 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
761
762 // memchr(x, y, 0) -> null
763 if (LenC && LenC->isNullValue())
764 return Constant::getNullValue(CI->getType());
765
Benjamin Kramer7857d722015-03-21 21:09:33 +0000766 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000767 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000768 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000769 return nullptr;
770
771 // Truncate the string to LenC. If Str is smaller than LenC we will still only
772 // scan the string, as reading past the end of it is undefined and we can just
773 // return null if we don't find the char.
774 Str = Str.substr(0, LenC->getZExtValue());
775
Benjamin Kramer7857d722015-03-21 21:09:33 +0000776 // If the char is variable but the input str and length are not we can turn
777 // this memchr call into a simple bit field test. Of course this only works
778 // when the return value is only checked against null.
779 //
780 // It would be really nice to reuse switch lowering here but we can't change
781 // the CFG at this point.
782 //
783 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
784 // after bounds check.
785 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000786 unsigned char Max =
787 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
788 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000789
790 // Make sure the bit field we're about to create fits in a register on the
791 // target.
792 // FIXME: On a 64 bit architecture this prevents us from using the
793 // interesting range of alpha ascii chars. We could do better by emitting
794 // two bitfields or shifting the range by 64 if no lower chars are used.
795 if (!DL.fitsInLegalInteger(Max + 1))
796 return nullptr;
797
798 // For the bit field use a power-of-2 type with at least 8 bits to avoid
799 // creating unnecessary illegal types.
800 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
801
802 // Now build the bit field.
803 APInt Bitfield(Width, 0);
804 for (char C : Str)
805 Bitfield.setBit((unsigned char)C);
806 Value *BitfieldC = B.getInt(Bitfield);
807
808 // First check that the bit field access is within bounds.
809 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
810 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
811 "memchr.bounds");
812
813 // Create code that checks if the given bit is set in the field.
814 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
815 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
816
817 // Finally merge both checks and cast to pointer type. The inttoptr
818 // implicitly zexts the i1 to intptr type.
819 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
820 }
821
822 // Check if all arguments are constants. If so, we can constant fold.
823 if (!CharC)
824 return nullptr;
825
Benjamin Kramer691363e2015-03-21 15:36:21 +0000826 // Compute the offset.
827 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
828 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
829 return Constant::getNullValue(CI->getType());
830
831 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000832 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000833}
834
Chris Bienemanad070d02014-09-17 20:55:46 +0000835Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
836 Function *Callee = CI->getCalledFunction();
837 FunctionType *FT = Callee->getFunctionType();
838 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
839 !FT->getParamType(1)->isPointerTy() ||
840 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000841 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000842
Chris Bienemanad070d02014-09-17 20:55:46 +0000843 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000844
Chris Bienemanad070d02014-09-17 20:55:46 +0000845 if (LHS == RHS) // memcmp(s,s,x) -> 0
846 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000847
Chris Bienemanad070d02014-09-17 20:55:46 +0000848 // Make sure we have a constant length.
849 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
850 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000851 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000852 uint64_t Len = LenC->getZExtValue();
853
854 if (Len == 0) // memcmp(s1,s2,0) -> 0
855 return Constant::getNullValue(CI->getType());
856
857 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
858 if (Len == 1) {
859 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
860 CI->getType(), "lhsv");
861 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
862 CI->getType(), "rhsv");
863 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000864 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000865
Chad Rosierdc655322015-08-28 18:30:18 +0000866 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
867 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
868
869 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
870 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
871
872 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
873 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
874
875 Type *LHSPtrTy =
876 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
877 Type *RHSPtrTy =
878 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
879
880 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
881 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
882
883 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
884 }
885 }
886
Chris Bienemanad070d02014-09-17 20:55:46 +0000887 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
888 StringRef LHSStr, RHSStr;
889 if (getConstantStringInfo(LHS, LHSStr) &&
890 getConstantStringInfo(RHS, RHSStr)) {
891 // Make sure we're not reading out-of-bounds memory.
892 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000893 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000894 // Fold the memcmp and normalize the result. This way we get consistent
895 // results across multiple platforms.
896 uint64_t Ret = 0;
897 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
898 if (Cmp < 0)
899 Ret = -1;
900 else if (Cmp > 0)
901 Ret = 1;
902 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000903 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000904
Chris Bienemanad070d02014-09-17 20:55:46 +0000905 return nullptr;
906}
Meador Inge9a6a1902012-10-31 00:20:56 +0000907
Chris Bienemanad070d02014-09-17 20:55:46 +0000908Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
909 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000910
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000911 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000912 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000913
Chris Bienemanad070d02014-09-17 20:55:46 +0000914 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
915 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
916 CI->getArgOperand(2), 1);
917 return CI->getArgOperand(0);
918}
Meador Inge05a625a2012-10-31 14:58:26 +0000919
Chris Bienemanad070d02014-09-17 20:55:46 +0000920Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
921 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000922
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000923 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000924 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000925
Chris Bienemanad070d02014-09-17 20:55:46 +0000926 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
927 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
928 CI->getArgOperand(2), 1);
929 return CI->getArgOperand(0);
930}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000931
Chris Bienemanad070d02014-09-17 20:55:46 +0000932Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
933 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000934
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000936 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000937
Chris Bienemanad070d02014-09-17 20:55:46 +0000938 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
939 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
940 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
941 return CI->getArgOperand(0);
942}
Meador Inged4825782012-11-11 06:49:03 +0000943
Meador Inge193e0352012-11-13 04:16:17 +0000944//===----------------------------------------------------------------------===//
945// Math Library Optimizations
946//===----------------------------------------------------------------------===//
947
Matthias Braund34e4d22014-12-03 21:46:33 +0000948/// Return a variant of Val with float type.
949/// Currently this works in two cases: If Val is an FPExtension of a float
950/// value to something bigger, simply return the operand.
951/// If Val is a ConstantFP but can be converted to a float ConstantFP without
952/// loss of precision do so.
953static Value *valueHasFloatPrecision(Value *Val) {
954 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
955 Value *Op = Cast->getOperand(0);
956 if (Op->getType()->isFloatTy())
957 return Op;
958 }
959 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
960 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000961 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000962 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000963 &losesInfo);
964 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000965 return ConstantFP::get(Const->getContext(), F);
966 }
967 return nullptr;
968}
969
Meador Inge193e0352012-11-13 04:16:17 +0000970//===----------------------------------------------------------------------===//
971// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
972
Chris Bienemanad070d02014-09-17 20:55:46 +0000973Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
974 bool CheckRetType) {
975 Function *Callee = CI->getCalledFunction();
976 FunctionType *FT = Callee->getFunctionType();
977 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
978 !FT->getParamType(0)->isDoubleTy())
979 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000980
Chris Bienemanad070d02014-09-17 20:55:46 +0000981 if (CheckRetType) {
982 // Check if all the uses for function like 'sin' are converted to float.
983 for (User *U : CI->users()) {
984 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
985 if (!Cast || !Cast->getType()->isFloatTy())
986 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000987 }
Meador Inge193e0352012-11-13 04:16:17 +0000988 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000989
990 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000991 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
992 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000993 return nullptr;
994
995 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000996 if (Callee->isIntrinsic()) {
997 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000998 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000999 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1000 V = B.CreateCall(F, V);
1001 } else {
1002 // The call is a library call rather than an intrinsic.
1003 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1004 }
1005
Chris Bienemanad070d02014-09-17 20:55:46 +00001006 return B.CreateFPExt(V, B.getDoubleTy());
1007}
Meador Inge193e0352012-11-13 04:16:17 +00001008
Yi Jiang6ab044e2013-12-16 22:42:40 +00001009// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001010Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1011 Function *Callee = CI->getCalledFunction();
1012 FunctionType *FT = Callee->getFunctionType();
1013 // Just make sure this has 2 arguments of the same FP type, which match the
1014 // result type.
1015 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1016 FT->getParamType(0) != FT->getParamType(1) ||
1017 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001018 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001019
Chris Bienemanad070d02014-09-17 20:55:46 +00001020 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001021 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1022 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1023 if (V1 == nullptr)
1024 return nullptr;
1025 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1026 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001027 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001028
1029 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001030 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001031 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001032 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1033 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001034 return B.CreateFPExt(V, B.getDoubleTy());
1035}
1036
1037Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1038 Function *Callee = CI->getCalledFunction();
1039 Value *Ret = nullptr;
1040 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1041 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001042 }
1043
Chris Bienemanad070d02014-09-17 20:55:46 +00001044 FunctionType *FT = Callee->getFunctionType();
1045 // Just make sure this has 1 argument of FP type, which matches the
1046 // result type.
1047 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1048 !FT->getParamType(0)->isFloatingPointTy())
1049 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001050
Chris Bienemanad070d02014-09-17 20:55:46 +00001051 // cos(-x) -> cos(x)
1052 Value *Op1 = CI->getArgOperand(0);
1053 if (BinaryOperator::isFNeg(Op1)) {
1054 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1055 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1056 }
1057 return Ret;
1058}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001059
Chris Bienemanad070d02014-09-17 20:55:46 +00001060Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1061 Function *Callee = CI->getCalledFunction();
1062
1063 Value *Ret = nullptr;
1064 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1065 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001066 }
1067
Chris Bienemanad070d02014-09-17 20:55:46 +00001068 FunctionType *FT = Callee->getFunctionType();
1069 // Just make sure this has 2 arguments of the same FP type, which match the
1070 // result type.
1071 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1072 FT->getParamType(0) != FT->getParamType(1) ||
1073 !FT->getParamType(0)->isFloatingPointTy())
1074 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001075
Chris Bienemanad070d02014-09-17 20:55:46 +00001076 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1077 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1078 // pow(1.0, x) -> 1.0
1079 if (Op1C->isExactlyValue(1.0))
1080 return Op1C;
1081 // pow(2.0, x) -> exp2(x)
1082 if (Op1C->isExactlyValue(2.0) &&
1083 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1084 LibFunc::exp2l))
1085 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1086 // pow(10.0, x) -> exp10(x)
1087 if (Op1C->isExactlyValue(10.0) &&
1088 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1089 LibFunc::exp10l))
1090 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1091 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001092 }
1093
Chris Bienemanad070d02014-09-17 20:55:46 +00001094 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1095 if (!Op2C)
1096 return Ret;
1097
1098 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1099 return ConstantFP::get(CI->getType(), 1.0);
1100
1101 if (Op2C->isExactlyValue(0.5) &&
1102 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1103 LibFunc::sqrtl) &&
1104 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1105 LibFunc::fabsl)) {
1106 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1107 // This is faster than calling pow, and still handles negative zero
1108 // and negative infinity correctly.
1109 // TODO: In fast-math mode, this could be just sqrt(x).
1110 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1111 Value *Inf = ConstantFP::getInfinity(CI->getType());
1112 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1113 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1114 Value *FAbs =
1115 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1116 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1117 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1118 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001119 }
1120
Chris Bienemanad070d02014-09-17 20:55:46 +00001121 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1122 return Op1;
1123 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1124 return B.CreateFMul(Op1, Op1, "pow2");
1125 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1126 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1127 return nullptr;
1128}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001129
Chris Bienemanad070d02014-09-17 20:55:46 +00001130Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1131 Function *Callee = CI->getCalledFunction();
1132 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001133
Chris Bienemanad070d02014-09-17 20:55:46 +00001134 Value *Ret = nullptr;
1135 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1136 TLI->has(LibFunc::exp2f)) {
1137 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001138 }
1139
Chris Bienemanad070d02014-09-17 20:55:46 +00001140 FunctionType *FT = Callee->getFunctionType();
1141 // Just make sure this has 1 argument of FP type, which matches the
1142 // result type.
1143 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1144 !FT->getParamType(0)->isFloatingPointTy())
1145 return Ret;
1146
1147 Value *Op = CI->getArgOperand(0);
1148 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1149 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1150 LibFunc::Func LdExp = LibFunc::ldexpl;
1151 if (Op->getType()->isFloatTy())
1152 LdExp = LibFunc::ldexpf;
1153 else if (Op->getType()->isDoubleTy())
1154 LdExp = LibFunc::ldexp;
1155
1156 if (TLI->has(LdExp)) {
1157 Value *LdExpArg = nullptr;
1158 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1159 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1160 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1161 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1162 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1163 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1164 }
1165
1166 if (LdExpArg) {
1167 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1168 if (!Op->getType()->isFloatTy())
1169 One = ConstantExpr::getFPExtend(One, Op->getType());
1170
1171 Module *M = Caller->getParent();
1172 Value *Callee =
1173 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001174 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001175 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001176 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1177 CI->setCallingConv(F->getCallingConv());
1178
1179 return CI;
1180 }
1181 }
1182 return Ret;
1183}
1184
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001185Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1186 Function *Callee = CI->getCalledFunction();
1187
1188 Value *Ret = nullptr;
1189 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1190 Ret = optimizeUnaryDoubleFP(CI, B, false);
1191 }
1192
1193 FunctionType *FT = Callee->getFunctionType();
1194 // Make sure this has 1 argument of FP type which matches the result type.
1195 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1196 !FT->getParamType(0)->isFloatingPointTy())
1197 return Ret;
1198
1199 Value *Op = CI->getArgOperand(0);
1200 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1201 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1202 if (I->getOpcode() == Instruction::FMul)
1203 if (I->getOperand(0) == I->getOperand(1))
1204 return Op;
1205 }
1206 return Ret;
1207}
1208
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001209Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1210 // If we can shrink the call to a float function rather than a double
1211 // function, do that first.
1212 Function *Callee = CI->getCalledFunction();
1213 if ((Callee->getName() == "fmin" && TLI->has(LibFunc::fminf)) ||
1214 (Callee->getName() == "fmax" && TLI->has(LibFunc::fmaxf))) {
1215 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1216 if (Ret)
1217 return Ret;
1218 }
1219
1220 // Make sure this has 2 arguments of FP type which match the result type.
1221 FunctionType *FT = Callee->getFunctionType();
1222 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1223 FT->getParamType(0) != FT->getParamType(1) ||
1224 !FT->getParamType(0)->isFloatingPointTy())
1225 return nullptr;
1226
1227 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1228 // fast-math flag decorations that are applied to FP instructions. For now,
1229 // we have to rely on the function-level attributes to do this optimization
1230 // because there's no other way to express that the calls can be relaxed.
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001231 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001232 FastMathFlags FMF;
1233 Function *F = CI->getParent()->getParent();
1234 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1235 if (Attr.getValueAsString() == "true") {
1236 // Unsafe algebra sets all fast-math-flags to true.
1237 FMF.setUnsafeAlgebra();
1238 } else {
1239 // At a minimum, no-nans-fp-math must be true.
1240 Attr = F->getFnAttribute("no-nans-fp-math");
1241 if (Attr.getValueAsString() != "true")
1242 return nullptr;
1243 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1244 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001245 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001246 // might be impractical."
1247 FMF.setNoSignedZeros();
1248 FMF.setNoNaNs();
1249 }
1250 B.SetFastMathFlags(FMF);
1251
1252 // We have a relaxed floating-point environment. We can ignore NaN-handling
1253 // and transform to a compare and select. We do not have to consider errno or
1254 // exceptions, because fmin/fmax do not have those.
1255 Value *Op0 = CI->getArgOperand(0);
1256 Value *Op1 = CI->getArgOperand(1);
1257 Value *Cmp = Callee->getName().startswith("fmin") ?
1258 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1259 return B.CreateSelect(Cmp, Op0, Op1);
1260}
1261
Sanjay Patelc699a612014-10-16 18:48:17 +00001262Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1263 Function *Callee = CI->getCalledFunction();
1264
1265 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001266 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1267 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001268 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patelc699a612014-10-16 18:48:17 +00001269
1270 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1271 // fast-math flag decorations that are applied to FP instructions. For now,
1272 // we have to rely on the function-level unsafe-fp-math attribute to do this
1273 // optimization because there's no other way to express that the sqrt can be
1274 // reassociated.
1275 Function *F = CI->getParent()->getParent();
1276 if (F->hasFnAttribute("unsafe-fp-math")) {
1277 // Check for unsafe-fp-math = true.
1278 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1279 if (Attr.getValueAsString() != "true")
1280 return Ret;
1281 }
1282 Value *Op = CI->getArgOperand(0);
1283 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1284 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1285 // We're looking for a repeated factor in a multiplication tree,
1286 // so we can do this fold: sqrt(x * x) -> fabs(x);
1287 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1288 Value *Op0 = I->getOperand(0);
1289 Value *Op1 = I->getOperand(1);
1290 Value *RepeatOp = nullptr;
1291 Value *OtherOp = nullptr;
1292 if (Op0 == Op1) {
1293 // Simple match: the operands of the multiply are identical.
1294 RepeatOp = Op0;
1295 } else {
1296 // Look for a more complicated pattern: one of the operands is itself
1297 // a multiply, so search for a common factor in that multiply.
1298 // Note: We don't bother looking any deeper than this first level or for
1299 // variations of this pattern because instcombine's visitFMUL and/or the
1300 // reassociation pass should give us this form.
1301 Value *OtherMul0, *OtherMul1;
1302 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1303 // Pattern: sqrt((x * y) * z)
1304 if (OtherMul0 == OtherMul1) {
1305 // Matched: sqrt((x * x) * z)
1306 RepeatOp = OtherMul0;
1307 OtherOp = Op1;
1308 }
1309 }
1310 }
1311 if (RepeatOp) {
1312 // Fast math flags for any created instructions should match the sqrt
1313 // and multiply.
1314 // FIXME: We're not checking the sqrt because it doesn't have
1315 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001316 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001317 B.SetFastMathFlags(I->getFastMathFlags());
1318 // If we found a repeated factor, hoist it out of the square root and
1319 // replace it with the fabs of that factor.
1320 Module *M = Callee->getParent();
1321 Type *ArgType = Op->getType();
1322 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1323 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1324 if (OtherOp) {
1325 // If we found a non-repeated factor, we still need to get its square
1326 // root. We then multiply that by the value that was simplified out
1327 // of the square root calculation.
1328 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1329 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1330 return B.CreateFMul(FabsCall, SqrtCall);
1331 }
1332 return FabsCall;
1333 }
1334 }
1335 }
1336 return Ret;
1337}
1338
Chris Bienemanad070d02014-09-17 20:55:46 +00001339static bool isTrigLibCall(CallInst *CI);
1340static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1341 bool UseFloat, Value *&Sin, Value *&Cos,
1342 Value *&SinCos);
1343
1344Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1345
1346 // Make sure the prototype is as expected, otherwise the rest of the
1347 // function is probably invalid and likely to abort.
1348 if (!isTrigLibCall(CI))
1349 return nullptr;
1350
1351 Value *Arg = CI->getArgOperand(0);
1352 SmallVector<CallInst *, 1> SinCalls;
1353 SmallVector<CallInst *, 1> CosCalls;
1354 SmallVector<CallInst *, 1> SinCosCalls;
1355
1356 bool IsFloat = Arg->getType()->isFloatTy();
1357
1358 // Look for all compatible sinpi, cospi and sincospi calls with the same
1359 // argument. If there are enough (in some sense) we can make the
1360 // substitution.
1361 for (User *U : Arg->users())
1362 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1363 SinCosCalls);
1364
1365 // It's only worthwhile if both sinpi and cospi are actually used.
1366 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1367 return nullptr;
1368
1369 Value *Sin, *Cos, *SinCos;
1370 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1371
1372 replaceTrigInsts(SinCalls, Sin);
1373 replaceTrigInsts(CosCalls, Cos);
1374 replaceTrigInsts(SinCosCalls, SinCos);
1375
1376 return nullptr;
1377}
1378
1379static bool isTrigLibCall(CallInst *CI) {
1380 Function *Callee = CI->getCalledFunction();
1381 FunctionType *FT = Callee->getFunctionType();
1382
1383 // We can only hope to do anything useful if we can ignore things like errno
1384 // and floating-point exceptions.
1385 bool AttributesSafe =
1386 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1387
1388 // Other than that we need float(float) or double(double)
1389 return AttributesSafe && FT->getNumParams() == 1 &&
1390 FT->getReturnType() == FT->getParamType(0) &&
1391 (FT->getParamType(0)->isFloatTy() ||
1392 FT->getParamType(0)->isDoubleTy());
1393}
1394
1395void
1396LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1397 SmallVectorImpl<CallInst *> &SinCalls,
1398 SmallVectorImpl<CallInst *> &CosCalls,
1399 SmallVectorImpl<CallInst *> &SinCosCalls) {
1400 CallInst *CI = dyn_cast<CallInst>(Val);
1401
1402 if (!CI)
1403 return;
1404
1405 Function *Callee = CI->getCalledFunction();
1406 StringRef FuncName = Callee->getName();
1407 LibFunc::Func Func;
1408 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1409 return;
1410
1411 if (IsFloat) {
1412 if (Func == LibFunc::sinpif)
1413 SinCalls.push_back(CI);
1414 else if (Func == LibFunc::cospif)
1415 CosCalls.push_back(CI);
1416 else if (Func == LibFunc::sincospif_stret)
1417 SinCosCalls.push_back(CI);
1418 } else {
1419 if (Func == LibFunc::sinpi)
1420 SinCalls.push_back(CI);
1421 else if (Func == LibFunc::cospi)
1422 CosCalls.push_back(CI);
1423 else if (Func == LibFunc::sincospi_stret)
1424 SinCosCalls.push_back(CI);
1425 }
1426}
1427
1428void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1429 Value *Res) {
1430 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1431 I != E; ++I) {
1432 replaceAllUsesWith(*I, Res);
1433 }
1434}
1435
1436void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1437 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1438 Type *ArgTy = Arg->getType();
1439 Type *ResTy;
1440 StringRef Name;
1441
1442 Triple T(OrigCallee->getParent()->getTargetTriple());
1443 if (UseFloat) {
1444 Name = "__sincospif_stret";
1445
1446 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1447 // x86_64 can't use {float, float} since that would be returned in both
1448 // xmm0 and xmm1, which isn't what a real struct would do.
1449 ResTy = T.getArch() == Triple::x86_64
1450 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001451 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001452 } else {
1453 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001454 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001455 }
1456
1457 Module *M = OrigCallee->getParent();
1458 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001459 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001460
1461 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1462 // If the argument is an instruction, it must dominate all uses so put our
1463 // sincos call there.
1464 BasicBlock::iterator Loc = ArgInst;
1465 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1466 } else {
1467 // Otherwise (e.g. for a constant) the beginning of the function is as
1468 // good a place as any.
1469 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1470 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1471 }
1472
1473 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1474
1475 if (SinCos->getType()->isStructTy()) {
1476 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1477 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1478 } else {
1479 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1480 "sinpi");
1481 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1482 "cospi");
1483 }
1484}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001485
Meador Inge7415f842012-11-25 20:45:27 +00001486//===----------------------------------------------------------------------===//
1487// Integer Library Call Optimizations
1488//===----------------------------------------------------------------------===//
1489
Chris Bienemanad070d02014-09-17 20:55:46 +00001490Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1491 Function *Callee = CI->getCalledFunction();
1492 FunctionType *FT = Callee->getFunctionType();
1493 // Just make sure this has 2 arguments of the same FP type, which match the
1494 // result type.
1495 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1496 !FT->getParamType(0)->isIntegerTy())
1497 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001498
Chris Bienemanad070d02014-09-17 20:55:46 +00001499 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001500
Chris Bienemanad070d02014-09-17 20:55:46 +00001501 // Constant fold.
1502 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1503 if (CI->isZero()) // ffs(0) -> 0.
1504 return B.getInt32(0);
1505 // ffs(c) -> cttz(c)+1
1506 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001507 }
Meador Inge7415f842012-11-25 20:45:27 +00001508
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1510 Type *ArgType = Op->getType();
1511 Value *F =
1512 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001513 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001514 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1515 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001516
Chris Bienemanad070d02014-09-17 20:55:46 +00001517 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1518 return B.CreateSelect(Cond, V, B.getInt32(0));
1519}
Meador Ingea0b6d872012-11-26 00:24:07 +00001520
Chris Bienemanad070d02014-09-17 20:55:46 +00001521Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1522 Function *Callee = CI->getCalledFunction();
1523 FunctionType *FT = Callee->getFunctionType();
1524 // We require integer(integer) where the types agree.
1525 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1526 FT->getParamType(0) != FT->getReturnType())
1527 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001528
Chris Bienemanad070d02014-09-17 20:55:46 +00001529 // abs(x) -> x >s -1 ? x : -x
1530 Value *Op = CI->getArgOperand(0);
1531 Value *Pos =
1532 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1533 Value *Neg = B.CreateNeg(Op, "neg");
1534 return B.CreateSelect(Pos, Op, Neg);
1535}
Meador Inge9a59ab62012-11-26 02:31:59 +00001536
Chris Bienemanad070d02014-09-17 20:55:46 +00001537Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1538 Function *Callee = CI->getCalledFunction();
1539 FunctionType *FT = Callee->getFunctionType();
1540 // We require integer(i32)
1541 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1542 !FT->getParamType(0)->isIntegerTy(32))
1543 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001544
Chris Bienemanad070d02014-09-17 20:55:46 +00001545 // isdigit(c) -> (c-'0') <u 10
1546 Value *Op = CI->getArgOperand(0);
1547 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1548 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1549 return B.CreateZExt(Op, CI->getType());
1550}
Meador Ingea62a39e2012-11-26 03:10:07 +00001551
Chris Bienemanad070d02014-09-17 20:55:46 +00001552Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1553 Function *Callee = CI->getCalledFunction();
1554 FunctionType *FT = Callee->getFunctionType();
1555 // We require integer(i32)
1556 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1557 !FT->getParamType(0)->isIntegerTy(32))
1558 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001559
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 // isascii(c) -> c <u 128
1561 Value *Op = CI->getArgOperand(0);
1562 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1563 return B.CreateZExt(Op, CI->getType());
1564}
1565
1566Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1567 Function *Callee = CI->getCalledFunction();
1568 FunctionType *FT = Callee->getFunctionType();
1569 // We require i32(i32)
1570 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1571 !FT->getParamType(0)->isIntegerTy(32))
1572 return nullptr;
1573
1574 // toascii(c) -> c & 0x7f
1575 return B.CreateAnd(CI->getArgOperand(0),
1576 ConstantInt::get(CI->getType(), 0x7F));
1577}
Meador Inge604937d2012-11-26 03:38:52 +00001578
Meador Inge08ca1152012-11-26 20:37:20 +00001579//===----------------------------------------------------------------------===//
1580// Formatting and IO Library Call Optimizations
1581//===----------------------------------------------------------------------===//
1582
Chris Bienemanad070d02014-09-17 20:55:46 +00001583static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001584
Chris Bienemanad070d02014-09-17 20:55:46 +00001585Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1586 int StreamArg) {
1587 // Error reporting calls should be cold, mark them as such.
1588 // This applies even to non-builtin calls: it is only a hint and applies to
1589 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001590
Chris Bienemanad070d02014-09-17 20:55:46 +00001591 // This heuristic was suggested in:
1592 // Improving Static Branch Prediction in a Compiler
1593 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1594 // Proceedings of PACT'98, Oct. 1998, IEEE
1595 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001596
Chris Bienemanad070d02014-09-17 20:55:46 +00001597 if (!CI->hasFnAttr(Attribute::Cold) &&
1598 isReportingError(Callee, CI, StreamArg)) {
1599 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1600 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001601
Chris Bienemanad070d02014-09-17 20:55:46 +00001602 return nullptr;
1603}
1604
1605static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1606 if (!ColdErrorCalls)
1607 return false;
1608
1609 if (!Callee || !Callee->isDeclaration())
1610 return false;
1611
1612 if (StreamArg < 0)
1613 return true;
1614
1615 // These functions might be considered cold, but only if their stream
1616 // argument is stderr.
1617
1618 if (StreamArg >= (int)CI->getNumArgOperands())
1619 return false;
1620 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1621 if (!LI)
1622 return false;
1623 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1624 if (!GV || !GV->isDeclaration())
1625 return false;
1626 return GV->getName() == "stderr";
1627}
1628
1629Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1630 // Check for a fixed format string.
1631 StringRef FormatStr;
1632 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001633 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001634
Chris Bienemanad070d02014-09-17 20:55:46 +00001635 // Empty format string -> noop.
1636 if (FormatStr.empty()) // Tolerate printf's declared void.
1637 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001638
Chris Bienemanad070d02014-09-17 20:55:46 +00001639 // Do not do any of the following transformations if the printf return value
1640 // is used, in general the printf return value is not compatible with either
1641 // putchar() or puts().
1642 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001643 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001644
1645 // printf("x") -> putchar('x'), even for '%'.
1646 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001647 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 if (CI->use_empty() || !Res)
1649 return Res;
1650 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001651 }
1652
Chris Bienemanad070d02014-09-17 20:55:46 +00001653 // printf("foo\n") --> puts("foo")
1654 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1655 FormatStr.find('%') == StringRef::npos) { // No format characters.
1656 // Create a string literal with no \n on it. We expect the constant merge
1657 // pass to be run after this pass, to merge duplicate strings.
1658 FormatStr = FormatStr.drop_back();
1659 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001660 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 return (CI->use_empty() || !NewCI)
1662 ? NewCI
1663 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1664 }
Meador Inge08ca1152012-11-26 20:37:20 +00001665
Chris Bienemanad070d02014-09-17 20:55:46 +00001666 // Optimize specific format strings.
1667 // printf("%c", chr) --> putchar(chr)
1668 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1669 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001670 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001671
Chris Bienemanad070d02014-09-17 20:55:46 +00001672 if (CI->use_empty() || !Res)
1673 return Res;
1674 return B.CreateIntCast(Res, CI->getType(), true);
1675 }
1676
1677 // printf("%s\n", str) --> puts(str)
1678 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1679 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001680 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001681 }
1682 return nullptr;
1683}
1684
1685Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1686
1687 Function *Callee = CI->getCalledFunction();
1688 // Require one fixed pointer argument and an integer/void result.
1689 FunctionType *FT = Callee->getFunctionType();
1690 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1691 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1692 return nullptr;
1693
1694 if (Value *V = optimizePrintFString(CI, B)) {
1695 return V;
1696 }
1697
1698 // printf(format, ...) -> iprintf(format, ...) if no floating point
1699 // arguments.
1700 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1701 Module *M = B.GetInsertBlock()->getParent()->getParent();
1702 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001703 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001704 CallInst *New = cast<CallInst>(CI->clone());
1705 New->setCalledFunction(IPrintFFn);
1706 B.Insert(New);
1707 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001708 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 return nullptr;
1710}
Meador Inge08ca1152012-11-26 20:37:20 +00001711
Chris Bienemanad070d02014-09-17 20:55:46 +00001712Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1713 // Check for a fixed format string.
1714 StringRef FormatStr;
1715 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001716 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001717
Chris Bienemanad070d02014-09-17 20:55:46 +00001718 // If we just have a format string (nothing else crazy) transform it.
1719 if (CI->getNumArgOperands() == 2) {
1720 // Make sure there's no % in the constant array. We could try to handle
1721 // %% -> % in the future if we cared.
1722 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1723 if (FormatStr[i] == '%')
1724 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001725
Chris Bienemanad070d02014-09-17 20:55:46 +00001726 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001727 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1728 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1729 FormatStr.size() + 1),
1730 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001731 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001732 }
Meador Ingef8e72502012-11-29 15:45:43 +00001733
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 // The remaining optimizations require the format string to be "%s" or "%c"
1735 // and have an extra operand.
1736 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1737 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001738 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001739
Chris Bienemanad070d02014-09-17 20:55:46 +00001740 // Decode the second character of the format string.
1741 if (FormatStr[1] == 'c') {
1742 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1743 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1744 return nullptr;
1745 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1746 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1747 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001748 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001749 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001750
Chris Bienemanad070d02014-09-17 20:55:46 +00001751 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001752 }
1753
Chris Bienemanad070d02014-09-17 20:55:46 +00001754 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001755 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1756 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1757 return nullptr;
1758
1759 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1760 if (!Len)
1761 return nullptr;
1762 Value *IncLen =
1763 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1764 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1765
1766 // The sprintf result is the unincremented number of bytes in the string.
1767 return B.CreateIntCast(Len, CI->getType(), false);
1768 }
1769 return nullptr;
1770}
1771
1772Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1773 Function *Callee = CI->getCalledFunction();
1774 // Require two fixed pointer arguments and an integer result.
1775 FunctionType *FT = Callee->getFunctionType();
1776 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1777 !FT->getParamType(1)->isPointerTy() ||
1778 !FT->getReturnType()->isIntegerTy())
1779 return nullptr;
1780
1781 if (Value *V = optimizeSPrintFString(CI, B)) {
1782 return V;
1783 }
1784
1785 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1786 // point arguments.
1787 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1788 Module *M = B.GetInsertBlock()->getParent()->getParent();
1789 Constant *SIPrintFFn =
1790 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1791 CallInst *New = cast<CallInst>(CI->clone());
1792 New->setCalledFunction(SIPrintFFn);
1793 B.Insert(New);
1794 return New;
1795 }
1796 return nullptr;
1797}
1798
1799Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1800 optimizeErrorReporting(CI, B, 0);
1801
1802 // All the optimizations depend on the format string.
1803 StringRef FormatStr;
1804 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1805 return nullptr;
1806
1807 // Do not do any of the following transformations if the fprintf return
1808 // value is used, in general the fprintf return value is not compatible
1809 // with fwrite(), fputc() or fputs().
1810 if (!CI->use_empty())
1811 return nullptr;
1812
1813 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1814 if (CI->getNumArgOperands() == 2) {
1815 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1816 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1817 return nullptr; // We found a format specifier.
1818
Chris Bienemanad070d02014-09-17 20:55:46 +00001819 return EmitFWrite(
1820 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001821 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001822 CI->getArgOperand(0), B, DL, TLI);
1823 }
1824
1825 // The remaining optimizations require the format string to be "%s" or "%c"
1826 // and have an extra operand.
1827 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1828 CI->getNumArgOperands() < 3)
1829 return nullptr;
1830
1831 // Decode the second character of the format string.
1832 if (FormatStr[1] == 'c') {
1833 // fprintf(F, "%c", chr) --> fputc(chr, F)
1834 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1835 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001836 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001837 }
1838
1839 if (FormatStr[1] == 's') {
1840 // fprintf(F, "%s", str) --> fputs(str, F)
1841 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1842 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001843 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001844 }
1845 return nullptr;
1846}
1847
1848Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1849 Function *Callee = CI->getCalledFunction();
1850 // Require two fixed paramters as pointers and integer result.
1851 FunctionType *FT = Callee->getFunctionType();
1852 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1853 !FT->getParamType(1)->isPointerTy() ||
1854 !FT->getReturnType()->isIntegerTy())
1855 return nullptr;
1856
1857 if (Value *V = optimizeFPrintFString(CI, B)) {
1858 return V;
1859 }
1860
1861 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1862 // floating point arguments.
1863 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1864 Module *M = B.GetInsertBlock()->getParent()->getParent();
1865 Constant *FIPrintFFn =
1866 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1867 CallInst *New = cast<CallInst>(CI->clone());
1868 New->setCalledFunction(FIPrintFFn);
1869 B.Insert(New);
1870 return New;
1871 }
1872 return nullptr;
1873}
1874
1875Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1876 optimizeErrorReporting(CI, B, 3);
1877
1878 Function *Callee = CI->getCalledFunction();
1879 // Require a pointer, an integer, an integer, a pointer, returning integer.
1880 FunctionType *FT = Callee->getFunctionType();
1881 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1882 !FT->getParamType(1)->isIntegerTy() ||
1883 !FT->getParamType(2)->isIntegerTy() ||
1884 !FT->getParamType(3)->isPointerTy() ||
1885 !FT->getReturnType()->isIntegerTy())
1886 return nullptr;
1887
1888 // Get the element size and count.
1889 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1890 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1891 if (!SizeC || !CountC)
1892 return nullptr;
1893 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1894
1895 // If this is writing zero records, remove the call (it's a noop).
1896 if (Bytes == 0)
1897 return ConstantInt::get(CI->getType(), 0);
1898
1899 // If this is writing one byte, turn it into fputc.
1900 // This optimisation is only valid, if the return value is unused.
1901 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1902 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001903 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001904 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1905 }
1906
1907 return nullptr;
1908}
1909
1910Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1911 optimizeErrorReporting(CI, B, 1);
1912
1913 Function *Callee = CI->getCalledFunction();
1914
Chris Bienemanad070d02014-09-17 20:55:46 +00001915 // Require two pointers. Also, we can't optimize if return value is used.
1916 FunctionType *FT = Callee->getFunctionType();
1917 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1918 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1919 return nullptr;
1920
1921 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1922 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1923 if (!Len)
1924 return nullptr;
1925
1926 // Known to have no uses (see above).
1927 return EmitFWrite(
1928 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001929 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001930 CI->getArgOperand(1), B, DL, TLI);
1931}
1932
1933Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1934 Function *Callee = CI->getCalledFunction();
1935 // Require one fixed pointer argument and an integer/void result.
1936 FunctionType *FT = Callee->getFunctionType();
1937 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1938 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1939 return nullptr;
1940
1941 // Check for a constant string.
1942 StringRef Str;
1943 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1944 return nullptr;
1945
1946 if (Str.empty() && CI->use_empty()) {
1947 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001948 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001949 if (CI->use_empty() || !Res)
1950 return Res;
1951 return B.CreateIntCast(Res, CI->getType(), true);
1952 }
1953
1954 return nullptr;
1955}
1956
1957bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001958 LibFunc::Func Func;
1959 SmallString<20> FloatFuncName = FuncName;
1960 FloatFuncName += 'f';
1961 if (TLI->getLibFunc(FloatFuncName, Func))
1962 return TLI->has(Func);
1963 return false;
1964}
Meador Inge7fb2f732012-10-13 16:45:32 +00001965
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001966Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1967 IRBuilder<> &Builder) {
1968 LibFunc::Func Func;
1969 Function *Callee = CI->getCalledFunction();
1970 StringRef FuncName = Callee->getName();
1971
1972 // Check for string/memory library functions.
1973 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1974 // Make sure we never change the calling convention.
1975 assert((ignoreCallingConv(Func) ||
1976 CI->getCallingConv() == llvm::CallingConv::C) &&
1977 "Optimizing string/memory libcall would change the calling convention");
1978 switch (Func) {
1979 case LibFunc::strcat:
1980 return optimizeStrCat(CI, Builder);
1981 case LibFunc::strncat:
1982 return optimizeStrNCat(CI, Builder);
1983 case LibFunc::strchr:
1984 return optimizeStrChr(CI, Builder);
1985 case LibFunc::strrchr:
1986 return optimizeStrRChr(CI, Builder);
1987 case LibFunc::strcmp:
1988 return optimizeStrCmp(CI, Builder);
1989 case LibFunc::strncmp:
1990 return optimizeStrNCmp(CI, Builder);
1991 case LibFunc::strcpy:
1992 return optimizeStrCpy(CI, Builder);
1993 case LibFunc::stpcpy:
1994 return optimizeStpCpy(CI, Builder);
1995 case LibFunc::strncpy:
1996 return optimizeStrNCpy(CI, Builder);
1997 case LibFunc::strlen:
1998 return optimizeStrLen(CI, Builder);
1999 case LibFunc::strpbrk:
2000 return optimizeStrPBrk(CI, Builder);
2001 case LibFunc::strtol:
2002 case LibFunc::strtod:
2003 case LibFunc::strtof:
2004 case LibFunc::strtoul:
2005 case LibFunc::strtoll:
2006 case LibFunc::strtold:
2007 case LibFunc::strtoull:
2008 return optimizeStrTo(CI, Builder);
2009 case LibFunc::strspn:
2010 return optimizeStrSpn(CI, Builder);
2011 case LibFunc::strcspn:
2012 return optimizeStrCSpn(CI, Builder);
2013 case LibFunc::strstr:
2014 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002015 case LibFunc::memchr:
2016 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002017 case LibFunc::memcmp:
2018 return optimizeMemCmp(CI, Builder);
2019 case LibFunc::memcpy:
2020 return optimizeMemCpy(CI, Builder);
2021 case LibFunc::memmove:
2022 return optimizeMemMove(CI, Builder);
2023 case LibFunc::memset:
2024 return optimizeMemSet(CI, Builder);
2025 default:
2026 break;
2027 }
2028 }
2029 return nullptr;
2030}
2031
Chris Bienemanad070d02014-09-17 20:55:46 +00002032Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2033 if (CI->isNoBuiltin())
2034 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002035
Meador Inge20255ef2013-03-12 00:08:29 +00002036 LibFunc::Func Func;
2037 Function *Callee = CI->getCalledFunction();
2038 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002039 IRBuilder<> Builder(CI);
2040 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002041
Sanjay Patela92fa442014-10-22 15:29:23 +00002042 // Command-line parameter overrides function attribute.
2043 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2044 UnsafeFPShrink = EnableUnsafeFPShrink;
2045 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2046 // FIXME: This is the same problem as described in optimizeSqrt().
2047 // If calls gain access to IR-level FMF, then use that instead of a
2048 // function attribute.
2049
2050 // Check for unsafe-fp-math = true.
2051 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2052 if (Attr.getValueAsString() == "true")
2053 UnsafeFPShrink = true;
2054 }
2055
Sanjay Patel848309d2014-10-23 21:52:45 +00002056 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002057 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002058 if (!isCallingConvC)
2059 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002060 switch (II->getIntrinsicID()) {
2061 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002062 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002063 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002064 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002065 case Intrinsic::fabs:
2066 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002067 case Intrinsic::sqrt:
2068 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002069 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002070 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002071 }
2072 }
2073
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002074 // Also try to simplify calls to fortified library functions.
2075 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2076 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002077 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2078 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002079 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
2080 // If we were able to further simplify, remove the now redundant call.
2081 SimplifiedCI->replaceAllUsesWith(V);
2082 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002083 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002084 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002085 return SimplifiedFortifiedCI;
2086 }
2087
Meador Inge20255ef2013-03-12 00:08:29 +00002088 // Then check for known library functions.
2089 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002090 // We never change the calling convention.
2091 if (!ignoreCallingConv(Func) && !isCallingConvC)
2092 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002093 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2094 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002095 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002096 case LibFunc::cosf:
2097 case LibFunc::cos:
2098 case LibFunc::cosl:
2099 return optimizeCos(CI, Builder);
2100 case LibFunc::sinpif:
2101 case LibFunc::sinpi:
2102 case LibFunc::cospif:
2103 case LibFunc::cospi:
2104 return optimizeSinCosPi(CI, Builder);
2105 case LibFunc::powf:
2106 case LibFunc::pow:
2107 case LibFunc::powl:
2108 return optimizePow(CI, Builder);
2109 case LibFunc::exp2l:
2110 case LibFunc::exp2:
2111 case LibFunc::exp2f:
2112 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002113 case LibFunc::fabsf:
2114 case LibFunc::fabs:
2115 case LibFunc::fabsl:
2116 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002117 case LibFunc::sqrtf:
2118 case LibFunc::sqrt:
2119 case LibFunc::sqrtl:
2120 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002121 case LibFunc::ffs:
2122 case LibFunc::ffsl:
2123 case LibFunc::ffsll:
2124 return optimizeFFS(CI, Builder);
2125 case LibFunc::abs:
2126 case LibFunc::labs:
2127 case LibFunc::llabs:
2128 return optimizeAbs(CI, Builder);
2129 case LibFunc::isdigit:
2130 return optimizeIsDigit(CI, Builder);
2131 case LibFunc::isascii:
2132 return optimizeIsAscii(CI, Builder);
2133 case LibFunc::toascii:
2134 return optimizeToAscii(CI, Builder);
2135 case LibFunc::printf:
2136 return optimizePrintF(CI, Builder);
2137 case LibFunc::sprintf:
2138 return optimizeSPrintF(CI, Builder);
2139 case LibFunc::fprintf:
2140 return optimizeFPrintF(CI, Builder);
2141 case LibFunc::fwrite:
2142 return optimizeFWrite(CI, Builder);
2143 case LibFunc::fputs:
2144 return optimizeFPuts(CI, Builder);
2145 case LibFunc::puts:
2146 return optimizePuts(CI, Builder);
2147 case LibFunc::perror:
2148 return optimizeErrorReporting(CI, Builder);
2149 case LibFunc::vfprintf:
2150 case LibFunc::fiprintf:
2151 return optimizeErrorReporting(CI, Builder, 0);
2152 case LibFunc::fputc:
2153 return optimizeErrorReporting(CI, Builder, 1);
2154 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002155 case LibFunc::floor:
2156 case LibFunc::rint:
2157 case LibFunc::round:
2158 case LibFunc::nearbyint:
2159 case LibFunc::trunc:
2160 if (hasFloatVersion(FuncName))
2161 return optimizeUnaryDoubleFP(CI, Builder, false);
2162 return nullptr;
2163 case LibFunc::acos:
2164 case LibFunc::acosh:
2165 case LibFunc::asin:
2166 case LibFunc::asinh:
2167 case LibFunc::atan:
2168 case LibFunc::atanh:
2169 case LibFunc::cbrt:
2170 case LibFunc::cosh:
2171 case LibFunc::exp:
2172 case LibFunc::exp10:
2173 case LibFunc::expm1:
2174 case LibFunc::log:
2175 case LibFunc::log10:
2176 case LibFunc::log1p:
2177 case LibFunc::log2:
2178 case LibFunc::logb:
2179 case LibFunc::sin:
2180 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002181 case LibFunc::tan:
2182 case LibFunc::tanh:
2183 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2184 return optimizeUnaryDoubleFP(CI, Builder, true);
2185 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002186 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002187 if (hasFloatVersion(FuncName))
2188 return optimizeBinaryDoubleFP(CI, Builder);
2189 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002190 case LibFunc::fminf:
2191 case LibFunc::fmin:
2192 case LibFunc::fminl:
2193 case LibFunc::fmaxf:
2194 case LibFunc::fmax:
2195 case LibFunc::fmaxl:
2196 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002197 default:
2198 return nullptr;
2199 }
Meador Inge20255ef2013-03-12 00:08:29 +00002200 }
Craig Topperf40110f2014-04-25 05:29:35 +00002201 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002202}
2203
Chandler Carruth92803822015-01-21 02:11:59 +00002204LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002205 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002206 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002207 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002208 Replacer(Replacer) {}
2209
2210void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2211 // Indirect through the replacer used in this instance.
2212 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002213}
2214
Chandler Carruth92803822015-01-21 02:11:59 +00002215/*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2216 Value *With) {
Meador Inge76fc1a42012-11-11 03:51:43 +00002217 I->replaceAllUsesWith(With);
2218 I->eraseFromParent();
2219}
2220
Meador Ingedfb08a22013-06-20 19:48:07 +00002221// TODO:
2222// Additional cases that we need to add to this file:
2223//
2224// cbrt:
2225// * cbrt(expN(X)) -> expN(x/3)
2226// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002227// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002228//
2229// exp, expf, expl:
2230// * exp(log(x)) -> x
2231//
2232// log, logf, logl:
2233// * log(exp(x)) -> x
2234// * log(x**y) -> y*log(x)
2235// * log(exp(y)) -> y*log(e)
2236// * log(exp2(y)) -> y*log(2)
2237// * log(exp10(y)) -> y*log(10)
2238// * log(sqrt(x)) -> 0.5*log(x)
2239// * log(pow(x,y)) -> y*log(x)
2240//
2241// lround, lroundf, lroundl:
2242// * lround(cnst) -> cnst'
2243//
2244// pow, powf, powl:
2245// * pow(exp(x),y) -> exp(x*y)
2246// * pow(sqrt(x),y) -> pow(x,y*0.5)
2247// * pow(pow(x,y),z)-> pow(x,y*z)
2248//
2249// round, roundf, roundl:
2250// * round(cnst) -> cnst'
2251//
2252// signbit:
2253// * signbit(cnst) -> cnst'
2254// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2255//
2256// sqrt, sqrtf, sqrtl:
2257// * sqrt(expN(x)) -> expN(x*0.5)
2258// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2259// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2260//
Meador Ingedfb08a22013-06-20 19:48:07 +00002261// tan, tanf, tanl:
2262// * tan(atan(x)) -> x
2263//
2264// trunc, truncf, truncl:
2265// * trunc(cnst) -> cnst'
2266//
2267//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002268
2269//===----------------------------------------------------------------------===//
2270// Fortified Library Call Optimizations
2271//===----------------------------------------------------------------------===//
2272
2273bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2274 unsigned ObjSizeOp,
2275 unsigned SizeOp,
2276 bool isString) {
2277 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2278 return true;
2279 if (ConstantInt *ObjSizeCI =
2280 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2281 if (ObjSizeCI->isAllOnesValue())
2282 return true;
2283 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2284 if (OnlyLowerUnknownSize)
2285 return false;
2286 if (isString) {
2287 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2288 // If the length is 0 we don't know how long it is and so we can't
2289 // remove the check.
2290 if (Len == 0)
2291 return false;
2292 return ObjSizeCI->getZExtValue() >= Len;
2293 }
2294 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2295 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2296 }
2297 return false;
2298}
2299
2300Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2301 Function *Callee = CI->getCalledFunction();
2302
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002303 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002304 return nullptr;
2305
2306 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2307 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2308 CI->getArgOperand(2), 1);
2309 return CI->getArgOperand(0);
2310 }
2311 return nullptr;
2312}
2313
2314Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2315 Function *Callee = CI->getCalledFunction();
2316
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002317 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002318 return nullptr;
2319
2320 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2321 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2322 CI->getArgOperand(2), 1);
2323 return CI->getArgOperand(0);
2324 }
2325 return nullptr;
2326}
2327
2328Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2329 Function *Callee = CI->getCalledFunction();
2330
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002331 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002332 return nullptr;
2333
2334 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2335 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2336 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2337 return CI->getArgOperand(0);
2338 }
2339 return nullptr;
2340}
2341
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002342Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2343 IRBuilder<> &B,
2344 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002345 Function *Callee = CI->getCalledFunction();
2346 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002347 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002348
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002349 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002350 return nullptr;
2351
2352 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2353 *ObjSize = CI->getArgOperand(2);
2354
2355 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002356 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002357 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002358 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002359 }
2360
2361 // If a) we don't have any length information, or b) we know this will
2362 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2363 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2364 // TODO: It might be nice to get a maximum length out of the possible
2365 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002366 if (isFortifiedCallFoldable(CI, 2, 1, true))
2367 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002368
David Blaikie65fab6d2015-04-03 21:32:06 +00002369 if (OnlyLowerUnknownSize)
2370 return nullptr;
2371
2372 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2373 uint64_t Len = GetStringLength(Src);
2374 if (Len == 0)
2375 return nullptr;
2376
2377 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2378 Value *LenV = ConstantInt::get(SizeTTy, Len);
2379 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2380 // If the function was an __stpcpy_chk, and we were able to fold it into
2381 // a __memcpy_chk, we still need to return the correct end pointer.
2382 if (Ret && Func == LibFunc::stpcpy_chk)
2383 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2384 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002385}
2386
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002387Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2388 IRBuilder<> &B,
2389 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002390 Function *Callee = CI->getCalledFunction();
2391 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002392
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002393 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002394 return nullptr;
2395 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002396 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2397 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002398 return Ret;
2399 }
2400 return nullptr;
2401}
2402
2403Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002404 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2405 // Some clang users checked for _chk libcall availability using:
2406 // __has_builtin(__builtin___memcpy_chk)
2407 // When compiling with -fno-builtin, this is always true.
2408 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2409 // end up with fortified libcalls, which isn't acceptable in a freestanding
2410 // environment which only provides their non-fortified counterparts.
2411 //
2412 // Until we change clang and/or teach external users to check for availability
2413 // differently, disregard the "nobuiltin" attribute and TLI::has.
2414 //
2415 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416
2417 LibFunc::Func Func;
2418 Function *Callee = CI->getCalledFunction();
2419 StringRef FuncName = Callee->getName();
2420 IRBuilder<> Builder(CI);
2421 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2422
2423 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002424 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002425 return nullptr;
2426
2427 // We never change the calling convention.
2428 if (!ignoreCallingConv(Func) && !isCallingConvC)
2429 return nullptr;
2430
2431 switch (Func) {
2432 case LibFunc::memcpy_chk:
2433 return optimizeMemCpyChk(CI, Builder);
2434 case LibFunc::memmove_chk:
2435 return optimizeMemMoveChk(CI, Builder);
2436 case LibFunc::memset_chk:
2437 return optimizeMemSetChk(CI, Builder);
2438 case LibFunc::stpcpy_chk:
2439 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002440 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002441 case LibFunc::stpncpy_chk:
2442 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002443 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002444 default:
2445 break;
2446 }
2447 return nullptr;
2448}
2449
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002450FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2451 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2452 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}