blob: 9fabf5de7f4e63d154d9b92c000dc1a19d4057a9 [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
Davide Italianoa904e522015-10-29 02:58:44 +0000120/// \brief Check whether we can use unsafe floating point math for
121/// the function passed as input.
122static bool canUseUnsafeFPMath(Function *F) {
123
124 // FIXME: For finer-grain optimization, we need intrinsics to have the same
125 // fast-math flag decorations that are applied to FP instructions. For now,
126 // we have to rely on the function-level unsafe-fp-math attribute to do this
127 // optimization because there's no other way to express that the sqrt can be
128 // reassociated.
129 if (F->hasFnAttribute("unsafe-fp-math")) {
130 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
131 if (Attr.getValueAsString() == "true")
132 return true;
133 }
134 return false;
135}
136
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000137/// \brief Returns whether \p F matches the signature expected for the
138/// string/memory copying library function \p Func.
139/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
140/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000141static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
142 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000143 FunctionType *FT = F->getFunctionType();
144 LLVMContext &Context = F->getContext();
145 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000146 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000147 unsigned NumParams = FT->getNumParams();
148
149 // All string libfuncs return the same type as the first parameter.
150 if (FT->getReturnType() != FT->getParamType(0))
151 return false;
152
153 switch (Func) {
154 default:
155 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
156 case LibFunc::stpncpy_chk:
157 case LibFunc::strncpy_chk:
158 --NumParams; // fallthrough
159 case LibFunc::stpncpy:
160 case LibFunc::strncpy: {
161 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
162 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
163 return false;
164 break;
165 }
166 case LibFunc::strcpy_chk:
167 case LibFunc::stpcpy_chk:
168 --NumParams; // fallthrough
169 case LibFunc::stpcpy:
170 case LibFunc::strcpy: {
171 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
172 FT->getParamType(0) != PCharTy)
173 return false;
174 break;
175 }
176 case LibFunc::memmove_chk:
177 case LibFunc::memcpy_chk:
178 --NumParams; // fallthrough
179 case LibFunc::memmove:
180 case LibFunc::memcpy: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
183 return false;
184 break;
185 }
186 case LibFunc::memset_chk:
187 --NumParams; // fallthrough
188 case LibFunc::memset: {
189 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
190 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
191 return false;
192 break;
193 }
194 }
195 // If this is a fortified libcall, the last parameter is a size_t.
196 if (NumParams == FT->getNumParams() - 1)
197 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
198 return true;
199}
200
Meador Inged589ac62012-10-31 03:33:06 +0000201//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000202// String and Memory Library Call Optimizations
203//===----------------------------------------------------------------------===//
204
Chris Bienemanad070d02014-09-17 20:55:46 +0000205Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
206 Function *Callee = CI->getCalledFunction();
207 // Verify the "strcat" function prototype.
208 FunctionType *FT = Callee->getFunctionType();
209 if (FT->getNumParams() != 2||
210 FT->getReturnType() != B.getInt8PtrTy() ||
211 FT->getParamType(0) != FT->getReturnType() ||
212 FT->getParamType(1) != FT->getReturnType())
213 return nullptr;
214
215 // Extract some information from the instruction
216 Value *Dst = CI->getArgOperand(0);
217 Value *Src = CI->getArgOperand(1);
218
219 // See if we can get the length of the input string.
220 uint64_t Len = GetStringLength(Src);
221 if (Len == 0)
222 return nullptr;
223 --Len; // Unbias length.
224
225 // Handle the simple, do-nothing case: strcat(x, "") -> x
226 if (Len == 0)
227 return Dst;
228
Chris Bienemanad070d02014-09-17 20:55:46 +0000229 return emitStrLenMemCpy(Src, Dst, Len, B);
230}
231
232Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
233 IRBuilder<> &B) {
234 // We need to find the end of the destination string. That's where the
235 // memory is to be moved to. We just generate a call to strlen.
236 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
237 if (!DstLen)
238 return nullptr;
239
240 // Now that we have the destination's length, we must index into the
241 // destination's pointer to get the actual memcpy destination (end of
242 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000243 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000244
245 // We have enough information to now generate the memcpy call to do the
246 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000247 B.CreateMemCpy(CpyDst, Src,
248 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
249 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000250 return Dst;
251}
252
253Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
254 Function *Callee = CI->getCalledFunction();
255 // Verify the "strncat" function prototype.
256 FunctionType *FT = Callee->getFunctionType();
257 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
258 FT->getParamType(0) != FT->getReturnType() ||
259 FT->getParamType(1) != FT->getReturnType() ||
260 !FT->getParamType(2)->isIntegerTy())
261 return nullptr;
262
263 // Extract some information from the instruction
264 Value *Dst = CI->getArgOperand(0);
265 Value *Src = CI->getArgOperand(1);
266 uint64_t Len;
267
268 // We don't do anything if length is not constant
269 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
270 Len = LengthArg->getZExtValue();
271 else
272 return nullptr;
273
274 // See if we can get the length of the input string.
275 uint64_t SrcLen = GetStringLength(Src);
276 if (SrcLen == 0)
277 return nullptr;
278 --SrcLen; // Unbias length.
279
280 // Handle the simple, do-nothing cases:
281 // strncat(x, "", c) -> x
282 // strncat(x, c, 0) -> x
283 if (SrcLen == 0 || Len == 0)
284 return Dst;
285
Chris Bienemanad070d02014-09-17 20:55:46 +0000286 // We don't optimize this case
287 if (Len < SrcLen)
288 return nullptr;
289
290 // strncat(x, s, c) -> strcat(x, s)
291 // s is constant so the strcat can be optimized further
292 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
293}
294
295Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
296 Function *Callee = CI->getCalledFunction();
297 // Verify the "strchr" function prototype.
298 FunctionType *FT = Callee->getFunctionType();
299 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
300 FT->getParamType(0) != FT->getReturnType() ||
301 !FT->getParamType(1)->isIntegerTy(32))
302 return nullptr;
303
304 Value *SrcStr = CI->getArgOperand(0);
305
306 // If the second operand is non-constant, see if we can compute the length
307 // of the input string and turn this into memchr.
308 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
309 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000310 uint64_t Len = GetStringLength(SrcStr);
311 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
312 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000313
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
315 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
316 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000317 }
318
Chris Bienemanad070d02014-09-17 20:55:46 +0000319 // Otherwise, the character is a constant, see if the first argument is
320 // a string literal. If so, we can constant fold.
321 StringRef Str;
322 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000323 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000324 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000325 return nullptr;
326 }
327
328 // Compute the offset, make sure to handle the case when we're searching for
329 // zero (a weird way to spell strlen).
330 size_t I = (0xFF & CharC->getSExtValue()) == 0
331 ? Str.size()
332 : Str.find(CharC->getSExtValue());
333 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
334 return Constant::getNullValue(CI->getType());
335
336 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000337 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000338}
339
340Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
341 Function *Callee = CI->getCalledFunction();
342 // Verify the "strrchr" function prototype.
343 FunctionType *FT = Callee->getFunctionType();
344 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
345 FT->getParamType(0) != FT->getReturnType() ||
346 !FT->getParamType(1)->isIntegerTy(32))
347 return nullptr;
348
349 Value *SrcStr = CI->getArgOperand(0);
350 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
351
352 // Cannot fold anything if we're not looking for a constant.
353 if (!CharC)
354 return nullptr;
355
356 StringRef Str;
357 if (!getConstantStringInfo(SrcStr, Str)) {
358 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000359 if (CharC->isZero())
360 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000361 return nullptr;
362 }
363
364 // Compute the offset.
365 size_t I = (0xFF & CharC->getSExtValue()) == 0
366 ? Str.size()
367 : Str.rfind(CharC->getSExtValue());
368 if (I == StringRef::npos) // Didn't find the char. Return null.
369 return Constant::getNullValue(CI->getType());
370
371 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000372 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000373}
374
375Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
376 Function *Callee = CI->getCalledFunction();
377 // Verify the "strcmp" function prototype.
378 FunctionType *FT = Callee->getFunctionType();
379 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
380 FT->getParamType(0) != FT->getParamType(1) ||
381 FT->getParamType(0) != B.getInt8PtrTy())
382 return nullptr;
383
384 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
385 if (Str1P == Str2P) // strcmp(x,x) -> 0
386 return ConstantInt::get(CI->getType(), 0);
387
388 StringRef Str1, Str2;
389 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
390 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
391
392 // strcmp(x, y) -> cnst (if both x and y are constant strings)
393 if (HasStr1 && HasStr2)
394 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
395
396 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
397 return B.CreateNeg(
398 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
399
400 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
401 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
402
403 // strcmp(P, "x") -> memcmp(P, "x", 2)
404 uint64_t Len1 = GetStringLength(Str1P);
405 uint64_t Len2 = GetStringLength(Str2P);
406 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000407 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000408 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000409 std::min(Len1, Len2)),
410 B, DL, TLI);
411 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000412
Chris Bienemanad070d02014-09-17 20:55:46 +0000413 return nullptr;
414}
415
416Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
417 Function *Callee = CI->getCalledFunction();
418 // Verify the "strncmp" function prototype.
419 FunctionType *FT = Callee->getFunctionType();
420 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
421 FT->getParamType(0) != FT->getParamType(1) ||
422 FT->getParamType(0) != B.getInt8PtrTy() ||
423 !FT->getParamType(2)->isIntegerTy())
424 return nullptr;
425
426 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
427 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
428 return ConstantInt::get(CI->getType(), 0);
429
430 // Get the length argument if it is constant.
431 uint64_t Length;
432 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
433 Length = LengthArg->getZExtValue();
434 else
435 return nullptr;
436
437 if (Length == 0) // strncmp(x,y,0) -> 0
438 return ConstantInt::get(CI->getType(), 0);
439
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000441 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
442
443 StringRef Str1, Str2;
444 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
445 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
446
447 // strncmp(x, y) -> cnst (if both x and y are constant strings)
448 if (HasStr1 && HasStr2) {
449 StringRef SubStr1 = Str1.substr(0, Length);
450 StringRef SubStr2 = Str2.substr(0, Length);
451 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
452 }
453
454 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
455 return B.CreateNeg(
456 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
457
458 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
459 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
460
461 return nullptr;
462}
463
464Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
465 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000466
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000467 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000468 return nullptr;
469
470 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
471 if (Dst == Src) // strcpy(x,x) -> x
472 return Src;
473
Chris Bienemanad070d02014-09-17 20:55:46 +0000474 // See if we can get the length of the input string.
475 uint64_t Len = GetStringLength(Src);
476 if (Len == 0)
477 return nullptr;
478
479 // We have enough information to now generate the memcpy call to do the
480 // copy for us. Make a memcpy to copy the nul byte with align = 1.
481 B.CreateMemCpy(Dst, Src,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000482 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 return Dst;
484}
485
486Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
487 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000488 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 return nullptr;
490
491 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
492 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
493 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000494 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000495 }
496
497 // See if we can get the length of the input string.
498 uint64_t Len = GetStringLength(Src);
499 if (Len == 0)
500 return nullptr;
501
Davide Italianob7487e62015-11-02 23:07:14 +0000502 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000504 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000505 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000506
507 // We have enough information to now generate the memcpy call to do the
508 // copy for us. Make a memcpy to copy the nul byte with align = 1.
509 B.CreateMemCpy(Dst, Src, LenV, 1);
510 return DstEnd;
511}
512
513Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
514 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000515 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 return nullptr;
517
518 Value *Dst = CI->getArgOperand(0);
519 Value *Src = CI->getArgOperand(1);
520 Value *LenOp = CI->getArgOperand(2);
521
522 // See if we can get the length of the input string.
523 uint64_t SrcLen = GetStringLength(Src);
524 if (SrcLen == 0)
525 return nullptr;
526 --SrcLen;
527
528 if (SrcLen == 0) {
529 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
530 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000531 return Dst;
532 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000533
Chris Bienemanad070d02014-09-17 20:55:46 +0000534 uint64_t Len;
535 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
536 Len = LengthArg->getZExtValue();
537 else
538 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000539
Chris Bienemanad070d02014-09-17 20:55:46 +0000540 if (Len == 0)
541 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000542
Chris Bienemanad070d02014-09-17 20:55:46 +0000543 // Let strncpy handle the zero padding
544 if (Len > SrcLen + 1)
545 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000546
Davide Italianob7487e62015-11-02 23:07:14 +0000547 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000549 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000550
Chris Bienemanad070d02014-09-17 20:55:46 +0000551 return Dst;
552}
Meador Inge7fb2f732012-10-13 16:45:32 +0000553
Chris Bienemanad070d02014-09-17 20:55:46 +0000554Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
555 Function *Callee = CI->getCalledFunction();
556 FunctionType *FT = Callee->getFunctionType();
557 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
558 !FT->getReturnType()->isIntegerTy())
559 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000560
Chris Bienemanad070d02014-09-17 20:55:46 +0000561 Value *Src = CI->getArgOperand(0);
562
563 // Constant folding: strlen("xyz") -> 3
564 if (uint64_t Len = GetStringLength(Src))
565 return ConstantInt::get(CI->getType(), Len - 1);
566
567 // strlen(x?"foo":"bars") --> x ? 3 : 4
568 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
569 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
570 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
571 if (LenTrue && LenFalse) {
572 Function *Caller = CI->getParent()->getParent();
573 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
574 SI->getDebugLoc(),
575 "folded strlen(select) to select of constants");
576 return B.CreateSelect(SI->getCondition(),
577 ConstantInt::get(CI->getType(), LenTrue - 1),
578 ConstantInt::get(CI->getType(), LenFalse - 1));
579 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000580 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000581
Chris Bienemanad070d02014-09-17 20:55:46 +0000582 // strlen(x) != 0 --> *x != 0
583 // strlen(x) == 0 --> *x == 0
584 if (isOnlyUsedInZeroEqualityComparison(CI))
585 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000586
Chris Bienemanad070d02014-09-17 20:55:46 +0000587 return nullptr;
588}
Meador Inge17418502012-10-13 16:45:37 +0000589
Chris Bienemanad070d02014-09-17 20:55:46 +0000590Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
591 Function *Callee = CI->getCalledFunction();
592 FunctionType *FT = Callee->getFunctionType();
593 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
594 FT->getParamType(1) != FT->getParamType(0) ||
595 FT->getReturnType() != FT->getParamType(0))
596 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000597
Chris Bienemanad070d02014-09-17 20:55:46 +0000598 StringRef S1, S2;
599 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
600 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000601
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000602 // strpbrk(s, "") -> nullptr
603 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000604 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
605 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000606
Chris Bienemanad070d02014-09-17 20:55:46 +0000607 // Constant folding.
608 if (HasS1 && HasS2) {
609 size_t I = S1.find_first_of(S2);
610 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000611 return Constant::getNullValue(CI->getType());
612
David Blaikie3909da72015-03-30 20:42:56 +0000613 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000614 }
Meador Inge17418502012-10-13 16:45:37 +0000615
Chris Bienemanad070d02014-09-17 20:55:46 +0000616 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 if (HasS2 && S2.size() == 1)
618 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000619
620 return nullptr;
621}
622
623Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
624 Function *Callee = CI->getCalledFunction();
625 FunctionType *FT = Callee->getFunctionType();
626 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
627 !FT->getParamType(0)->isPointerTy() ||
628 !FT->getParamType(1)->isPointerTy())
629 return nullptr;
630
631 Value *EndPtr = CI->getArgOperand(1);
632 if (isa<ConstantPointerNull>(EndPtr)) {
633 // With a null EndPtr, this function won't capture the main argument.
634 // It would be readonly too, except that it still may write to errno.
635 CI->addAttribute(1, Attribute::NoCapture);
636 }
637
638 return nullptr;
639}
640
641Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
642 Function *Callee = CI->getCalledFunction();
643 FunctionType *FT = Callee->getFunctionType();
644 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
645 FT->getParamType(1) != FT->getParamType(0) ||
646 !FT->getReturnType()->isIntegerTy())
647 return nullptr;
648
649 StringRef S1, S2;
650 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
651 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
652
653 // strspn(s, "") -> 0
654 // strspn("", s) -> 0
655 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
656 return Constant::getNullValue(CI->getType());
657
658 // Constant folding.
659 if (HasS1 && HasS2) {
660 size_t Pos = S1.find_first_not_of(S2);
661 if (Pos == StringRef::npos)
662 Pos = S1.size();
663 return ConstantInt::get(CI->getType(), Pos);
664 }
665
666 return nullptr;
667}
668
669Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
670 Function *Callee = CI->getCalledFunction();
671 FunctionType *FT = Callee->getFunctionType();
672 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
673 FT->getParamType(1) != FT->getParamType(0) ||
674 !FT->getReturnType()->isIntegerTy())
675 return nullptr;
676
677 StringRef S1, S2;
678 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
679 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
680
681 // strcspn("", s) -> 0
682 if (HasS1 && S1.empty())
683 return Constant::getNullValue(CI->getType());
684
685 // Constant folding.
686 if (HasS1 && HasS2) {
687 size_t Pos = S1.find_first_of(S2);
688 if (Pos == StringRef::npos)
689 Pos = S1.size();
690 return ConstantInt::get(CI->getType(), Pos);
691 }
692
693 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000694 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000695 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
696
697 return nullptr;
698}
699
700Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
701 Function *Callee = CI->getCalledFunction();
702 FunctionType *FT = Callee->getFunctionType();
703 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
704 !FT->getParamType(1)->isPointerTy() ||
705 !FT->getReturnType()->isPointerTy())
706 return nullptr;
707
708 // fold strstr(x, x) -> x.
709 if (CI->getArgOperand(0) == CI->getArgOperand(1))
710 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
711
712 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000713 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000714 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
715 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000716 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000717 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
718 StrLen, B, DL, TLI);
719 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000720 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
722 ICmpInst *Old = cast<ICmpInst>(*UI++);
723 Value *Cmp =
724 B.CreateICmp(Old->getPredicate(), StrNCmp,
725 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
726 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000727 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000728 return CI;
729 }
Meador Inge17418502012-10-13 16:45:37 +0000730
Chris Bienemanad070d02014-09-17 20:55:46 +0000731 // See if either input string is a constant string.
732 StringRef SearchStr, ToFindStr;
733 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
734 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
735
736 // fold strstr(x, "") -> x.
737 if (HasStr2 && ToFindStr.empty())
738 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
739
740 // If both strings are known, constant fold it.
741 if (HasStr1 && HasStr2) {
742 size_t Offset = SearchStr.find(ToFindStr);
743
744 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000745 return Constant::getNullValue(CI->getType());
746
Chris Bienemanad070d02014-09-17 20:55:46 +0000747 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
748 Value *Result = CastToCStr(CI->getArgOperand(0), B);
749 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
750 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000751 }
Meador Inge17418502012-10-13 16:45:37 +0000752
Chris Bienemanad070d02014-09-17 20:55:46 +0000753 // fold strstr(x, "y") -> strchr(x, 'y').
754 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000755 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000756 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
757 }
758 return nullptr;
759}
Meador Inge40b6fac2012-10-15 03:47:37 +0000760
Benjamin Kramer691363e2015-03-21 15:36:21 +0000761Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
762 Function *Callee = CI->getCalledFunction();
763 FunctionType *FT = Callee->getFunctionType();
764 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
765 !FT->getParamType(1)->isIntegerTy(32) ||
766 !FT->getParamType(2)->isIntegerTy() ||
767 !FT->getReturnType()->isPointerTy())
768 return nullptr;
769
770 Value *SrcStr = CI->getArgOperand(0);
771 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
772 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
773
774 // memchr(x, y, 0) -> null
775 if (LenC && LenC->isNullValue())
776 return Constant::getNullValue(CI->getType());
777
Benjamin Kramer7857d722015-03-21 21:09:33 +0000778 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000779 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000780 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000781 return nullptr;
782
783 // Truncate the string to LenC. If Str is smaller than LenC we will still only
784 // scan the string, as reading past the end of it is undefined and we can just
785 // return null if we don't find the char.
786 Str = Str.substr(0, LenC->getZExtValue());
787
Benjamin Kramer7857d722015-03-21 21:09:33 +0000788 // If the char is variable but the input str and length are not we can turn
789 // this memchr call into a simple bit field test. Of course this only works
790 // when the return value is only checked against null.
791 //
792 // It would be really nice to reuse switch lowering here but we can't change
793 // the CFG at this point.
794 //
795 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
796 // after bounds check.
797 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000798 unsigned char Max =
799 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
800 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000801
802 // Make sure the bit field we're about to create fits in a register on the
803 // target.
804 // FIXME: On a 64 bit architecture this prevents us from using the
805 // interesting range of alpha ascii chars. We could do better by emitting
806 // two bitfields or shifting the range by 64 if no lower chars are used.
807 if (!DL.fitsInLegalInteger(Max + 1))
808 return nullptr;
809
810 // For the bit field use a power-of-2 type with at least 8 bits to avoid
811 // creating unnecessary illegal types.
812 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
813
814 // Now build the bit field.
815 APInt Bitfield(Width, 0);
816 for (char C : Str)
817 Bitfield.setBit((unsigned char)C);
818 Value *BitfieldC = B.getInt(Bitfield);
819
820 // First check that the bit field access is within bounds.
821 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
822 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
823 "memchr.bounds");
824
825 // Create code that checks if the given bit is set in the field.
826 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
827 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
828
829 // Finally merge both checks and cast to pointer type. The inttoptr
830 // implicitly zexts the i1 to intptr type.
831 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
832 }
833
834 // Check if all arguments are constants. If so, we can constant fold.
835 if (!CharC)
836 return nullptr;
837
Benjamin Kramer691363e2015-03-21 15:36:21 +0000838 // Compute the offset.
839 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
840 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
841 return Constant::getNullValue(CI->getType());
842
843 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000844 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000845}
846
Chris Bienemanad070d02014-09-17 20:55:46 +0000847Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
848 Function *Callee = CI->getCalledFunction();
849 FunctionType *FT = Callee->getFunctionType();
850 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
851 !FT->getParamType(1)->isPointerTy() ||
852 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000853 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000854
Chris Bienemanad070d02014-09-17 20:55:46 +0000855 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000856
Chris Bienemanad070d02014-09-17 20:55:46 +0000857 if (LHS == RHS) // memcmp(s,s,x) -> 0
858 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000859
Chris Bienemanad070d02014-09-17 20:55:46 +0000860 // Make sure we have a constant length.
861 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
862 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000863 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000864 uint64_t Len = LenC->getZExtValue();
865
866 if (Len == 0) // memcmp(s1,s2,0) -> 0
867 return Constant::getNullValue(CI->getType());
868
869 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
870 if (Len == 1) {
871 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
872 CI->getType(), "lhsv");
873 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
874 CI->getType(), "rhsv");
875 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000876 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000877
Chad Rosierdc655322015-08-28 18:30:18 +0000878 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
879 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
880
881 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
882 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
883
884 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
885 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
886
887 Type *LHSPtrTy =
888 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
889 Type *RHSPtrTy =
890 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
891
892 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
893 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
894
895 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
896 }
897 }
898
Chris Bienemanad070d02014-09-17 20:55:46 +0000899 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
900 StringRef LHSStr, RHSStr;
901 if (getConstantStringInfo(LHS, LHSStr) &&
902 getConstantStringInfo(RHS, RHSStr)) {
903 // Make sure we're not reading out-of-bounds memory.
904 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000905 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000906 // Fold the memcmp and normalize the result. This way we get consistent
907 // results across multiple platforms.
908 uint64_t Ret = 0;
909 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
910 if (Cmp < 0)
911 Ret = -1;
912 else if (Cmp > 0)
913 Ret = 1;
914 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000915 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000916
Chris Bienemanad070d02014-09-17 20:55:46 +0000917 return nullptr;
918}
Meador Inge9a6a1902012-10-31 00:20:56 +0000919
Chris Bienemanad070d02014-09-17 20:55:46 +0000920Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
921 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000922
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000923 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000924 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000925
Chris Bienemanad070d02014-09-17 20:55:46 +0000926 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
927 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
928 CI->getArgOperand(2), 1);
929 return CI->getArgOperand(0);
930}
Meador Inge05a625a2012-10-31 14:58:26 +0000931
Chris Bienemanad070d02014-09-17 20:55:46 +0000932Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
933 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000934
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000936 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000937
Chris Bienemanad070d02014-09-17 20:55:46 +0000938 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
939 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
940 CI->getArgOperand(2), 1);
941 return CI->getArgOperand(0);
942}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000943
Chris Bienemanad070d02014-09-17 20:55:46 +0000944Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
945 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000946
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000948 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000949
Chris Bienemanad070d02014-09-17 20:55:46 +0000950 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
951 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
952 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
953 return CI->getArgOperand(0);
954}
Meador Inged4825782012-11-11 06:49:03 +0000955
Meador Inge193e0352012-11-13 04:16:17 +0000956//===----------------------------------------------------------------------===//
957// Math Library Optimizations
958//===----------------------------------------------------------------------===//
959
Matthias Braund34e4d22014-12-03 21:46:33 +0000960/// Return a variant of Val with float type.
961/// Currently this works in two cases: If Val is an FPExtension of a float
962/// value to something bigger, simply return the operand.
963/// If Val is a ConstantFP but can be converted to a float ConstantFP without
964/// loss of precision do so.
965static Value *valueHasFloatPrecision(Value *Val) {
966 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
967 Value *Op = Cast->getOperand(0);
968 if (Op->getType()->isFloatTy())
969 return Op;
970 }
971 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
972 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000973 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000974 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000975 &losesInfo);
976 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000977 return ConstantFP::get(Const->getContext(), F);
978 }
979 return nullptr;
980}
981
Meador Inge193e0352012-11-13 04:16:17 +0000982//===----------------------------------------------------------------------===//
983// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
984
Chris Bienemanad070d02014-09-17 20:55:46 +0000985Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
986 bool CheckRetType) {
987 Function *Callee = CI->getCalledFunction();
988 FunctionType *FT = Callee->getFunctionType();
989 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
990 !FT->getParamType(0)->isDoubleTy())
991 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000992
Chris Bienemanad070d02014-09-17 20:55:46 +0000993 if (CheckRetType) {
994 // Check if all the uses for function like 'sin' are converted to float.
995 for (User *U : CI->users()) {
996 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
997 if (!Cast || !Cast->getType()->isFloatTy())
998 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000999 }
Meador Inge193e0352012-11-13 04:16:17 +00001000 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001001
1002 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +00001003 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1004 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +00001005 return nullptr;
1006
1007 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001008 if (Callee->isIntrinsic()) {
1009 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001010 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001011 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1012 V = B.CreateCall(F, V);
1013 } else {
1014 // The call is a library call rather than an intrinsic.
1015 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1016 }
1017
Chris Bienemanad070d02014-09-17 20:55:46 +00001018 return B.CreateFPExt(V, B.getDoubleTy());
1019}
Meador Inge193e0352012-11-13 04:16:17 +00001020
Yi Jiang6ab044e2013-12-16 22:42:40 +00001021// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001022Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1023 Function *Callee = CI->getCalledFunction();
1024 FunctionType *FT = Callee->getFunctionType();
1025 // Just make sure this has 2 arguments of the same FP type, which match the
1026 // result type.
1027 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1028 FT->getParamType(0) != FT->getParamType(1) ||
1029 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001030 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001031
Chris Bienemanad070d02014-09-17 20:55:46 +00001032 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001033 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1034 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1035 if (V1 == nullptr)
1036 return nullptr;
1037 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1038 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001039 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001040
1041 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001042 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001043 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001044 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1045 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001046 return B.CreateFPExt(V, B.getDoubleTy());
1047}
1048
1049Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1050 Function *Callee = CI->getCalledFunction();
1051 Value *Ret = nullptr;
1052 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1053 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001054 }
1055
Chris Bienemanad070d02014-09-17 20:55:46 +00001056 FunctionType *FT = Callee->getFunctionType();
1057 // Just make sure this has 1 argument of FP type, which matches the
1058 // result type.
1059 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1060 !FT->getParamType(0)->isFloatingPointTy())
1061 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001062
Chris Bienemanad070d02014-09-17 20:55:46 +00001063 // cos(-x) -> cos(x)
1064 Value *Op1 = CI->getArgOperand(0);
1065 if (BinaryOperator::isFNeg(Op1)) {
1066 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1067 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1068 }
1069 return Ret;
1070}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001071
Chris Bienemanad070d02014-09-17 20:55:46 +00001072Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1073 Function *Callee = CI->getCalledFunction();
1074
1075 Value *Ret = nullptr;
1076 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1077 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001078 }
1079
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 FunctionType *FT = Callee->getFunctionType();
1081 // Just make sure this has 2 arguments of the same FP type, which match the
1082 // result type.
1083 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1084 FT->getParamType(0) != FT->getParamType(1) ||
1085 !FT->getParamType(0)->isFloatingPointTy())
1086 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001087
Chris Bienemanad070d02014-09-17 20:55:46 +00001088 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1089 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1090 // pow(1.0, x) -> 1.0
1091 if (Op1C->isExactlyValue(1.0))
1092 return Op1C;
1093 // pow(2.0, x) -> exp2(x)
1094 if (Op1C->isExactlyValue(2.0) &&
1095 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1096 LibFunc::exp2l))
1097 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1098 // pow(10.0, x) -> exp10(x)
1099 if (Op1C->isExactlyValue(10.0) &&
1100 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1101 LibFunc::exp10l))
1102 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1103 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001104 }
1105
Chris Bienemanad070d02014-09-17 20:55:46 +00001106 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1107 if (!Op2C)
1108 return Ret;
1109
1110 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1111 return ConstantFP::get(CI->getType(), 1.0);
1112
1113 if (Op2C->isExactlyValue(0.5) &&
1114 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1115 LibFunc::sqrtl) &&
1116 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1117 LibFunc::fabsl)) {
1118 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1119 // This is faster than calling pow, and still handles negative zero
1120 // and negative infinity correctly.
1121 // TODO: In fast-math mode, this could be just sqrt(x).
1122 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1123 Value *Inf = ConstantFP::getInfinity(CI->getType());
1124 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1125 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1126 Value *FAbs =
1127 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1128 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1129 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1130 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001131 }
1132
Chris Bienemanad070d02014-09-17 20:55:46 +00001133 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1134 return Op1;
1135 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1136 return B.CreateFMul(Op1, Op1, "pow2");
1137 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1138 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1139 return nullptr;
1140}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001141
Chris Bienemanad070d02014-09-17 20:55:46 +00001142Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1143 Function *Callee = CI->getCalledFunction();
1144 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001145
Chris Bienemanad070d02014-09-17 20:55:46 +00001146 Value *Ret = nullptr;
1147 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1148 TLI->has(LibFunc::exp2f)) {
1149 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001150 }
1151
Chris Bienemanad070d02014-09-17 20:55:46 +00001152 FunctionType *FT = Callee->getFunctionType();
1153 // Just make sure this has 1 argument of FP type, which matches the
1154 // result type.
1155 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1156 !FT->getParamType(0)->isFloatingPointTy())
1157 return Ret;
1158
1159 Value *Op = CI->getArgOperand(0);
1160 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1161 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1162 LibFunc::Func LdExp = LibFunc::ldexpl;
1163 if (Op->getType()->isFloatTy())
1164 LdExp = LibFunc::ldexpf;
1165 else if (Op->getType()->isDoubleTy())
1166 LdExp = LibFunc::ldexp;
1167
1168 if (TLI->has(LdExp)) {
1169 Value *LdExpArg = nullptr;
1170 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1171 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1172 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1173 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1174 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1175 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1176 }
1177
1178 if (LdExpArg) {
1179 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1180 if (!Op->getType()->isFloatTy())
1181 One = ConstantExpr::getFPExtend(One, Op->getType());
1182
1183 Module *M = Caller->getParent();
1184 Value *Callee =
1185 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001186 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001187 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001188 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1189 CI->setCallingConv(F->getCallingConv());
1190
1191 return CI;
1192 }
1193 }
1194 return Ret;
1195}
1196
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001197Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1198 Function *Callee = CI->getCalledFunction();
1199
1200 Value *Ret = nullptr;
1201 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1202 Ret = optimizeUnaryDoubleFP(CI, B, false);
1203 }
1204
1205 FunctionType *FT = Callee->getFunctionType();
1206 // Make sure this has 1 argument of FP type which matches the result type.
1207 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1208 !FT->getParamType(0)->isFloatingPointTy())
1209 return Ret;
1210
1211 Value *Op = CI->getArgOperand(0);
1212 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1213 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1214 if (I->getOpcode() == Instruction::FMul)
1215 if (I->getOperand(0) == I->getOperand(1))
1216 return Op;
1217 }
1218 return Ret;
1219}
1220
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001221Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1222 // If we can shrink the call to a float function rather than a double
1223 // function, do that first.
1224 Function *Callee = CI->getCalledFunction();
1225 if ((Callee->getName() == "fmin" && TLI->has(LibFunc::fminf)) ||
1226 (Callee->getName() == "fmax" && TLI->has(LibFunc::fmaxf))) {
1227 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1228 if (Ret)
1229 return Ret;
1230 }
1231
1232 // Make sure this has 2 arguments of FP type which match the result type.
1233 FunctionType *FT = Callee->getFunctionType();
1234 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1235 FT->getParamType(0) != FT->getParamType(1) ||
1236 !FT->getParamType(0)->isFloatingPointTy())
1237 return nullptr;
1238
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001239 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001240 FastMathFlags FMF;
1241 Function *F = CI->getParent()->getParent();
Davide Italianoa904e522015-10-29 02:58:44 +00001242 if (canUseUnsafeFPMath(F)) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001243 // Unsafe algebra sets all fast-math-flags to true.
1244 FMF.setUnsafeAlgebra();
1245 } else {
1246 // At a minimum, no-nans-fp-math must be true.
Davide Italianoa904e522015-10-29 02:58:44 +00001247 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001248 if (Attr.getValueAsString() != "true")
1249 return nullptr;
1250 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1251 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001252 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001253 // might be impractical."
1254 FMF.setNoSignedZeros();
1255 FMF.setNoNaNs();
1256 }
1257 B.SetFastMathFlags(FMF);
1258
1259 // We have a relaxed floating-point environment. We can ignore NaN-handling
1260 // and transform to a compare and select. We do not have to consider errno or
1261 // exceptions, because fmin/fmax do not have those.
1262 Value *Op0 = CI->getArgOperand(0);
1263 Value *Op1 = CI->getArgOperand(1);
1264 Value *Cmp = Callee->getName().startswith("fmin") ?
1265 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1266 return B.CreateSelect(Cmp, Op0, Op1);
1267}
1268
Sanjay Patelc699a612014-10-16 18:48:17 +00001269Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1270 Function *Callee = CI->getCalledFunction();
1271
1272 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001273 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1274 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001275 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianoa904e522015-10-29 02:58:44 +00001276 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1277 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001278
Sanjay Patelc699a612014-10-16 18:48:17 +00001279 Value *Op = CI->getArgOperand(0);
1280 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1281 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1282 // We're looking for a repeated factor in a multiplication tree,
1283 // so we can do this fold: sqrt(x * x) -> fabs(x);
1284 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1285 Value *Op0 = I->getOperand(0);
1286 Value *Op1 = I->getOperand(1);
1287 Value *RepeatOp = nullptr;
1288 Value *OtherOp = nullptr;
1289 if (Op0 == Op1) {
1290 // Simple match: the operands of the multiply are identical.
1291 RepeatOp = Op0;
1292 } else {
1293 // Look for a more complicated pattern: one of the operands is itself
1294 // a multiply, so search for a common factor in that multiply.
1295 // Note: We don't bother looking any deeper than this first level or for
1296 // variations of this pattern because instcombine's visitFMUL and/or the
1297 // reassociation pass should give us this form.
1298 Value *OtherMul0, *OtherMul1;
1299 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1300 // Pattern: sqrt((x * y) * z)
1301 if (OtherMul0 == OtherMul1) {
1302 // Matched: sqrt((x * x) * z)
1303 RepeatOp = OtherMul0;
1304 OtherOp = Op1;
1305 }
1306 }
1307 }
1308 if (RepeatOp) {
1309 // Fast math flags for any created instructions should match the sqrt
1310 // and multiply.
1311 // FIXME: We're not checking the sqrt because it doesn't have
1312 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001313 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001314 B.SetFastMathFlags(I->getFastMathFlags());
1315 // If we found a repeated factor, hoist it out of the square root and
1316 // replace it with the fabs of that factor.
1317 Module *M = Callee->getParent();
1318 Type *ArgType = Op->getType();
1319 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1320 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1321 if (OtherOp) {
1322 // If we found a non-repeated factor, we still need to get its square
1323 // root. We then multiply that by the value that was simplified out
1324 // of the square root calculation.
1325 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1326 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1327 return B.CreateFMul(FabsCall, SqrtCall);
1328 }
1329 return FabsCall;
1330 }
1331 }
1332 }
1333 return Ret;
1334}
1335
Chris Bienemanad070d02014-09-17 20:55:46 +00001336static bool isTrigLibCall(CallInst *CI);
1337static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1338 bool UseFloat, Value *&Sin, Value *&Cos,
1339 Value *&SinCos);
1340
1341Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1342
1343 // Make sure the prototype is as expected, otherwise the rest of the
1344 // function is probably invalid and likely to abort.
1345 if (!isTrigLibCall(CI))
1346 return nullptr;
1347
1348 Value *Arg = CI->getArgOperand(0);
1349 SmallVector<CallInst *, 1> SinCalls;
1350 SmallVector<CallInst *, 1> CosCalls;
1351 SmallVector<CallInst *, 1> SinCosCalls;
1352
1353 bool IsFloat = Arg->getType()->isFloatTy();
1354
1355 // Look for all compatible sinpi, cospi and sincospi calls with the same
1356 // argument. If there are enough (in some sense) we can make the
1357 // substitution.
1358 for (User *U : Arg->users())
1359 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1360 SinCosCalls);
1361
1362 // It's only worthwhile if both sinpi and cospi are actually used.
1363 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1364 return nullptr;
1365
1366 Value *Sin, *Cos, *SinCos;
1367 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1368
1369 replaceTrigInsts(SinCalls, Sin);
1370 replaceTrigInsts(CosCalls, Cos);
1371 replaceTrigInsts(SinCosCalls, SinCos);
1372
1373 return nullptr;
1374}
1375
1376static bool isTrigLibCall(CallInst *CI) {
1377 Function *Callee = CI->getCalledFunction();
1378 FunctionType *FT = Callee->getFunctionType();
1379
1380 // We can only hope to do anything useful if we can ignore things like errno
1381 // and floating-point exceptions.
1382 bool AttributesSafe =
1383 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1384
1385 // Other than that we need float(float) or double(double)
1386 return AttributesSafe && FT->getNumParams() == 1 &&
1387 FT->getReturnType() == FT->getParamType(0) &&
1388 (FT->getParamType(0)->isFloatTy() ||
1389 FT->getParamType(0)->isDoubleTy());
1390}
1391
1392void
1393LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1394 SmallVectorImpl<CallInst *> &SinCalls,
1395 SmallVectorImpl<CallInst *> &CosCalls,
1396 SmallVectorImpl<CallInst *> &SinCosCalls) {
1397 CallInst *CI = dyn_cast<CallInst>(Val);
1398
1399 if (!CI)
1400 return;
1401
1402 Function *Callee = CI->getCalledFunction();
1403 StringRef FuncName = Callee->getName();
1404 LibFunc::Func Func;
1405 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1406 return;
1407
1408 if (IsFloat) {
1409 if (Func == LibFunc::sinpif)
1410 SinCalls.push_back(CI);
1411 else if (Func == LibFunc::cospif)
1412 CosCalls.push_back(CI);
1413 else if (Func == LibFunc::sincospif_stret)
1414 SinCosCalls.push_back(CI);
1415 } else {
1416 if (Func == LibFunc::sinpi)
1417 SinCalls.push_back(CI);
1418 else if (Func == LibFunc::cospi)
1419 CosCalls.push_back(CI);
1420 else if (Func == LibFunc::sincospi_stret)
1421 SinCosCalls.push_back(CI);
1422 }
1423}
1424
1425void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1426 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001427 for (CallInst *C : Calls)
1428 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001429}
1430
1431void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1432 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1433 Type *ArgTy = Arg->getType();
1434 Type *ResTy;
1435 StringRef Name;
1436
1437 Triple T(OrigCallee->getParent()->getTargetTriple());
1438 if (UseFloat) {
1439 Name = "__sincospif_stret";
1440
1441 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1442 // x86_64 can't use {float, float} since that would be returned in both
1443 // xmm0 and xmm1, which isn't what a real struct would do.
1444 ResTy = T.getArch() == Triple::x86_64
1445 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001446 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001447 } else {
1448 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001449 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001450 }
1451
1452 Module *M = OrigCallee->getParent();
1453 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001454 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001455
1456 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1457 // If the argument is an instruction, it must dominate all uses so put our
1458 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001459 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001460 } else {
1461 // Otherwise (e.g. for a constant) the beginning of the function is as
1462 // good a place as any.
1463 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1464 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1465 }
1466
1467 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1468
1469 if (SinCos->getType()->isStructTy()) {
1470 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1471 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1472 } else {
1473 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1474 "sinpi");
1475 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1476 "cospi");
1477 }
1478}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001479
Meador Inge7415f842012-11-25 20:45:27 +00001480//===----------------------------------------------------------------------===//
1481// Integer Library Call Optimizations
1482//===----------------------------------------------------------------------===//
1483
Davide Italiano396f3ee2015-10-31 23:17:45 +00001484static bool checkIntUnaryReturnAndParam(Function *Callee) {
1485 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001486 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1487 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001488}
1489
Chris Bienemanad070d02014-09-17 20:55:46 +00001490Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1491 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001492 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001493 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001494 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001495
Chris Bienemanad070d02014-09-17 20:55:46 +00001496 // Constant fold.
1497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1498 if (CI->isZero()) // ffs(0) -> 0.
1499 return B.getInt32(0);
1500 // ffs(c) -> cttz(c)+1
1501 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001502 }
Meador Inge7415f842012-11-25 20:45:27 +00001503
Chris Bienemanad070d02014-09-17 20:55:46 +00001504 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1505 Type *ArgType = Op->getType();
1506 Value *F =
1507 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001508 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1510 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001511
Chris Bienemanad070d02014-09-17 20:55:46 +00001512 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1513 return B.CreateSelect(Cond, V, B.getInt32(0));
1514}
Meador Ingea0b6d872012-11-26 00:24:07 +00001515
Chris Bienemanad070d02014-09-17 20:55:46 +00001516Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1517 Function *Callee = CI->getCalledFunction();
1518 FunctionType *FT = Callee->getFunctionType();
1519 // We require integer(integer) where the types agree.
1520 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1521 FT->getParamType(0) != FT->getReturnType())
1522 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001523
Chris Bienemanad070d02014-09-17 20:55:46 +00001524 // abs(x) -> x >s -1 ? x : -x
1525 Value *Op = CI->getArgOperand(0);
1526 Value *Pos =
1527 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1528 Value *Neg = B.CreateNeg(Op, "neg");
1529 return B.CreateSelect(Pos, Op, Neg);
1530}
Meador Inge9a59ab62012-11-26 02:31:59 +00001531
Chris Bienemanad070d02014-09-17 20:55:46 +00001532Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001533 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001534 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001535
Chris Bienemanad070d02014-09-17 20:55:46 +00001536 // isdigit(c) -> (c-'0') <u 10
1537 Value *Op = CI->getArgOperand(0);
1538 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1539 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1540 return B.CreateZExt(Op, CI->getType());
1541}
Meador Ingea62a39e2012-11-26 03:10:07 +00001542
Chris Bienemanad070d02014-09-17 20:55:46 +00001543Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001544 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001545 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001546
Chris Bienemanad070d02014-09-17 20:55:46 +00001547 // isascii(c) -> c <u 128
1548 Value *Op = CI->getArgOperand(0);
1549 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1550 return B.CreateZExt(Op, CI->getType());
1551}
1552
1553Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001554 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 return nullptr;
1556
1557 // toascii(c) -> c & 0x7f
1558 return B.CreateAnd(CI->getArgOperand(0),
1559 ConstantInt::get(CI->getType(), 0x7F));
1560}
Meador Inge604937d2012-11-26 03:38:52 +00001561
Meador Inge08ca1152012-11-26 20:37:20 +00001562//===----------------------------------------------------------------------===//
1563// Formatting and IO Library Call Optimizations
1564//===----------------------------------------------------------------------===//
1565
Chris Bienemanad070d02014-09-17 20:55:46 +00001566static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001567
Chris Bienemanad070d02014-09-17 20:55:46 +00001568Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1569 int StreamArg) {
1570 // Error reporting calls should be cold, mark them as such.
1571 // This applies even to non-builtin calls: it is only a hint and applies to
1572 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001573
Chris Bienemanad070d02014-09-17 20:55:46 +00001574 // This heuristic was suggested in:
1575 // Improving Static Branch Prediction in a Compiler
1576 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1577 // Proceedings of PACT'98, Oct. 1998, IEEE
1578 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001579
Chris Bienemanad070d02014-09-17 20:55:46 +00001580 if (!CI->hasFnAttr(Attribute::Cold) &&
1581 isReportingError(Callee, CI, StreamArg)) {
1582 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1583 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001584
Chris Bienemanad070d02014-09-17 20:55:46 +00001585 return nullptr;
1586}
1587
1588static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001589 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001590 return false;
1591
1592 if (StreamArg < 0)
1593 return true;
1594
1595 // These functions might be considered cold, but only if their stream
1596 // argument is stderr.
1597
1598 if (StreamArg >= (int)CI->getNumArgOperands())
1599 return false;
1600 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1601 if (!LI)
1602 return false;
1603 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1604 if (!GV || !GV->isDeclaration())
1605 return false;
1606 return GV->getName() == "stderr";
1607}
1608
1609Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1610 // Check for a fixed format string.
1611 StringRef FormatStr;
1612 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001613 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001614
Chris Bienemanad070d02014-09-17 20:55:46 +00001615 // Empty format string -> noop.
1616 if (FormatStr.empty()) // Tolerate printf's declared void.
1617 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001618
Chris Bienemanad070d02014-09-17 20:55:46 +00001619 // Do not do any of the following transformations if the printf return value
1620 // is used, in general the printf return value is not compatible with either
1621 // putchar() or puts().
1622 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001623 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001624
1625 // printf("x") -> putchar('x'), even for '%'.
1626 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001627 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001628 if (CI->use_empty() || !Res)
1629 return Res;
1630 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001631 }
1632
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 // printf("foo\n") --> puts("foo")
1634 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1635 FormatStr.find('%') == StringRef::npos) { // No format characters.
1636 // Create a string literal with no \n on it. We expect the constant merge
1637 // pass to be run after this pass, to merge duplicate strings.
1638 FormatStr = FormatStr.drop_back();
1639 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001640 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001641 return (CI->use_empty() || !NewCI)
1642 ? NewCI
1643 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1644 }
Meador Inge08ca1152012-11-26 20:37:20 +00001645
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 // Optimize specific format strings.
1647 // printf("%c", chr) --> putchar(chr)
1648 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1649 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001650 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001651
Chris Bienemanad070d02014-09-17 20:55:46 +00001652 if (CI->use_empty() || !Res)
1653 return Res;
1654 return B.CreateIntCast(Res, CI->getType(), true);
1655 }
1656
1657 // printf("%s\n", str) --> puts(str)
1658 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1659 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001660 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 }
1662 return nullptr;
1663}
1664
1665Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1666
1667 Function *Callee = CI->getCalledFunction();
1668 // Require one fixed pointer argument and an integer/void result.
1669 FunctionType *FT = Callee->getFunctionType();
1670 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1671 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1672 return nullptr;
1673
1674 if (Value *V = optimizePrintFString(CI, B)) {
1675 return V;
1676 }
1677
1678 // printf(format, ...) -> iprintf(format, ...) if no floating point
1679 // arguments.
1680 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1681 Module *M = B.GetInsertBlock()->getParent()->getParent();
1682 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001683 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001684 CallInst *New = cast<CallInst>(CI->clone());
1685 New->setCalledFunction(IPrintFFn);
1686 B.Insert(New);
1687 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001688 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001689 return nullptr;
1690}
Meador Inge08ca1152012-11-26 20:37:20 +00001691
Chris Bienemanad070d02014-09-17 20:55:46 +00001692Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1693 // Check for a fixed format string.
1694 StringRef FormatStr;
1695 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001696 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001697
Chris Bienemanad070d02014-09-17 20:55:46 +00001698 // If we just have a format string (nothing else crazy) transform it.
1699 if (CI->getNumArgOperands() == 2) {
1700 // Make sure there's no % in the constant array. We could try to handle
1701 // %% -> % in the future if we cared.
1702 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1703 if (FormatStr[i] == '%')
1704 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001705
Chris Bienemanad070d02014-09-17 20:55:46 +00001706 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001707 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1708 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1709 FormatStr.size() + 1),
1710 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001712 }
Meador Ingef8e72502012-11-29 15:45:43 +00001713
Chris Bienemanad070d02014-09-17 20:55:46 +00001714 // The remaining optimizations require the format string to be "%s" or "%c"
1715 // and have an extra operand.
1716 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1717 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001718 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001719
Chris Bienemanad070d02014-09-17 20:55:46 +00001720 // Decode the second character of the format string.
1721 if (FormatStr[1] == 'c') {
1722 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1723 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1724 return nullptr;
1725 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1726 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1727 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001728 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001729 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001730
Chris Bienemanad070d02014-09-17 20:55:46 +00001731 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001732 }
1733
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001735 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1736 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1737 return nullptr;
1738
1739 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1740 if (!Len)
1741 return nullptr;
1742 Value *IncLen =
1743 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1744 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1745
1746 // The sprintf result is the unincremented number of bytes in the string.
1747 return B.CreateIntCast(Len, CI->getType(), false);
1748 }
1749 return nullptr;
1750}
1751
1752Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1753 Function *Callee = CI->getCalledFunction();
1754 // Require two fixed pointer arguments and an integer result.
1755 FunctionType *FT = Callee->getFunctionType();
1756 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1757 !FT->getParamType(1)->isPointerTy() ||
1758 !FT->getReturnType()->isIntegerTy())
1759 return nullptr;
1760
1761 if (Value *V = optimizeSPrintFString(CI, B)) {
1762 return V;
1763 }
1764
1765 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1766 // point arguments.
1767 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1768 Module *M = B.GetInsertBlock()->getParent()->getParent();
1769 Constant *SIPrintFFn =
1770 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1771 CallInst *New = cast<CallInst>(CI->clone());
1772 New->setCalledFunction(SIPrintFFn);
1773 B.Insert(New);
1774 return New;
1775 }
1776 return nullptr;
1777}
1778
1779Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1780 optimizeErrorReporting(CI, B, 0);
1781
1782 // All the optimizations depend on the format string.
1783 StringRef FormatStr;
1784 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1785 return nullptr;
1786
1787 // Do not do any of the following transformations if the fprintf return
1788 // value is used, in general the fprintf return value is not compatible
1789 // with fwrite(), fputc() or fputs().
1790 if (!CI->use_empty())
1791 return nullptr;
1792
1793 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1794 if (CI->getNumArgOperands() == 2) {
1795 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1796 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1797 return nullptr; // We found a format specifier.
1798
Chris Bienemanad070d02014-09-17 20:55:46 +00001799 return EmitFWrite(
1800 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001801 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001802 CI->getArgOperand(0), B, DL, TLI);
1803 }
1804
1805 // The remaining optimizations require the format string to be "%s" or "%c"
1806 // and have an extra operand.
1807 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1808 CI->getNumArgOperands() < 3)
1809 return nullptr;
1810
1811 // Decode the second character of the format string.
1812 if (FormatStr[1] == 'c') {
1813 // fprintf(F, "%c", chr) --> fputc(chr, F)
1814 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1815 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001816 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001817 }
1818
1819 if (FormatStr[1] == 's') {
1820 // fprintf(F, "%s", str) --> fputs(str, F)
1821 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1822 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001823 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 }
1825 return nullptr;
1826}
1827
1828Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1829 Function *Callee = CI->getCalledFunction();
1830 // Require two fixed paramters as pointers and integer result.
1831 FunctionType *FT = Callee->getFunctionType();
1832 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1833 !FT->getParamType(1)->isPointerTy() ||
1834 !FT->getReturnType()->isIntegerTy())
1835 return nullptr;
1836
1837 if (Value *V = optimizeFPrintFString(CI, B)) {
1838 return V;
1839 }
1840
1841 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1842 // floating point arguments.
1843 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1844 Module *M = B.GetInsertBlock()->getParent()->getParent();
1845 Constant *FIPrintFFn =
1846 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1847 CallInst *New = cast<CallInst>(CI->clone());
1848 New->setCalledFunction(FIPrintFFn);
1849 B.Insert(New);
1850 return New;
1851 }
1852 return nullptr;
1853}
1854
1855Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1856 optimizeErrorReporting(CI, B, 3);
1857
1858 Function *Callee = CI->getCalledFunction();
1859 // Require a pointer, an integer, an integer, a pointer, returning integer.
1860 FunctionType *FT = Callee->getFunctionType();
1861 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1862 !FT->getParamType(1)->isIntegerTy() ||
1863 !FT->getParamType(2)->isIntegerTy() ||
1864 !FT->getParamType(3)->isPointerTy() ||
1865 !FT->getReturnType()->isIntegerTy())
1866 return nullptr;
1867
1868 // Get the element size and count.
1869 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1870 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1871 if (!SizeC || !CountC)
1872 return nullptr;
1873 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1874
1875 // If this is writing zero records, remove the call (it's a noop).
1876 if (Bytes == 0)
1877 return ConstantInt::get(CI->getType(), 0);
1878
1879 // If this is writing one byte, turn it into fputc.
1880 // This optimisation is only valid, if the return value is unused.
1881 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1882 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001883 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1885 }
1886
1887 return nullptr;
1888}
1889
1890Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1891 optimizeErrorReporting(CI, B, 1);
1892
1893 Function *Callee = CI->getCalledFunction();
1894
Chris Bienemanad070d02014-09-17 20:55:46 +00001895 // Require two pointers. Also, we can't optimize if return value is used.
1896 FunctionType *FT = Callee->getFunctionType();
1897 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1898 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1899 return nullptr;
1900
1901 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1902 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1903 if (!Len)
1904 return nullptr;
1905
1906 // Known to have no uses (see above).
1907 return EmitFWrite(
1908 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001909 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001910 CI->getArgOperand(1), B, DL, TLI);
1911}
1912
1913Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1914 Function *Callee = CI->getCalledFunction();
1915 // Require one fixed pointer argument and an integer/void result.
1916 FunctionType *FT = Callee->getFunctionType();
1917 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1918 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1919 return nullptr;
1920
1921 // Check for a constant string.
1922 StringRef Str;
1923 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1924 return nullptr;
1925
1926 if (Str.empty() && CI->use_empty()) {
1927 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001928 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001929 if (CI->use_empty() || !Res)
1930 return Res;
1931 return B.CreateIntCast(Res, CI->getType(), true);
1932 }
1933
1934 return nullptr;
1935}
1936
1937bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001938 LibFunc::Func Func;
1939 SmallString<20> FloatFuncName = FuncName;
1940 FloatFuncName += 'f';
1941 if (TLI->getLibFunc(FloatFuncName, Func))
1942 return TLI->has(Func);
1943 return false;
1944}
Meador Inge7fb2f732012-10-13 16:45:32 +00001945
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001946Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1947 IRBuilder<> &Builder) {
1948 LibFunc::Func Func;
1949 Function *Callee = CI->getCalledFunction();
1950 StringRef FuncName = Callee->getName();
1951
1952 // Check for string/memory library functions.
1953 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1954 // Make sure we never change the calling convention.
1955 assert((ignoreCallingConv(Func) ||
1956 CI->getCallingConv() == llvm::CallingConv::C) &&
1957 "Optimizing string/memory libcall would change the calling convention");
1958 switch (Func) {
1959 case LibFunc::strcat:
1960 return optimizeStrCat(CI, Builder);
1961 case LibFunc::strncat:
1962 return optimizeStrNCat(CI, Builder);
1963 case LibFunc::strchr:
1964 return optimizeStrChr(CI, Builder);
1965 case LibFunc::strrchr:
1966 return optimizeStrRChr(CI, Builder);
1967 case LibFunc::strcmp:
1968 return optimizeStrCmp(CI, Builder);
1969 case LibFunc::strncmp:
1970 return optimizeStrNCmp(CI, Builder);
1971 case LibFunc::strcpy:
1972 return optimizeStrCpy(CI, Builder);
1973 case LibFunc::stpcpy:
1974 return optimizeStpCpy(CI, Builder);
1975 case LibFunc::strncpy:
1976 return optimizeStrNCpy(CI, Builder);
1977 case LibFunc::strlen:
1978 return optimizeStrLen(CI, Builder);
1979 case LibFunc::strpbrk:
1980 return optimizeStrPBrk(CI, Builder);
1981 case LibFunc::strtol:
1982 case LibFunc::strtod:
1983 case LibFunc::strtof:
1984 case LibFunc::strtoul:
1985 case LibFunc::strtoll:
1986 case LibFunc::strtold:
1987 case LibFunc::strtoull:
1988 return optimizeStrTo(CI, Builder);
1989 case LibFunc::strspn:
1990 return optimizeStrSpn(CI, Builder);
1991 case LibFunc::strcspn:
1992 return optimizeStrCSpn(CI, Builder);
1993 case LibFunc::strstr:
1994 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00001995 case LibFunc::memchr:
1996 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001997 case LibFunc::memcmp:
1998 return optimizeMemCmp(CI, Builder);
1999 case LibFunc::memcpy:
2000 return optimizeMemCpy(CI, Builder);
2001 case LibFunc::memmove:
2002 return optimizeMemMove(CI, Builder);
2003 case LibFunc::memset:
2004 return optimizeMemSet(CI, Builder);
2005 default:
2006 break;
2007 }
2008 }
2009 return nullptr;
2010}
2011
Chris Bienemanad070d02014-09-17 20:55:46 +00002012Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2013 if (CI->isNoBuiltin())
2014 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002015
Meador Inge20255ef2013-03-12 00:08:29 +00002016 LibFunc::Func Func;
2017 Function *Callee = CI->getCalledFunction();
2018 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002019 IRBuilder<> Builder(CI);
2020 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002021
Sanjay Patela92fa442014-10-22 15:29:23 +00002022 // Command-line parameter overrides function attribute.
2023 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2024 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002025 else if (canUseUnsafeFPMath(Callee))
2026 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002027
Sanjay Patel848309d2014-10-23 21:52:45 +00002028 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002029 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002030 if (!isCallingConvC)
2031 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002032 switch (II->getIntrinsicID()) {
2033 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002034 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002035 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002036 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002037 case Intrinsic::fabs:
2038 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002039 case Intrinsic::sqrt:
2040 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002041 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002042 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002043 }
2044 }
2045
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002046 // Also try to simplify calls to fortified library functions.
2047 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2048 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002049 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002050 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2051 // Use an IR Builder from SimplifiedCI if available instead of CI
2052 // to guarantee we reach all uses we might replace later on.
2053 IRBuilder<> TmpBuilder(SimplifiedCI);
2054 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002055 // If we were able to further simplify, remove the now redundant call.
2056 SimplifiedCI->replaceAllUsesWith(V);
2057 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002058 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002059 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002060 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002061 return SimplifiedFortifiedCI;
2062 }
2063
Meador Inge20255ef2013-03-12 00:08:29 +00002064 // Then check for known library functions.
2065 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002066 // We never change the calling convention.
2067 if (!ignoreCallingConv(Func) && !isCallingConvC)
2068 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002069 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2070 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002071 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002072 case LibFunc::cosf:
2073 case LibFunc::cos:
2074 case LibFunc::cosl:
2075 return optimizeCos(CI, Builder);
2076 case LibFunc::sinpif:
2077 case LibFunc::sinpi:
2078 case LibFunc::cospif:
2079 case LibFunc::cospi:
2080 return optimizeSinCosPi(CI, Builder);
2081 case LibFunc::powf:
2082 case LibFunc::pow:
2083 case LibFunc::powl:
2084 return optimizePow(CI, Builder);
2085 case LibFunc::exp2l:
2086 case LibFunc::exp2:
2087 case LibFunc::exp2f:
2088 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002089 case LibFunc::fabsf:
2090 case LibFunc::fabs:
2091 case LibFunc::fabsl:
2092 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002093 case LibFunc::sqrtf:
2094 case LibFunc::sqrt:
2095 case LibFunc::sqrtl:
2096 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002097 case LibFunc::ffs:
2098 case LibFunc::ffsl:
2099 case LibFunc::ffsll:
2100 return optimizeFFS(CI, Builder);
2101 case LibFunc::abs:
2102 case LibFunc::labs:
2103 case LibFunc::llabs:
2104 return optimizeAbs(CI, Builder);
2105 case LibFunc::isdigit:
2106 return optimizeIsDigit(CI, Builder);
2107 case LibFunc::isascii:
2108 return optimizeIsAscii(CI, Builder);
2109 case LibFunc::toascii:
2110 return optimizeToAscii(CI, Builder);
2111 case LibFunc::printf:
2112 return optimizePrintF(CI, Builder);
2113 case LibFunc::sprintf:
2114 return optimizeSPrintF(CI, Builder);
2115 case LibFunc::fprintf:
2116 return optimizeFPrintF(CI, Builder);
2117 case LibFunc::fwrite:
2118 return optimizeFWrite(CI, Builder);
2119 case LibFunc::fputs:
2120 return optimizeFPuts(CI, Builder);
2121 case LibFunc::puts:
2122 return optimizePuts(CI, Builder);
2123 case LibFunc::perror:
2124 return optimizeErrorReporting(CI, Builder);
2125 case LibFunc::vfprintf:
2126 case LibFunc::fiprintf:
2127 return optimizeErrorReporting(CI, Builder, 0);
2128 case LibFunc::fputc:
2129 return optimizeErrorReporting(CI, Builder, 1);
2130 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002131 case LibFunc::floor:
2132 case LibFunc::rint:
2133 case LibFunc::round:
2134 case LibFunc::nearbyint:
2135 case LibFunc::trunc:
2136 if (hasFloatVersion(FuncName))
2137 return optimizeUnaryDoubleFP(CI, Builder, false);
2138 return nullptr;
2139 case LibFunc::acos:
2140 case LibFunc::acosh:
2141 case LibFunc::asin:
2142 case LibFunc::asinh:
2143 case LibFunc::atan:
2144 case LibFunc::atanh:
2145 case LibFunc::cbrt:
2146 case LibFunc::cosh:
2147 case LibFunc::exp:
2148 case LibFunc::exp10:
2149 case LibFunc::expm1:
2150 case LibFunc::log:
2151 case LibFunc::log10:
2152 case LibFunc::log1p:
2153 case LibFunc::log2:
2154 case LibFunc::logb:
2155 case LibFunc::sin:
2156 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002157 case LibFunc::tan:
2158 case LibFunc::tanh:
2159 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2160 return optimizeUnaryDoubleFP(CI, Builder, true);
2161 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002162 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002163 if (hasFloatVersion(FuncName))
2164 return optimizeBinaryDoubleFP(CI, Builder);
2165 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002166 case LibFunc::fminf:
2167 case LibFunc::fmin:
2168 case LibFunc::fminl:
2169 case LibFunc::fmaxf:
2170 case LibFunc::fmax:
2171 case LibFunc::fmaxl:
2172 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002173 default:
2174 return nullptr;
2175 }
Meador Inge20255ef2013-03-12 00:08:29 +00002176 }
Craig Topperf40110f2014-04-25 05:29:35 +00002177 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002178}
2179
Chandler Carruth92803822015-01-21 02:11:59 +00002180LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002181 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002182 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002183 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002184 Replacer(Replacer) {}
2185
2186void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2187 // Indirect through the replacer used in this instance.
2188 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002189}
2190
Meador Ingedfb08a22013-06-20 19:48:07 +00002191// TODO:
2192// Additional cases that we need to add to this file:
2193//
2194// cbrt:
2195// * cbrt(expN(X)) -> expN(x/3)
2196// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002197// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002198//
2199// exp, expf, expl:
2200// * exp(log(x)) -> x
2201//
2202// log, logf, logl:
2203// * log(exp(x)) -> x
2204// * log(x**y) -> y*log(x)
2205// * log(exp(y)) -> y*log(e)
2206// * log(exp2(y)) -> y*log(2)
2207// * log(exp10(y)) -> y*log(10)
2208// * log(sqrt(x)) -> 0.5*log(x)
2209// * log(pow(x,y)) -> y*log(x)
2210//
2211// lround, lroundf, lroundl:
2212// * lround(cnst) -> cnst'
2213//
2214// pow, powf, powl:
2215// * pow(exp(x),y) -> exp(x*y)
2216// * pow(sqrt(x),y) -> pow(x,y*0.5)
2217// * pow(pow(x,y),z)-> pow(x,y*z)
2218//
2219// round, roundf, roundl:
2220// * round(cnst) -> cnst'
2221//
2222// signbit:
2223// * signbit(cnst) -> cnst'
2224// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2225//
2226// sqrt, sqrtf, sqrtl:
2227// * sqrt(expN(x)) -> expN(x*0.5)
2228// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2229// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2230//
Meador Ingedfb08a22013-06-20 19:48:07 +00002231// tan, tanf, tanl:
2232// * tan(atan(x)) -> x
2233//
2234// trunc, truncf, truncl:
2235// * trunc(cnst) -> cnst'
2236//
2237//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002238
2239//===----------------------------------------------------------------------===//
2240// Fortified Library Call Optimizations
2241//===----------------------------------------------------------------------===//
2242
2243bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2244 unsigned ObjSizeOp,
2245 unsigned SizeOp,
2246 bool isString) {
2247 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2248 return true;
2249 if (ConstantInt *ObjSizeCI =
2250 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2251 if (ObjSizeCI->isAllOnesValue())
2252 return true;
2253 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2254 if (OnlyLowerUnknownSize)
2255 return false;
2256 if (isString) {
2257 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2258 // If the length is 0 we don't know how long it is and so we can't
2259 // remove the check.
2260 if (Len == 0)
2261 return false;
2262 return ObjSizeCI->getZExtValue() >= Len;
2263 }
2264 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2265 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2266 }
2267 return false;
2268}
2269
2270Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2271 Function *Callee = CI->getCalledFunction();
2272
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002273 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002274 return nullptr;
2275
2276 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2277 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2278 CI->getArgOperand(2), 1);
2279 return CI->getArgOperand(0);
2280 }
2281 return nullptr;
2282}
2283
2284Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2285 Function *Callee = CI->getCalledFunction();
2286
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002287 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002288 return nullptr;
2289
2290 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2291 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2292 CI->getArgOperand(2), 1);
2293 return CI->getArgOperand(0);
2294 }
2295 return nullptr;
2296}
2297
2298Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2299 Function *Callee = CI->getCalledFunction();
2300
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002301 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002302 return nullptr;
2303
2304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2305 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2306 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2307 return CI->getArgOperand(0);
2308 }
2309 return nullptr;
2310}
2311
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002312Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2313 IRBuilder<> &B,
2314 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002315 Function *Callee = CI->getCalledFunction();
2316 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002317 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002318
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002319 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002320 return nullptr;
2321
2322 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2323 *ObjSize = CI->getArgOperand(2);
2324
2325 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002326 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002327 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002328 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002329 }
2330
2331 // If a) we don't have any length information, or b) we know this will
2332 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2333 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2334 // TODO: It might be nice to get a maximum length out of the possible
2335 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002336 if (isFortifiedCallFoldable(CI, 2, 1, true))
2337 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002338
David Blaikie65fab6d2015-04-03 21:32:06 +00002339 if (OnlyLowerUnknownSize)
2340 return nullptr;
2341
2342 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2343 uint64_t Len = GetStringLength(Src);
2344 if (Len == 0)
2345 return nullptr;
2346
2347 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2348 Value *LenV = ConstantInt::get(SizeTTy, Len);
2349 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2350 // If the function was an __stpcpy_chk, and we were able to fold it into
2351 // a __memcpy_chk, we still need to return the correct end pointer.
2352 if (Ret && Func == LibFunc::stpcpy_chk)
2353 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2354 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002355}
2356
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002357Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2358 IRBuilder<> &B,
2359 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002360 Function *Callee = CI->getCalledFunction();
2361 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002362
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002363 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002364 return nullptr;
2365 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002366 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2367 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002368 return Ret;
2369 }
2370 return nullptr;
2371}
2372
2373Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002374 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2375 // Some clang users checked for _chk libcall availability using:
2376 // __has_builtin(__builtin___memcpy_chk)
2377 // When compiling with -fno-builtin, this is always true.
2378 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2379 // end up with fortified libcalls, which isn't acceptable in a freestanding
2380 // environment which only provides their non-fortified counterparts.
2381 //
2382 // Until we change clang and/or teach external users to check for availability
2383 // differently, disregard the "nobuiltin" attribute and TLI::has.
2384 //
2385 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002386
2387 LibFunc::Func Func;
2388 Function *Callee = CI->getCalledFunction();
2389 StringRef FuncName = Callee->getName();
2390 IRBuilder<> Builder(CI);
2391 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2392
2393 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002394 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002395 return nullptr;
2396
2397 // We never change the calling convention.
2398 if (!ignoreCallingConv(Func) && !isCallingConvC)
2399 return nullptr;
2400
2401 switch (Func) {
2402 case LibFunc::memcpy_chk:
2403 return optimizeMemCpyChk(CI, Builder);
2404 case LibFunc::memmove_chk:
2405 return optimizeMemMoveChk(CI, Builder);
2406 case LibFunc::memset_chk:
2407 return optimizeMemSetChk(CI, Builder);
2408 case LibFunc::stpcpy_chk:
2409 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002410 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002411 case LibFunc::stpncpy_chk:
2412 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002413 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414 default:
2415 break;
2416 }
2417 return nullptr;
2418}
2419
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002420FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2421 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2422 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}