blob: f6cc431656b806fbfe18359fd63b4c1ce88f1174 [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"
35
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000040 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000042
Sanjay Patela92fa442014-10-22 15:29:23 +000043static cl::opt<bool>
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
45 cl::init(false),
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
48
49
Meador Ingedf796f82012-10-13 16:45:24 +000050//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000051// Helper Functions
52//===----------------------------------------------------------------------===//
53
Chris Bienemanad070d02014-09-17 20:55:46 +000054static bool ignoreCallingConv(LibFunc::Func Func) {
55 switch (Func) {
56 case LibFunc::abs:
57 case LibFunc::labs:
58 case LibFunc::llabs:
59 case LibFunc::strlen:
60 return true;
61 default:
62 return false;
63 }
Chris Bienemancf93cbb2014-09-17 21:06:59 +000064 llvm_unreachable("All cases should be covered in the switch.");
Chris Bienemanad070d02014-09-17 20:55:46 +000065}
66
Meador Inged589ac62012-10-31 03:33:06 +000067/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
68/// value is equal or not-equal to zero.
69static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000070 for (User *U : V->users()) {
71 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000072 if (IC->isEquality())
73 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
74 if (C->isNullValue())
75 continue;
76 // Unknown instruction.
77 return false;
78 }
79 return true;
80}
81
Meador Inge56edbc92012-11-11 03:51:48 +000082/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
83/// comparisons with With.
84static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000085 for (User *U : V->users()) {
86 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000087 if (IC->isEquality() && IC->getOperand(1) == With)
88 continue;
89 // Unknown instruction.
90 return false;
91 }
92 return true;
93}
94
Meador Inge08ca1152012-11-26 20:37:20 +000095static bool callHasFloatingPointArgument(const CallInst *CI) {
96 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
97 it != e; ++it) {
98 if ((*it)->getType()->isFloatingPointTy())
99 return true;
100 }
101 return false;
102}
103
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000104/// \brief Check whether the overloaded unary floating point function
105/// corresponing to \a Ty is available.
106static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
107 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
108 LibFunc::Func LongDoubleFn) {
109 switch (Ty->getTypeID()) {
110 case Type::FloatTyID:
111 return TLI->has(FloatFn);
112 case Type::DoubleTyID:
113 return TLI->has(DoubleFn);
114 default:
115 return TLI->has(LongDoubleFn);
116 }
117}
118
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000119/// \brief Returns whether \p F matches the signature expected for the
120/// string/memory copying library function \p Func.
121/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
122/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000123static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
124 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000125 FunctionType *FT = F->getFunctionType();
126 LLVMContext &Context = F->getContext();
127 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000128 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000129 unsigned NumParams = FT->getNumParams();
130
131 // All string libfuncs return the same type as the first parameter.
132 if (FT->getReturnType() != FT->getParamType(0))
133 return false;
134
135 switch (Func) {
136 default:
137 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
138 case LibFunc::stpncpy_chk:
139 case LibFunc::strncpy_chk:
140 --NumParams; // fallthrough
141 case LibFunc::stpncpy:
142 case LibFunc::strncpy: {
143 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
144 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
145 return false;
146 break;
147 }
148 case LibFunc::strcpy_chk:
149 case LibFunc::stpcpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpcpy:
152 case LibFunc::strcpy: {
153 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy)
155 return false;
156 break;
157 }
158 case LibFunc::memmove_chk:
159 case LibFunc::memcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::memmove:
162 case LibFunc::memcpy: {
163 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
164 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
165 return false;
166 break;
167 }
168 case LibFunc::memset_chk:
169 --NumParams; // fallthrough
170 case LibFunc::memset: {
171 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
172 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
173 return false;
174 break;
175 }
176 }
177 // If this is a fortified libcall, the last parameter is a size_t.
178 if (NumParams == FT->getNumParams() - 1)
179 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
180 return true;
181}
182
Meador Inged589ac62012-10-31 03:33:06 +0000183//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000184// String and Memory Library Call Optimizations
185//===----------------------------------------------------------------------===//
186
Chris Bienemanad070d02014-09-17 20:55:46 +0000187Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
188 Function *Callee = CI->getCalledFunction();
189 // Verify the "strcat" function prototype.
190 FunctionType *FT = Callee->getFunctionType();
191 if (FT->getNumParams() != 2||
192 FT->getReturnType() != B.getInt8PtrTy() ||
193 FT->getParamType(0) != FT->getReturnType() ||
194 FT->getParamType(1) != FT->getReturnType())
195 return nullptr;
196
197 // Extract some information from the instruction
198 Value *Dst = CI->getArgOperand(0);
199 Value *Src = CI->getArgOperand(1);
200
201 // See if we can get the length of the input string.
202 uint64_t Len = GetStringLength(Src);
203 if (Len == 0)
204 return nullptr;
205 --Len; // Unbias length.
206
207 // Handle the simple, do-nothing case: strcat(x, "") -> x
208 if (Len == 0)
209 return Dst;
210
Chris Bienemanad070d02014-09-17 20:55:46 +0000211 return emitStrLenMemCpy(Src, Dst, Len, B);
212}
213
214Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
215 IRBuilder<> &B) {
216 // We need to find the end of the destination string. That's where the
217 // memory is to be moved to. We just generate a call to strlen.
218 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
219 if (!DstLen)
220 return nullptr;
221
222 // Now that we have the destination's length, we must index into the
223 // destination's pointer to get the actual memcpy destination (end of
224 // the string .. we're concatenating).
225 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
226
227 // We have enough information to now generate the memcpy call to do the
228 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229 B.CreateMemCpy(CpyDst, Src,
230 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
231 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000232 return Dst;
233}
234
235Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
236 Function *Callee = CI->getCalledFunction();
237 // Verify the "strncat" function prototype.
238 FunctionType *FT = Callee->getFunctionType();
239 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
240 FT->getParamType(0) != FT->getReturnType() ||
241 FT->getParamType(1) != FT->getReturnType() ||
242 !FT->getParamType(2)->isIntegerTy())
243 return nullptr;
244
245 // Extract some information from the instruction
246 Value *Dst = CI->getArgOperand(0);
247 Value *Src = CI->getArgOperand(1);
248 uint64_t Len;
249
250 // We don't do anything if length is not constant
251 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
252 Len = LengthArg->getZExtValue();
253 else
254 return nullptr;
255
256 // See if we can get the length of the input string.
257 uint64_t SrcLen = GetStringLength(Src);
258 if (SrcLen == 0)
259 return nullptr;
260 --SrcLen; // Unbias length.
261
262 // Handle the simple, do-nothing cases:
263 // strncat(x, "", c) -> x
264 // strncat(x, c, 0) -> x
265 if (SrcLen == 0 || Len == 0)
266 return Dst;
267
Chris Bienemanad070d02014-09-17 20:55:46 +0000268 // We don't optimize this case
269 if (Len < SrcLen)
270 return nullptr;
271
272 // strncat(x, s, c) -> strcat(x, s)
273 // s is constant so the strcat can be optimized further
274 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
275}
276
277Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
278 Function *Callee = CI->getCalledFunction();
279 // Verify the "strchr" function prototype.
280 FunctionType *FT = Callee->getFunctionType();
281 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
282 FT->getParamType(0) != FT->getReturnType() ||
283 !FT->getParamType(1)->isIntegerTy(32))
284 return nullptr;
285
286 Value *SrcStr = CI->getArgOperand(0);
287
288 // If the second operand is non-constant, see if we can compute the length
289 // of the input string and turn this into memchr.
290 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
291 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000292 uint64_t Len = GetStringLength(SrcStr);
293 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
294 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000295
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
297 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
298 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000299 }
300
Chris Bienemanad070d02014-09-17 20:55:46 +0000301 // Otherwise, the character is a constant, see if the first argument is
302 // a string literal. If so, we can constant fold.
303 StringRef Str;
304 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000305 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Chris Bienemanad070d02014-09-17 20:55:46 +0000306 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
307 return nullptr;
308 }
309
310 // Compute the offset, make sure to handle the case when we're searching for
311 // zero (a weird way to spell strlen).
312 size_t I = (0xFF & CharC->getSExtValue()) == 0
313 ? Str.size()
314 : Str.find(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
316 return Constant::getNullValue(CI->getType());
317
318 // strchr(s+n,c) -> gep(s+n+i,c)
319 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
320}
321
322Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
323 Function *Callee = CI->getCalledFunction();
324 // Verify the "strrchr" function prototype.
325 FunctionType *FT = Callee->getFunctionType();
326 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
327 FT->getParamType(0) != FT->getReturnType() ||
328 !FT->getParamType(1)->isIntegerTy(32))
329 return nullptr;
330
331 Value *SrcStr = CI->getArgOperand(0);
332 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
333
334 // Cannot fold anything if we're not looking for a constant.
335 if (!CharC)
336 return nullptr;
337
338 StringRef Str;
339 if (!getConstantStringInfo(SrcStr, Str)) {
340 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000341 if (CharC->isZero())
342 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000343 return nullptr;
344 }
345
346 // Compute the offset.
347 size_t I = (0xFF & CharC->getSExtValue()) == 0
348 ? Str.size()
349 : Str.rfind(CharC->getSExtValue());
350 if (I == StringRef::npos) // Didn't find the char. Return null.
351 return Constant::getNullValue(CI->getType());
352
353 // strrchr(s+n,c) -> gep(s+n+i,c)
354 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
355}
356
357Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
358 Function *Callee = CI->getCalledFunction();
359 // Verify the "strcmp" function prototype.
360 FunctionType *FT = Callee->getFunctionType();
361 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
362 FT->getParamType(0) != FT->getParamType(1) ||
363 FT->getParamType(0) != B.getInt8PtrTy())
364 return nullptr;
365
366 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
367 if (Str1P == Str2P) // strcmp(x,x) -> 0
368 return ConstantInt::get(CI->getType(), 0);
369
370 StringRef Str1, Str2;
371 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
372 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
373
374 // strcmp(x, y) -> cnst (if both x and y are constant strings)
375 if (HasStr1 && HasStr2)
376 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
377
378 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
379 return B.CreateNeg(
380 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
381
382 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
383 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
384
385 // strcmp(P, "x") -> memcmp(P, "x", 2)
386 uint64_t Len1 = GetStringLength(Str1P);
387 uint64_t Len2 = GetStringLength(Str2P);
388 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000389 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000390 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000391 std::min(Len1, Len2)),
392 B, DL, TLI);
393 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000394
Chris Bienemanad070d02014-09-17 20:55:46 +0000395 return nullptr;
396}
397
398Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
399 Function *Callee = CI->getCalledFunction();
400 // Verify the "strncmp" function prototype.
401 FunctionType *FT = Callee->getFunctionType();
402 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
403 FT->getParamType(0) != FT->getParamType(1) ||
404 FT->getParamType(0) != B.getInt8PtrTy() ||
405 !FT->getParamType(2)->isIntegerTy())
406 return nullptr;
407
408 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
409 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
410 return ConstantInt::get(CI->getType(), 0);
411
412 // Get the length argument if it is constant.
413 uint64_t Length;
414 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
415 Length = LengthArg->getZExtValue();
416 else
417 return nullptr;
418
419 if (Length == 0) // strncmp(x,y,0) -> 0
420 return ConstantInt::get(CI->getType(), 0);
421
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000423 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
424
425 StringRef Str1, Str2;
426 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
427 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
428
429 // strncmp(x, y) -> cnst (if both x and y are constant strings)
430 if (HasStr1 && HasStr2) {
431 StringRef SubStr1 = Str1.substr(0, Length);
432 StringRef SubStr2 = Str2.substr(0, Length);
433 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
434 }
435
436 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
437 return B.CreateNeg(
438 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
439
440 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
441 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
442
443 return nullptr;
444}
445
446Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
447 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000448
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000449 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000450 return nullptr;
451
452 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
453 if (Dst == Src) // strcpy(x,x) -> x
454 return Src;
455
Chris Bienemanad070d02014-09-17 20:55:46 +0000456 // See if we can get the length of the input string.
457 uint64_t Len = GetStringLength(Src);
458 if (Len == 0)
459 return nullptr;
460
461 // We have enough information to now generate the memcpy call to do the
462 // copy for us. Make a memcpy to copy the nul byte with align = 1.
463 B.CreateMemCpy(Dst, Src,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000464 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000465 return Dst;
466}
467
468Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
469 Function *Callee = CI->getCalledFunction();
470 // Verify the "stpcpy" function prototype.
471 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000472
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000473 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000474 return nullptr;
475
476 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
477 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
478 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
479 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
480 }
481
482 // See if we can get the length of the input string.
483 uint64_t Len = GetStringLength(Src);
484 if (Len == 0)
485 return nullptr;
486
487 Type *PT = FT->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000488 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 Value *DstEnd =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490 B.CreateGEP(Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000491
492 // We have enough information to now generate the memcpy call to do the
493 // copy for us. Make a memcpy to copy the nul byte with align = 1.
494 B.CreateMemCpy(Dst, Src, LenV, 1);
495 return DstEnd;
496}
497
498Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
499 Function *Callee = CI->getCalledFunction();
500 FunctionType *FT = Callee->getFunctionType();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000501
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000502 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000503 return nullptr;
504
505 Value *Dst = CI->getArgOperand(0);
506 Value *Src = CI->getArgOperand(1);
507 Value *LenOp = CI->getArgOperand(2);
508
509 // See if we can get the length of the input string.
510 uint64_t SrcLen = GetStringLength(Src);
511 if (SrcLen == 0)
512 return nullptr;
513 --SrcLen;
514
515 if (SrcLen == 0) {
516 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
517 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000518 return Dst;
519 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000520
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 uint64_t Len;
522 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
523 Len = LengthArg->getZExtValue();
524 else
525 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000526
Chris Bienemanad070d02014-09-17 20:55:46 +0000527 if (Len == 0)
528 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000529
Chris Bienemanad070d02014-09-17 20:55:46 +0000530 // Let strncpy handle the zero padding
531 if (Len > SrcLen + 1)
532 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000533
Chris Bienemanad070d02014-09-17 20:55:46 +0000534 Type *PT = FT->getParamType(0);
535 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000536 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000537
Chris Bienemanad070d02014-09-17 20:55:46 +0000538 return Dst;
539}
Meador Inge7fb2f732012-10-13 16:45:32 +0000540
Chris Bienemanad070d02014-09-17 20:55:46 +0000541Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
542 Function *Callee = CI->getCalledFunction();
543 FunctionType *FT = Callee->getFunctionType();
544 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
545 !FT->getReturnType()->isIntegerTy())
546 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000547
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 Value *Src = CI->getArgOperand(0);
549
550 // Constant folding: strlen("xyz") -> 3
551 if (uint64_t Len = GetStringLength(Src))
552 return ConstantInt::get(CI->getType(), Len - 1);
553
554 // strlen(x?"foo":"bars") --> x ? 3 : 4
555 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
556 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
557 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
558 if (LenTrue && LenFalse) {
559 Function *Caller = CI->getParent()->getParent();
560 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
561 SI->getDebugLoc(),
562 "folded strlen(select) to select of constants");
563 return B.CreateSelect(SI->getCondition(),
564 ConstantInt::get(CI->getType(), LenTrue - 1),
565 ConstantInt::get(CI->getType(), LenFalse - 1));
566 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000567 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000568
Chris Bienemanad070d02014-09-17 20:55:46 +0000569 // strlen(x) != 0 --> *x != 0
570 // strlen(x) == 0 --> *x == 0
571 if (isOnlyUsedInZeroEqualityComparison(CI))
572 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000573
Chris Bienemanad070d02014-09-17 20:55:46 +0000574 return nullptr;
575}
Meador Inge17418502012-10-13 16:45:37 +0000576
Chris Bienemanad070d02014-09-17 20:55:46 +0000577Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
578 Function *Callee = CI->getCalledFunction();
579 FunctionType *FT = Callee->getFunctionType();
580 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
581 FT->getParamType(1) != FT->getParamType(0) ||
582 FT->getReturnType() != FT->getParamType(0))
583 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000584
Chris Bienemanad070d02014-09-17 20:55:46 +0000585 StringRef S1, S2;
586 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
587 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000588
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000589 // strpbrk(s, "") -> nullptr
590 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000591 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
592 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000593
Chris Bienemanad070d02014-09-17 20:55:46 +0000594 // Constant folding.
595 if (HasS1 && HasS2) {
596 size_t I = S1.find_first_of(S2);
597 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000598 return Constant::getNullValue(CI->getType());
599
Chris Bienemanad070d02014-09-17 20:55:46 +0000600 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000601 }
Meador Inge17418502012-10-13 16:45:37 +0000602
Chris Bienemanad070d02014-09-17 20:55:46 +0000603 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 if (HasS2 && S2.size() == 1)
605 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000606
607 return nullptr;
608}
609
610Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
611 Function *Callee = CI->getCalledFunction();
612 FunctionType *FT = Callee->getFunctionType();
613 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
614 !FT->getParamType(0)->isPointerTy() ||
615 !FT->getParamType(1)->isPointerTy())
616 return nullptr;
617
618 Value *EndPtr = CI->getArgOperand(1);
619 if (isa<ConstantPointerNull>(EndPtr)) {
620 // With a null EndPtr, this function won't capture the main argument.
621 // It would be readonly too, except that it still may write to errno.
622 CI->addAttribute(1, Attribute::NoCapture);
623 }
624
625 return nullptr;
626}
627
628Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
629 Function *Callee = CI->getCalledFunction();
630 FunctionType *FT = Callee->getFunctionType();
631 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
632 FT->getParamType(1) != FT->getParamType(0) ||
633 !FT->getReturnType()->isIntegerTy())
634 return nullptr;
635
636 StringRef S1, S2;
637 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
638 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
639
640 // strspn(s, "") -> 0
641 // strspn("", s) -> 0
642 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
643 return Constant::getNullValue(CI->getType());
644
645 // Constant folding.
646 if (HasS1 && HasS2) {
647 size_t Pos = S1.find_first_not_of(S2);
648 if (Pos == StringRef::npos)
649 Pos = S1.size();
650 return ConstantInt::get(CI->getType(), Pos);
651 }
652
653 return nullptr;
654}
655
656Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
657 Function *Callee = CI->getCalledFunction();
658 FunctionType *FT = Callee->getFunctionType();
659 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
660 FT->getParamType(1) != FT->getParamType(0) ||
661 !FT->getReturnType()->isIntegerTy())
662 return nullptr;
663
664 StringRef S1, S2;
665 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
666 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
667
668 // strcspn("", s) -> 0
669 if (HasS1 && S1.empty())
670 return Constant::getNullValue(CI->getType());
671
672 // Constant folding.
673 if (HasS1 && HasS2) {
674 size_t Pos = S1.find_first_of(S2);
675 if (Pos == StringRef::npos)
676 Pos = S1.size();
677 return ConstantInt::get(CI->getType(), Pos);
678 }
679
680 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000681 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000682 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
683
684 return nullptr;
685}
686
687Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
688 Function *Callee = CI->getCalledFunction();
689 FunctionType *FT = Callee->getFunctionType();
690 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
691 !FT->getParamType(1)->isPointerTy() ||
692 !FT->getReturnType()->isPointerTy())
693 return nullptr;
694
695 // fold strstr(x, x) -> x.
696 if (CI->getArgOperand(0) == CI->getArgOperand(1))
697 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
698
699 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000700 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000701 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
702 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000703 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000704 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
705 StrLen, B, DL, TLI);
706 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000707 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000708 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
709 ICmpInst *Old = cast<ICmpInst>(*UI++);
710 Value *Cmp =
711 B.CreateICmp(Old->getPredicate(), StrNCmp,
712 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
713 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000714 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000715 return CI;
716 }
Meador Inge17418502012-10-13 16:45:37 +0000717
Chris Bienemanad070d02014-09-17 20:55:46 +0000718 // See if either input string is a constant string.
719 StringRef SearchStr, ToFindStr;
720 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
721 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
722
723 // fold strstr(x, "") -> x.
724 if (HasStr2 && ToFindStr.empty())
725 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
726
727 // If both strings are known, constant fold it.
728 if (HasStr1 && HasStr2) {
729 size_t Offset = SearchStr.find(ToFindStr);
730
731 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000732 return Constant::getNullValue(CI->getType());
733
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
735 Value *Result = CastToCStr(CI->getArgOperand(0), B);
736 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
737 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000738 }
Meador Inge17418502012-10-13 16:45:37 +0000739
Chris Bienemanad070d02014-09-17 20:55:46 +0000740 // fold strstr(x, "y") -> strchr(x, 'y').
741 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000742 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
744 }
745 return nullptr;
746}
Meador Inge40b6fac2012-10-15 03:47:37 +0000747
Benjamin Kramer691363e2015-03-21 15:36:21 +0000748Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
749 Function *Callee = CI->getCalledFunction();
750 FunctionType *FT = Callee->getFunctionType();
751 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
752 !FT->getParamType(1)->isIntegerTy(32) ||
753 !FT->getParamType(2)->isIntegerTy() ||
754 !FT->getReturnType()->isPointerTy())
755 return nullptr;
756
757 Value *SrcStr = CI->getArgOperand(0);
758 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
759 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
760
761 // memchr(x, y, 0) -> null
762 if (LenC && LenC->isNullValue())
763 return Constant::getNullValue(CI->getType());
764
Benjamin Kramer7857d722015-03-21 21:09:33 +0000765 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000766 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000767 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000768 return nullptr;
769
770 // Truncate the string to LenC. If Str is smaller than LenC we will still only
771 // scan the string, as reading past the end of it is undefined and we can just
772 // return null if we don't find the char.
773 Str = Str.substr(0, LenC->getZExtValue());
774
Benjamin Kramer7857d722015-03-21 21:09:33 +0000775 // If the char is variable but the input str and length are not we can turn
776 // this memchr call into a simple bit field test. Of course this only works
777 // when the return value is only checked against null.
778 //
779 // It would be really nice to reuse switch lowering here but we can't change
780 // the CFG at this point.
781 //
782 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
783 // after bounds check.
784 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
785 unsigned char Max = *std::max_element(Str.begin(), Str.end());
786
787 // Make sure the bit field we're about to create fits in a register on the
788 // target.
789 // FIXME: On a 64 bit architecture this prevents us from using the
790 // interesting range of alpha ascii chars. We could do better by emitting
791 // two bitfields or shifting the range by 64 if no lower chars are used.
792 if (!DL.fitsInLegalInteger(Max + 1))
793 return nullptr;
794
795 // For the bit field use a power-of-2 type with at least 8 bits to avoid
796 // creating unnecessary illegal types.
797 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
798
799 // Now build the bit field.
800 APInt Bitfield(Width, 0);
801 for (char C : Str)
802 Bitfield.setBit((unsigned char)C);
803 Value *BitfieldC = B.getInt(Bitfield);
804
805 // First check that the bit field access is within bounds.
806 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
807 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
808 "memchr.bounds");
809
810 // Create code that checks if the given bit is set in the field.
811 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
812 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
813
814 // Finally merge both checks and cast to pointer type. The inttoptr
815 // implicitly zexts the i1 to intptr type.
816 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
817 }
818
819 // Check if all arguments are constants. If so, we can constant fold.
820 if (!CharC)
821 return nullptr;
822
Benjamin Kramer691363e2015-03-21 15:36:21 +0000823 // Compute the offset.
824 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
825 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
826 return Constant::getNullValue(CI->getType());
827
828 // memchr(s+n,c,l) -> gep(s+n+i,c)
829 return B.CreateGEP(SrcStr, B.getInt64(I), "memchr");
830}
831
Chris Bienemanad070d02014-09-17 20:55:46 +0000832Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
833 Function *Callee = CI->getCalledFunction();
834 FunctionType *FT = Callee->getFunctionType();
835 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
836 !FT->getParamType(1)->isPointerTy() ||
837 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000838 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000839
Chris Bienemanad070d02014-09-17 20:55:46 +0000840 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000841
Chris Bienemanad070d02014-09-17 20:55:46 +0000842 if (LHS == RHS) // memcmp(s,s,x) -> 0
843 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000844
Chris Bienemanad070d02014-09-17 20:55:46 +0000845 // Make sure we have a constant length.
846 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
847 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000848 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000849 uint64_t Len = LenC->getZExtValue();
850
851 if (Len == 0) // memcmp(s1,s2,0) -> 0
852 return Constant::getNullValue(CI->getType());
853
854 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
855 if (Len == 1) {
856 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
857 CI->getType(), "lhsv");
858 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
859 CI->getType(), "rhsv");
860 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000861 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000862
Chris Bienemanad070d02014-09-17 20:55:46 +0000863 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
864 StringRef LHSStr, RHSStr;
865 if (getConstantStringInfo(LHS, LHSStr) &&
866 getConstantStringInfo(RHS, RHSStr)) {
867 // Make sure we're not reading out-of-bounds memory.
868 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000869 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000870 // Fold the memcmp and normalize the result. This way we get consistent
871 // results across multiple platforms.
872 uint64_t Ret = 0;
873 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
874 if (Cmp < 0)
875 Ret = -1;
876 else if (Cmp > 0)
877 Ret = 1;
878 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000879 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000880
Chris Bienemanad070d02014-09-17 20:55:46 +0000881 return nullptr;
882}
Meador Inge9a6a1902012-10-31 00:20:56 +0000883
Chris Bienemanad070d02014-09-17 20:55:46 +0000884Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
885 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000886
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000887 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000888 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000889
Chris Bienemanad070d02014-09-17 20:55:46 +0000890 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
891 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
892 CI->getArgOperand(2), 1);
893 return CI->getArgOperand(0);
894}
Meador Inge05a625a2012-10-31 14:58:26 +0000895
Chris Bienemanad070d02014-09-17 20:55:46 +0000896Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
897 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000898
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000900 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000901
Chris Bienemanad070d02014-09-17 20:55:46 +0000902 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
903 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
904 CI->getArgOperand(2), 1);
905 return CI->getArgOperand(0);
906}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000907
Chris Bienemanad070d02014-09-17 20:55:46 +0000908Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
909 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000910
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000911 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000912 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000913
Chris Bienemanad070d02014-09-17 20:55:46 +0000914 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
915 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
916 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
917 return CI->getArgOperand(0);
918}
Meador Inged4825782012-11-11 06:49:03 +0000919
Meador Inge193e0352012-11-13 04:16:17 +0000920//===----------------------------------------------------------------------===//
921// Math Library Optimizations
922//===----------------------------------------------------------------------===//
923
Matthias Braund34e4d22014-12-03 21:46:33 +0000924/// Return a variant of Val with float type.
925/// Currently this works in two cases: If Val is an FPExtension of a float
926/// value to something bigger, simply return the operand.
927/// If Val is a ConstantFP but can be converted to a float ConstantFP without
928/// loss of precision do so.
929static Value *valueHasFloatPrecision(Value *Val) {
930 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
931 Value *Op = Cast->getOperand(0);
932 if (Op->getType()->isFloatTy())
933 return Op;
934 }
935 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
936 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000937 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000938 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000939 &losesInfo);
940 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000941 return ConstantFP::get(Const->getContext(), F);
942 }
943 return nullptr;
944}
945
Meador Inge193e0352012-11-13 04:16:17 +0000946//===----------------------------------------------------------------------===//
947// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
948
Chris Bienemanad070d02014-09-17 20:55:46 +0000949Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
950 bool CheckRetType) {
951 Function *Callee = CI->getCalledFunction();
952 FunctionType *FT = Callee->getFunctionType();
953 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
954 !FT->getParamType(0)->isDoubleTy())
955 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000956
Chris Bienemanad070d02014-09-17 20:55:46 +0000957 if (CheckRetType) {
958 // Check if all the uses for function like 'sin' are converted to float.
959 for (User *U : CI->users()) {
960 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
961 if (!Cast || !Cast->getType()->isFloatTy())
962 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000963 }
Meador Inge193e0352012-11-13 04:16:17 +0000964 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000965
966 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000967 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
968 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000969 return nullptr;
970
971 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000972 if (Callee->isIntrinsic()) {
973 Module *M = CI->getParent()->getParent()->getParent();
974 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
975 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
976 V = B.CreateCall(F, V);
977 } else {
978 // The call is a library call rather than an intrinsic.
979 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
980 }
981
Chris Bienemanad070d02014-09-17 20:55:46 +0000982 return B.CreateFPExt(V, B.getDoubleTy());
983}
Meador Inge193e0352012-11-13 04:16:17 +0000984
Yi Jiang6ab044e2013-12-16 22:42:40 +0000985// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +0000986Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
987 Function *Callee = CI->getCalledFunction();
988 FunctionType *FT = Callee->getFunctionType();
989 // Just make sure this has 2 arguments of the same FP type, which match the
990 // result type.
991 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
992 FT->getParamType(0) != FT->getParamType(1) ||
993 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000994 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000995
Chris Bienemanad070d02014-09-17 20:55:46 +0000996 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000997 // or fmin(1.0, (double)floatval), then we convert it to fminf.
998 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
999 if (V1 == nullptr)
1000 return nullptr;
1001 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1002 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001003 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001004
1005 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001006 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001007 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001008 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1009 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001010 return B.CreateFPExt(V, B.getDoubleTy());
1011}
1012
1013Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1014 Function *Callee = CI->getCalledFunction();
1015 Value *Ret = nullptr;
1016 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1017 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001018 }
1019
Chris Bienemanad070d02014-09-17 20:55:46 +00001020 FunctionType *FT = Callee->getFunctionType();
1021 // Just make sure this has 1 argument of FP type, which matches the
1022 // result type.
1023 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1024 !FT->getParamType(0)->isFloatingPointTy())
1025 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001026
Chris Bienemanad070d02014-09-17 20:55:46 +00001027 // cos(-x) -> cos(x)
1028 Value *Op1 = CI->getArgOperand(0);
1029 if (BinaryOperator::isFNeg(Op1)) {
1030 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1031 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1032 }
1033 return Ret;
1034}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001035
Chris Bienemanad070d02014-09-17 20:55:46 +00001036Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1037 Function *Callee = CI->getCalledFunction();
1038
1039 Value *Ret = nullptr;
1040 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1041 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001042 }
1043
Chris Bienemanad070d02014-09-17 20:55:46 +00001044 FunctionType *FT = Callee->getFunctionType();
1045 // Just make sure this has 2 arguments of the same FP type, which match the
1046 // result type.
1047 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1048 FT->getParamType(0) != FT->getParamType(1) ||
1049 !FT->getParamType(0)->isFloatingPointTy())
1050 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001051
Chris Bienemanad070d02014-09-17 20:55:46 +00001052 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1053 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1054 // pow(1.0, x) -> 1.0
1055 if (Op1C->isExactlyValue(1.0))
1056 return Op1C;
1057 // pow(2.0, x) -> exp2(x)
1058 if (Op1C->isExactlyValue(2.0) &&
1059 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1060 LibFunc::exp2l))
1061 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1062 // pow(10.0, x) -> exp10(x)
1063 if (Op1C->isExactlyValue(10.0) &&
1064 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1065 LibFunc::exp10l))
1066 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1067 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001068 }
1069
Chris Bienemanad070d02014-09-17 20:55:46 +00001070 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1071 if (!Op2C)
1072 return Ret;
1073
1074 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1075 return ConstantFP::get(CI->getType(), 1.0);
1076
1077 if (Op2C->isExactlyValue(0.5) &&
1078 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1079 LibFunc::sqrtl) &&
1080 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1081 LibFunc::fabsl)) {
1082 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1083 // This is faster than calling pow, and still handles negative zero
1084 // and negative infinity correctly.
1085 // TODO: In fast-math mode, this could be just sqrt(x).
1086 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1087 Value *Inf = ConstantFP::getInfinity(CI->getType());
1088 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1089 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1090 Value *FAbs =
1091 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1092 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1093 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1094 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001095 }
1096
Chris Bienemanad070d02014-09-17 20:55:46 +00001097 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1098 return Op1;
1099 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1100 return B.CreateFMul(Op1, Op1, "pow2");
1101 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1102 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1103 return nullptr;
1104}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001105
Chris Bienemanad070d02014-09-17 20:55:46 +00001106Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1107 Function *Callee = CI->getCalledFunction();
1108 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001109
Chris Bienemanad070d02014-09-17 20:55:46 +00001110 Value *Ret = nullptr;
1111 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1112 TLI->has(LibFunc::exp2f)) {
1113 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001114 }
1115
Chris Bienemanad070d02014-09-17 20:55:46 +00001116 FunctionType *FT = Callee->getFunctionType();
1117 // Just make sure this has 1 argument of FP type, which matches the
1118 // result type.
1119 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1120 !FT->getParamType(0)->isFloatingPointTy())
1121 return Ret;
1122
1123 Value *Op = CI->getArgOperand(0);
1124 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1125 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1126 LibFunc::Func LdExp = LibFunc::ldexpl;
1127 if (Op->getType()->isFloatTy())
1128 LdExp = LibFunc::ldexpf;
1129 else if (Op->getType()->isDoubleTy())
1130 LdExp = LibFunc::ldexp;
1131
1132 if (TLI->has(LdExp)) {
1133 Value *LdExpArg = nullptr;
1134 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1135 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1136 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1137 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1138 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1139 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1140 }
1141
1142 if (LdExpArg) {
1143 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1144 if (!Op->getType()->isFloatTy())
1145 One = ConstantExpr::getFPExtend(One, Op->getType());
1146
1147 Module *M = Caller->getParent();
1148 Value *Callee =
1149 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001150 Op->getType(), B.getInt32Ty(), nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001151 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1152 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1153 CI->setCallingConv(F->getCallingConv());
1154
1155 return CI;
1156 }
1157 }
1158 return Ret;
1159}
1160
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001161Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1162 Function *Callee = CI->getCalledFunction();
1163
1164 Value *Ret = nullptr;
1165 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1166 Ret = optimizeUnaryDoubleFP(CI, B, false);
1167 }
1168
1169 FunctionType *FT = Callee->getFunctionType();
1170 // Make sure this has 1 argument of FP type which matches the result type.
1171 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1172 !FT->getParamType(0)->isFloatingPointTy())
1173 return Ret;
1174
1175 Value *Op = CI->getArgOperand(0);
1176 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1177 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1178 if (I->getOpcode() == Instruction::FMul)
1179 if (I->getOperand(0) == I->getOperand(1))
1180 return Op;
1181 }
1182 return Ret;
1183}
1184
Sanjay Patelc699a612014-10-16 18:48:17 +00001185Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1186 Function *Callee = CI->getCalledFunction();
1187
1188 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001189 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1190 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001191 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patelc699a612014-10-16 18:48:17 +00001192
1193 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1194 // fast-math flag decorations that are applied to FP instructions. For now,
1195 // we have to rely on the function-level unsafe-fp-math attribute to do this
1196 // optimization because there's no other way to express that the sqrt can be
1197 // reassociated.
1198 Function *F = CI->getParent()->getParent();
1199 if (F->hasFnAttribute("unsafe-fp-math")) {
1200 // Check for unsafe-fp-math = true.
1201 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1202 if (Attr.getValueAsString() != "true")
1203 return Ret;
1204 }
1205 Value *Op = CI->getArgOperand(0);
1206 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1207 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1208 // We're looking for a repeated factor in a multiplication tree,
1209 // so we can do this fold: sqrt(x * x) -> fabs(x);
1210 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1211 Value *Op0 = I->getOperand(0);
1212 Value *Op1 = I->getOperand(1);
1213 Value *RepeatOp = nullptr;
1214 Value *OtherOp = nullptr;
1215 if (Op0 == Op1) {
1216 // Simple match: the operands of the multiply are identical.
1217 RepeatOp = Op0;
1218 } else {
1219 // Look for a more complicated pattern: one of the operands is itself
1220 // a multiply, so search for a common factor in that multiply.
1221 // Note: We don't bother looking any deeper than this first level or for
1222 // variations of this pattern because instcombine's visitFMUL and/or the
1223 // reassociation pass should give us this form.
1224 Value *OtherMul0, *OtherMul1;
1225 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1226 // Pattern: sqrt((x * y) * z)
1227 if (OtherMul0 == OtherMul1) {
1228 // Matched: sqrt((x * x) * z)
1229 RepeatOp = OtherMul0;
1230 OtherOp = Op1;
1231 }
1232 }
1233 }
1234 if (RepeatOp) {
1235 // Fast math flags for any created instructions should match the sqrt
1236 // and multiply.
1237 // FIXME: We're not checking the sqrt because it doesn't have
1238 // fast-math-flags (see earlier comment).
1239 IRBuilder<true, ConstantFolder,
1240 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1241 B.SetFastMathFlags(I->getFastMathFlags());
1242 // If we found a repeated factor, hoist it out of the square root and
1243 // replace it with the fabs of that factor.
1244 Module *M = Callee->getParent();
1245 Type *ArgType = Op->getType();
1246 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1247 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1248 if (OtherOp) {
1249 // If we found a non-repeated factor, we still need to get its square
1250 // root. We then multiply that by the value that was simplified out
1251 // of the square root calculation.
1252 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1253 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1254 return B.CreateFMul(FabsCall, SqrtCall);
1255 }
1256 return FabsCall;
1257 }
1258 }
1259 }
1260 return Ret;
1261}
1262
Chris Bienemanad070d02014-09-17 20:55:46 +00001263static bool isTrigLibCall(CallInst *CI);
1264static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1265 bool UseFloat, Value *&Sin, Value *&Cos,
1266 Value *&SinCos);
1267
1268Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1269
1270 // Make sure the prototype is as expected, otherwise the rest of the
1271 // function is probably invalid and likely to abort.
1272 if (!isTrigLibCall(CI))
1273 return nullptr;
1274
1275 Value *Arg = CI->getArgOperand(0);
1276 SmallVector<CallInst *, 1> SinCalls;
1277 SmallVector<CallInst *, 1> CosCalls;
1278 SmallVector<CallInst *, 1> SinCosCalls;
1279
1280 bool IsFloat = Arg->getType()->isFloatTy();
1281
1282 // Look for all compatible sinpi, cospi and sincospi calls with the same
1283 // argument. If there are enough (in some sense) we can make the
1284 // substitution.
1285 for (User *U : Arg->users())
1286 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1287 SinCosCalls);
1288
1289 // It's only worthwhile if both sinpi and cospi are actually used.
1290 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1291 return nullptr;
1292
1293 Value *Sin, *Cos, *SinCos;
1294 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1295
1296 replaceTrigInsts(SinCalls, Sin);
1297 replaceTrigInsts(CosCalls, Cos);
1298 replaceTrigInsts(SinCosCalls, SinCos);
1299
1300 return nullptr;
1301}
1302
1303static bool isTrigLibCall(CallInst *CI) {
1304 Function *Callee = CI->getCalledFunction();
1305 FunctionType *FT = Callee->getFunctionType();
1306
1307 // We can only hope to do anything useful if we can ignore things like errno
1308 // and floating-point exceptions.
1309 bool AttributesSafe =
1310 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1311
1312 // Other than that we need float(float) or double(double)
1313 return AttributesSafe && FT->getNumParams() == 1 &&
1314 FT->getReturnType() == FT->getParamType(0) &&
1315 (FT->getParamType(0)->isFloatTy() ||
1316 FT->getParamType(0)->isDoubleTy());
1317}
1318
1319void
1320LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1321 SmallVectorImpl<CallInst *> &SinCalls,
1322 SmallVectorImpl<CallInst *> &CosCalls,
1323 SmallVectorImpl<CallInst *> &SinCosCalls) {
1324 CallInst *CI = dyn_cast<CallInst>(Val);
1325
1326 if (!CI)
1327 return;
1328
1329 Function *Callee = CI->getCalledFunction();
1330 StringRef FuncName = Callee->getName();
1331 LibFunc::Func Func;
1332 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1333 return;
1334
1335 if (IsFloat) {
1336 if (Func == LibFunc::sinpif)
1337 SinCalls.push_back(CI);
1338 else if (Func == LibFunc::cospif)
1339 CosCalls.push_back(CI);
1340 else if (Func == LibFunc::sincospif_stret)
1341 SinCosCalls.push_back(CI);
1342 } else {
1343 if (Func == LibFunc::sinpi)
1344 SinCalls.push_back(CI);
1345 else if (Func == LibFunc::cospi)
1346 CosCalls.push_back(CI);
1347 else if (Func == LibFunc::sincospi_stret)
1348 SinCosCalls.push_back(CI);
1349 }
1350}
1351
1352void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1353 Value *Res) {
1354 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1355 I != E; ++I) {
1356 replaceAllUsesWith(*I, Res);
1357 }
1358}
1359
1360void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1361 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1362 Type *ArgTy = Arg->getType();
1363 Type *ResTy;
1364 StringRef Name;
1365
1366 Triple T(OrigCallee->getParent()->getTargetTriple());
1367 if (UseFloat) {
1368 Name = "__sincospif_stret";
1369
1370 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1371 // x86_64 can't use {float, float} since that would be returned in both
1372 // xmm0 and xmm1, which isn't what a real struct would do.
1373 ResTy = T.getArch() == Triple::x86_64
1374 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001375 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001376 } else {
1377 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001378 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001379 }
1380
1381 Module *M = OrigCallee->getParent();
1382 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001383 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001384
1385 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1386 // If the argument is an instruction, it must dominate all uses so put our
1387 // sincos call there.
1388 BasicBlock::iterator Loc = ArgInst;
1389 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1390 } else {
1391 // Otherwise (e.g. for a constant) the beginning of the function is as
1392 // good a place as any.
1393 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1394 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1395 }
1396
1397 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1398
1399 if (SinCos->getType()->isStructTy()) {
1400 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1401 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1402 } else {
1403 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1404 "sinpi");
1405 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1406 "cospi");
1407 }
1408}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001409
Meador Inge7415f842012-11-25 20:45:27 +00001410//===----------------------------------------------------------------------===//
1411// Integer Library Call Optimizations
1412//===----------------------------------------------------------------------===//
1413
Chris Bienemanad070d02014-09-17 20:55:46 +00001414Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1415 Function *Callee = CI->getCalledFunction();
1416 FunctionType *FT = Callee->getFunctionType();
1417 // Just make sure this has 2 arguments of the same FP type, which match the
1418 // result type.
1419 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1420 !FT->getParamType(0)->isIntegerTy())
1421 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001422
Chris Bienemanad070d02014-09-17 20:55:46 +00001423 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001424
Chris Bienemanad070d02014-09-17 20:55:46 +00001425 // Constant fold.
1426 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1427 if (CI->isZero()) // ffs(0) -> 0.
1428 return B.getInt32(0);
1429 // ffs(c) -> cttz(c)+1
1430 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001431 }
Meador Inge7415f842012-11-25 20:45:27 +00001432
Chris Bienemanad070d02014-09-17 20:55:46 +00001433 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1434 Type *ArgType = Op->getType();
1435 Value *F =
1436 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1437 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1438 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1439 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001440
Chris Bienemanad070d02014-09-17 20:55:46 +00001441 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1442 return B.CreateSelect(Cond, V, B.getInt32(0));
1443}
Meador Ingea0b6d872012-11-26 00:24:07 +00001444
Chris Bienemanad070d02014-09-17 20:55:46 +00001445Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1446 Function *Callee = CI->getCalledFunction();
1447 FunctionType *FT = Callee->getFunctionType();
1448 // We require integer(integer) where the types agree.
1449 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1450 FT->getParamType(0) != FT->getReturnType())
1451 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001452
Chris Bienemanad070d02014-09-17 20:55:46 +00001453 // abs(x) -> x >s -1 ? x : -x
1454 Value *Op = CI->getArgOperand(0);
1455 Value *Pos =
1456 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1457 Value *Neg = B.CreateNeg(Op, "neg");
1458 return B.CreateSelect(Pos, Op, Neg);
1459}
Meador Inge9a59ab62012-11-26 02:31:59 +00001460
Chris Bienemanad070d02014-09-17 20:55:46 +00001461Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1462 Function *Callee = CI->getCalledFunction();
1463 FunctionType *FT = Callee->getFunctionType();
1464 // We require integer(i32)
1465 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1466 !FT->getParamType(0)->isIntegerTy(32))
1467 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001468
Chris Bienemanad070d02014-09-17 20:55:46 +00001469 // isdigit(c) -> (c-'0') <u 10
1470 Value *Op = CI->getArgOperand(0);
1471 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1472 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1473 return B.CreateZExt(Op, CI->getType());
1474}
Meador Ingea62a39e2012-11-26 03:10:07 +00001475
Chris Bienemanad070d02014-09-17 20:55:46 +00001476Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1477 Function *Callee = CI->getCalledFunction();
1478 FunctionType *FT = Callee->getFunctionType();
1479 // We require integer(i32)
1480 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1481 !FT->getParamType(0)->isIntegerTy(32))
1482 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001483
Chris Bienemanad070d02014-09-17 20:55:46 +00001484 // isascii(c) -> c <u 128
1485 Value *Op = CI->getArgOperand(0);
1486 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1487 return B.CreateZExt(Op, CI->getType());
1488}
1489
1490Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1491 Function *Callee = CI->getCalledFunction();
1492 FunctionType *FT = Callee->getFunctionType();
1493 // We require i32(i32)
1494 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1495 !FT->getParamType(0)->isIntegerTy(32))
1496 return nullptr;
1497
1498 // toascii(c) -> c & 0x7f
1499 return B.CreateAnd(CI->getArgOperand(0),
1500 ConstantInt::get(CI->getType(), 0x7F));
1501}
Meador Inge604937d2012-11-26 03:38:52 +00001502
Meador Inge08ca1152012-11-26 20:37:20 +00001503//===----------------------------------------------------------------------===//
1504// Formatting and IO Library Call Optimizations
1505//===----------------------------------------------------------------------===//
1506
Chris Bienemanad070d02014-09-17 20:55:46 +00001507static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001508
Chris Bienemanad070d02014-09-17 20:55:46 +00001509Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1510 int StreamArg) {
1511 // Error reporting calls should be cold, mark them as such.
1512 // This applies even to non-builtin calls: it is only a hint and applies to
1513 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001514
Chris Bienemanad070d02014-09-17 20:55:46 +00001515 // This heuristic was suggested in:
1516 // Improving Static Branch Prediction in a Compiler
1517 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1518 // Proceedings of PACT'98, Oct. 1998, IEEE
1519 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001520
Chris Bienemanad070d02014-09-17 20:55:46 +00001521 if (!CI->hasFnAttr(Attribute::Cold) &&
1522 isReportingError(Callee, CI, StreamArg)) {
1523 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1524 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001525
Chris Bienemanad070d02014-09-17 20:55:46 +00001526 return nullptr;
1527}
1528
1529static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1530 if (!ColdErrorCalls)
1531 return false;
1532
1533 if (!Callee || !Callee->isDeclaration())
1534 return false;
1535
1536 if (StreamArg < 0)
1537 return true;
1538
1539 // These functions might be considered cold, but only if their stream
1540 // argument is stderr.
1541
1542 if (StreamArg >= (int)CI->getNumArgOperands())
1543 return false;
1544 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1545 if (!LI)
1546 return false;
1547 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1548 if (!GV || !GV->isDeclaration())
1549 return false;
1550 return GV->getName() == "stderr";
1551}
1552
1553Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1554 // Check for a fixed format string.
1555 StringRef FormatStr;
1556 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001557 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001558
Chris Bienemanad070d02014-09-17 20:55:46 +00001559 // Empty format string -> noop.
1560 if (FormatStr.empty()) // Tolerate printf's declared void.
1561 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001562
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 // Do not do any of the following transformations if the printf return value
1564 // is used, in general the printf return value is not compatible with either
1565 // putchar() or puts().
1566 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001567 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001568
1569 // printf("x") -> putchar('x'), even for '%'.
1570 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001571 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001572 if (CI->use_empty() || !Res)
1573 return Res;
1574 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001575 }
1576
Chris Bienemanad070d02014-09-17 20:55:46 +00001577 // printf("foo\n") --> puts("foo")
1578 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1579 FormatStr.find('%') == StringRef::npos) { // No format characters.
1580 // Create a string literal with no \n on it. We expect the constant merge
1581 // pass to be run after this pass, to merge duplicate strings.
1582 FormatStr = FormatStr.drop_back();
1583 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001584 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001585 return (CI->use_empty() || !NewCI)
1586 ? NewCI
1587 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1588 }
Meador Inge08ca1152012-11-26 20:37:20 +00001589
Chris Bienemanad070d02014-09-17 20:55:46 +00001590 // Optimize specific format strings.
1591 // printf("%c", chr) --> putchar(chr)
1592 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1593 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001594 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001595
Chris Bienemanad070d02014-09-17 20:55:46 +00001596 if (CI->use_empty() || !Res)
1597 return Res;
1598 return B.CreateIntCast(Res, CI->getType(), true);
1599 }
1600
1601 // printf("%s\n", str) --> puts(str)
1602 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1603 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001604 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001605 }
1606 return nullptr;
1607}
1608
1609Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1610
1611 Function *Callee = CI->getCalledFunction();
1612 // Require one fixed pointer argument and an integer/void result.
1613 FunctionType *FT = Callee->getFunctionType();
1614 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1615 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1616 return nullptr;
1617
1618 if (Value *V = optimizePrintFString(CI, B)) {
1619 return V;
1620 }
1621
1622 // printf(format, ...) -> iprintf(format, ...) if no floating point
1623 // arguments.
1624 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1625 Module *M = B.GetInsertBlock()->getParent()->getParent();
1626 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001627 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001628 CallInst *New = cast<CallInst>(CI->clone());
1629 New->setCalledFunction(IPrintFFn);
1630 B.Insert(New);
1631 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001632 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 return nullptr;
1634}
Meador Inge08ca1152012-11-26 20:37:20 +00001635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1637 // Check for a fixed format string.
1638 StringRef FormatStr;
1639 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001640 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001641
Chris Bienemanad070d02014-09-17 20:55:46 +00001642 // If we just have a format string (nothing else crazy) transform it.
1643 if (CI->getNumArgOperands() == 2) {
1644 // Make sure there's no % in the constant array. We could try to handle
1645 // %% -> % in the future if we cared.
1646 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1647 if (FormatStr[i] == '%')
1648 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001649
Chris Bienemanad070d02014-09-17 20:55:46 +00001650 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001651 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1652 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1653 FormatStr.size() + 1),
1654 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001655 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001656 }
Meador Ingef8e72502012-11-29 15:45:43 +00001657
Chris Bienemanad070d02014-09-17 20:55:46 +00001658 // The remaining optimizations require the format string to be "%s" or "%c"
1659 // and have an extra operand.
1660 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1661 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001662 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001663
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 // Decode the second character of the format string.
1665 if (FormatStr[1] == 'c') {
1666 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1667 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1668 return nullptr;
1669 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1670 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1671 B.CreateStore(V, Ptr);
1672 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1673 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001674
Chris Bienemanad070d02014-09-17 20:55:46 +00001675 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001676 }
1677
Chris Bienemanad070d02014-09-17 20:55:46 +00001678 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1680 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1681 return nullptr;
1682
1683 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1684 if (!Len)
1685 return nullptr;
1686 Value *IncLen =
1687 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1688 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1689
1690 // The sprintf result is the unincremented number of bytes in the string.
1691 return B.CreateIntCast(Len, CI->getType(), false);
1692 }
1693 return nullptr;
1694}
1695
1696Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1697 Function *Callee = CI->getCalledFunction();
1698 // Require two fixed pointer arguments and an integer result.
1699 FunctionType *FT = Callee->getFunctionType();
1700 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1701 !FT->getParamType(1)->isPointerTy() ||
1702 !FT->getReturnType()->isIntegerTy())
1703 return nullptr;
1704
1705 if (Value *V = optimizeSPrintFString(CI, B)) {
1706 return V;
1707 }
1708
1709 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1710 // point arguments.
1711 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1712 Module *M = B.GetInsertBlock()->getParent()->getParent();
1713 Constant *SIPrintFFn =
1714 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1715 CallInst *New = cast<CallInst>(CI->clone());
1716 New->setCalledFunction(SIPrintFFn);
1717 B.Insert(New);
1718 return New;
1719 }
1720 return nullptr;
1721}
1722
1723Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1724 optimizeErrorReporting(CI, B, 0);
1725
1726 // All the optimizations depend on the format string.
1727 StringRef FormatStr;
1728 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1729 return nullptr;
1730
1731 // Do not do any of the following transformations if the fprintf return
1732 // value is used, in general the fprintf return value is not compatible
1733 // with fwrite(), fputc() or fputs().
1734 if (!CI->use_empty())
1735 return nullptr;
1736
1737 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1738 if (CI->getNumArgOperands() == 2) {
1739 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1740 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1741 return nullptr; // We found a format specifier.
1742
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 return EmitFWrite(
1744 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001745 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001746 CI->getArgOperand(0), B, DL, TLI);
1747 }
1748
1749 // The remaining optimizations require the format string to be "%s" or "%c"
1750 // and have an extra operand.
1751 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1752 CI->getNumArgOperands() < 3)
1753 return nullptr;
1754
1755 // Decode the second character of the format string.
1756 if (FormatStr[1] == 'c') {
1757 // fprintf(F, "%c", chr) --> fputc(chr, F)
1758 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1759 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001760 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001761 }
1762
1763 if (FormatStr[1] == 's') {
1764 // fprintf(F, "%s", str) --> fputs(str, F)
1765 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1766 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001767 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 }
1769 return nullptr;
1770}
1771
1772Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1773 Function *Callee = CI->getCalledFunction();
1774 // Require two fixed paramters as pointers and integer result.
1775 FunctionType *FT = Callee->getFunctionType();
1776 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1777 !FT->getParamType(1)->isPointerTy() ||
1778 !FT->getReturnType()->isIntegerTy())
1779 return nullptr;
1780
1781 if (Value *V = optimizeFPrintFString(CI, B)) {
1782 return V;
1783 }
1784
1785 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1786 // floating point arguments.
1787 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1788 Module *M = B.GetInsertBlock()->getParent()->getParent();
1789 Constant *FIPrintFFn =
1790 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1791 CallInst *New = cast<CallInst>(CI->clone());
1792 New->setCalledFunction(FIPrintFFn);
1793 B.Insert(New);
1794 return New;
1795 }
1796 return nullptr;
1797}
1798
1799Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1800 optimizeErrorReporting(CI, B, 3);
1801
1802 Function *Callee = CI->getCalledFunction();
1803 // Require a pointer, an integer, an integer, a pointer, returning integer.
1804 FunctionType *FT = Callee->getFunctionType();
1805 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1806 !FT->getParamType(1)->isIntegerTy() ||
1807 !FT->getParamType(2)->isIntegerTy() ||
1808 !FT->getParamType(3)->isPointerTy() ||
1809 !FT->getReturnType()->isIntegerTy())
1810 return nullptr;
1811
1812 // Get the element size and count.
1813 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1814 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1815 if (!SizeC || !CountC)
1816 return nullptr;
1817 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1818
1819 // If this is writing zero records, remove the call (it's a noop).
1820 if (Bytes == 0)
1821 return ConstantInt::get(CI->getType(), 0);
1822
1823 // If this is writing one byte, turn it into fputc.
1824 // This optimisation is only valid, if the return value is unused.
1825 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1826 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001827 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1829 }
1830
1831 return nullptr;
1832}
1833
1834Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1835 optimizeErrorReporting(CI, B, 1);
1836
1837 Function *Callee = CI->getCalledFunction();
1838
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 // Require two pointers. Also, we can't optimize if return value is used.
1840 FunctionType *FT = Callee->getFunctionType();
1841 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1842 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1843 return nullptr;
1844
1845 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1846 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1847 if (!Len)
1848 return nullptr;
1849
1850 // Known to have no uses (see above).
1851 return EmitFWrite(
1852 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001853 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001854 CI->getArgOperand(1), B, DL, TLI);
1855}
1856
1857Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1858 Function *Callee = CI->getCalledFunction();
1859 // Require one fixed pointer argument and an integer/void result.
1860 FunctionType *FT = Callee->getFunctionType();
1861 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1862 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1863 return nullptr;
1864
1865 // Check for a constant string.
1866 StringRef Str;
1867 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1868 return nullptr;
1869
1870 if (Str.empty() && CI->use_empty()) {
1871 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001872 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 if (CI->use_empty() || !Res)
1874 return Res;
1875 return B.CreateIntCast(Res, CI->getType(), true);
1876 }
1877
1878 return nullptr;
1879}
1880
1881bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001882 LibFunc::Func Func;
1883 SmallString<20> FloatFuncName = FuncName;
1884 FloatFuncName += 'f';
1885 if (TLI->getLibFunc(FloatFuncName, Func))
1886 return TLI->has(Func);
1887 return false;
1888}
Meador Inge7fb2f732012-10-13 16:45:32 +00001889
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001890Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1891 IRBuilder<> &Builder) {
1892 LibFunc::Func Func;
1893 Function *Callee = CI->getCalledFunction();
1894 StringRef FuncName = Callee->getName();
1895
1896 // Check for string/memory library functions.
1897 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
1898 // Make sure we never change the calling convention.
1899 assert((ignoreCallingConv(Func) ||
1900 CI->getCallingConv() == llvm::CallingConv::C) &&
1901 "Optimizing string/memory libcall would change the calling convention");
1902 switch (Func) {
1903 case LibFunc::strcat:
1904 return optimizeStrCat(CI, Builder);
1905 case LibFunc::strncat:
1906 return optimizeStrNCat(CI, Builder);
1907 case LibFunc::strchr:
1908 return optimizeStrChr(CI, Builder);
1909 case LibFunc::strrchr:
1910 return optimizeStrRChr(CI, Builder);
1911 case LibFunc::strcmp:
1912 return optimizeStrCmp(CI, Builder);
1913 case LibFunc::strncmp:
1914 return optimizeStrNCmp(CI, Builder);
1915 case LibFunc::strcpy:
1916 return optimizeStrCpy(CI, Builder);
1917 case LibFunc::stpcpy:
1918 return optimizeStpCpy(CI, Builder);
1919 case LibFunc::strncpy:
1920 return optimizeStrNCpy(CI, Builder);
1921 case LibFunc::strlen:
1922 return optimizeStrLen(CI, Builder);
1923 case LibFunc::strpbrk:
1924 return optimizeStrPBrk(CI, Builder);
1925 case LibFunc::strtol:
1926 case LibFunc::strtod:
1927 case LibFunc::strtof:
1928 case LibFunc::strtoul:
1929 case LibFunc::strtoll:
1930 case LibFunc::strtold:
1931 case LibFunc::strtoull:
1932 return optimizeStrTo(CI, Builder);
1933 case LibFunc::strspn:
1934 return optimizeStrSpn(CI, Builder);
1935 case LibFunc::strcspn:
1936 return optimizeStrCSpn(CI, Builder);
1937 case LibFunc::strstr:
1938 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00001939 case LibFunc::memchr:
1940 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001941 case LibFunc::memcmp:
1942 return optimizeMemCmp(CI, Builder);
1943 case LibFunc::memcpy:
1944 return optimizeMemCpy(CI, Builder);
1945 case LibFunc::memmove:
1946 return optimizeMemMove(CI, Builder);
1947 case LibFunc::memset:
1948 return optimizeMemSet(CI, Builder);
1949 default:
1950 break;
1951 }
1952 }
1953 return nullptr;
1954}
1955
Chris Bienemanad070d02014-09-17 20:55:46 +00001956Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1957 if (CI->isNoBuiltin())
1958 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001959
Meador Inge20255ef2013-03-12 00:08:29 +00001960 LibFunc::Func Func;
1961 Function *Callee = CI->getCalledFunction();
1962 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00001963 IRBuilder<> Builder(CI);
1964 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00001965
Sanjay Patela92fa442014-10-22 15:29:23 +00001966 // Command-line parameter overrides function attribute.
1967 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1968 UnsafeFPShrink = EnableUnsafeFPShrink;
1969 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
1970 // FIXME: This is the same problem as described in optimizeSqrt().
1971 // If calls gain access to IR-level FMF, then use that instead of a
1972 // function attribute.
1973
1974 // Check for unsafe-fp-math = true.
1975 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
1976 if (Attr.getValueAsString() == "true")
1977 UnsafeFPShrink = true;
1978 }
1979
Sanjay Patel848309d2014-10-23 21:52:45 +00001980 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00001981 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001982 if (!isCallingConvC)
1983 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001984 switch (II->getIntrinsicID()) {
1985 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00001986 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001987 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00001988 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001989 case Intrinsic::fabs:
1990 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00001991 case Intrinsic::sqrt:
1992 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001993 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00001994 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001995 }
1996 }
1997
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001998 // Also try to simplify calls to fortified library functions.
1999 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2000 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002001 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
2002 if (SimplifiedCI && SimplifiedCI->getCalledFunction())
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002003 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
2004 // If we were able to further simplify, remove the now redundant call.
2005 SimplifiedCI->replaceAllUsesWith(V);
2006 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002007 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002008 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002009 return SimplifiedFortifiedCI;
2010 }
2011
Meador Inge20255ef2013-03-12 00:08:29 +00002012 // Then check for known library functions.
2013 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002014 // We never change the calling convention.
2015 if (!ignoreCallingConv(Func) && !isCallingConvC)
2016 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002017 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2018 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002019 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002020 case LibFunc::cosf:
2021 case LibFunc::cos:
2022 case LibFunc::cosl:
2023 return optimizeCos(CI, Builder);
2024 case LibFunc::sinpif:
2025 case LibFunc::sinpi:
2026 case LibFunc::cospif:
2027 case LibFunc::cospi:
2028 return optimizeSinCosPi(CI, Builder);
2029 case LibFunc::powf:
2030 case LibFunc::pow:
2031 case LibFunc::powl:
2032 return optimizePow(CI, Builder);
2033 case LibFunc::exp2l:
2034 case LibFunc::exp2:
2035 case LibFunc::exp2f:
2036 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002037 case LibFunc::fabsf:
2038 case LibFunc::fabs:
2039 case LibFunc::fabsl:
2040 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002041 case LibFunc::sqrtf:
2042 case LibFunc::sqrt:
2043 case LibFunc::sqrtl:
2044 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002045 case LibFunc::ffs:
2046 case LibFunc::ffsl:
2047 case LibFunc::ffsll:
2048 return optimizeFFS(CI, Builder);
2049 case LibFunc::abs:
2050 case LibFunc::labs:
2051 case LibFunc::llabs:
2052 return optimizeAbs(CI, Builder);
2053 case LibFunc::isdigit:
2054 return optimizeIsDigit(CI, Builder);
2055 case LibFunc::isascii:
2056 return optimizeIsAscii(CI, Builder);
2057 case LibFunc::toascii:
2058 return optimizeToAscii(CI, Builder);
2059 case LibFunc::printf:
2060 return optimizePrintF(CI, Builder);
2061 case LibFunc::sprintf:
2062 return optimizeSPrintF(CI, Builder);
2063 case LibFunc::fprintf:
2064 return optimizeFPrintF(CI, Builder);
2065 case LibFunc::fwrite:
2066 return optimizeFWrite(CI, Builder);
2067 case LibFunc::fputs:
2068 return optimizeFPuts(CI, Builder);
2069 case LibFunc::puts:
2070 return optimizePuts(CI, Builder);
2071 case LibFunc::perror:
2072 return optimizeErrorReporting(CI, Builder);
2073 case LibFunc::vfprintf:
2074 case LibFunc::fiprintf:
2075 return optimizeErrorReporting(CI, Builder, 0);
2076 case LibFunc::fputc:
2077 return optimizeErrorReporting(CI, Builder, 1);
2078 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002079 case LibFunc::floor:
2080 case LibFunc::rint:
2081 case LibFunc::round:
2082 case LibFunc::nearbyint:
2083 case LibFunc::trunc:
2084 if (hasFloatVersion(FuncName))
2085 return optimizeUnaryDoubleFP(CI, Builder, false);
2086 return nullptr;
2087 case LibFunc::acos:
2088 case LibFunc::acosh:
2089 case LibFunc::asin:
2090 case LibFunc::asinh:
2091 case LibFunc::atan:
2092 case LibFunc::atanh:
2093 case LibFunc::cbrt:
2094 case LibFunc::cosh:
2095 case LibFunc::exp:
2096 case LibFunc::exp10:
2097 case LibFunc::expm1:
2098 case LibFunc::log:
2099 case LibFunc::log10:
2100 case LibFunc::log1p:
2101 case LibFunc::log2:
2102 case LibFunc::logb:
2103 case LibFunc::sin:
2104 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002105 case LibFunc::tan:
2106 case LibFunc::tanh:
2107 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2108 return optimizeUnaryDoubleFP(CI, Builder, true);
2109 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002110 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002111 case LibFunc::fmin:
2112 case LibFunc::fmax:
2113 if (hasFloatVersion(FuncName))
2114 return optimizeBinaryDoubleFP(CI, Builder);
2115 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00002116 default:
2117 return nullptr;
2118 }
Meador Inge20255ef2013-03-12 00:08:29 +00002119 }
Craig Topperf40110f2014-04-25 05:29:35 +00002120 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002121}
2122
Chandler Carruth92803822015-01-21 02:11:59 +00002123LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002124 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002125 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002126 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002127 Replacer(Replacer) {}
2128
2129void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2130 // Indirect through the replacer used in this instance.
2131 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002132}
2133
Chandler Carruth92803822015-01-21 02:11:59 +00002134/*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
2135 Value *With) {
Meador Inge76fc1a42012-11-11 03:51:43 +00002136 I->replaceAllUsesWith(With);
2137 I->eraseFromParent();
2138}
2139
Meador Ingedfb08a22013-06-20 19:48:07 +00002140// TODO:
2141// Additional cases that we need to add to this file:
2142//
2143// cbrt:
2144// * cbrt(expN(X)) -> expN(x/3)
2145// * cbrt(sqrt(x)) -> pow(x,1/6)
2146// * cbrt(sqrt(x)) -> pow(x,1/9)
2147//
2148// exp, expf, expl:
2149// * exp(log(x)) -> x
2150//
2151// log, logf, logl:
2152// * log(exp(x)) -> x
2153// * log(x**y) -> y*log(x)
2154// * log(exp(y)) -> y*log(e)
2155// * log(exp2(y)) -> y*log(2)
2156// * log(exp10(y)) -> y*log(10)
2157// * log(sqrt(x)) -> 0.5*log(x)
2158// * log(pow(x,y)) -> y*log(x)
2159//
2160// lround, lroundf, lroundl:
2161// * lround(cnst) -> cnst'
2162//
2163// pow, powf, powl:
2164// * pow(exp(x),y) -> exp(x*y)
2165// * pow(sqrt(x),y) -> pow(x,y*0.5)
2166// * pow(pow(x,y),z)-> pow(x,y*z)
2167//
2168// round, roundf, roundl:
2169// * round(cnst) -> cnst'
2170//
2171// signbit:
2172// * signbit(cnst) -> cnst'
2173// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2174//
2175// sqrt, sqrtf, sqrtl:
2176// * sqrt(expN(x)) -> expN(x*0.5)
2177// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2178// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2179//
Meador Ingedfb08a22013-06-20 19:48:07 +00002180// tan, tanf, tanl:
2181// * tan(atan(x)) -> x
2182//
2183// trunc, truncf, truncl:
2184// * trunc(cnst) -> cnst'
2185//
2186//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002187
2188//===----------------------------------------------------------------------===//
2189// Fortified Library Call Optimizations
2190//===----------------------------------------------------------------------===//
2191
2192bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2193 unsigned ObjSizeOp,
2194 unsigned SizeOp,
2195 bool isString) {
2196 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2197 return true;
2198 if (ConstantInt *ObjSizeCI =
2199 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2200 if (ObjSizeCI->isAllOnesValue())
2201 return true;
2202 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2203 if (OnlyLowerUnknownSize)
2204 return false;
2205 if (isString) {
2206 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2207 // If the length is 0 we don't know how long it is and so we can't
2208 // remove the check.
2209 if (Len == 0)
2210 return false;
2211 return ObjSizeCI->getZExtValue() >= Len;
2212 }
2213 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2214 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2215 }
2216 return false;
2217}
2218
2219Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2220 Function *Callee = CI->getCalledFunction();
2221
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002222 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002223 return nullptr;
2224
2225 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2226 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2227 CI->getArgOperand(2), 1);
2228 return CI->getArgOperand(0);
2229 }
2230 return nullptr;
2231}
2232
2233Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2234 Function *Callee = CI->getCalledFunction();
2235
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002236 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002237 return nullptr;
2238
2239 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2240 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2241 CI->getArgOperand(2), 1);
2242 return CI->getArgOperand(0);
2243 }
2244 return nullptr;
2245}
2246
2247Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2248 Function *Callee = CI->getCalledFunction();
2249
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002250 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002251 return nullptr;
2252
2253 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2254 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2255 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2256 return CI->getArgOperand(0);
2257 }
2258 return nullptr;
2259}
2260
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002261Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2262 IRBuilder<> &B,
2263 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002264 Function *Callee = CI->getCalledFunction();
2265 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002266 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002267
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002268 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002269 return nullptr;
2270
2271 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2272 *ObjSize = CI->getArgOperand(2);
2273
2274 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002275 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002276 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
2277 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
2278 }
2279
2280 // If a) we don't have any length information, or b) we know this will
2281 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2282 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2283 // TODO: It might be nice to get a maximum length out of the possible
2284 // string lengths for varying.
2285 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002286 Value *Ret = EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002287 return Ret;
2288 } else if (!OnlyLowerUnknownSize) {
2289 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2290 uint64_t Len = GetStringLength(Src);
2291 if (Len == 0)
2292 return nullptr;
2293
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002294 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002295 Value *LenV = ConstantInt::get(SizeTTy, Len);
2296 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2297 // If the function was an __stpcpy_chk, and we were able to fold it into
2298 // a __memcpy_chk, we still need to return the correct end pointer.
2299 if (Ret && Func == LibFunc::stpcpy_chk)
2300 return B.CreateGEP(Dst, ConstantInt::get(SizeTTy, Len - 1));
2301 return Ret;
2302 }
2303 return nullptr;
2304}
2305
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002306Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2307 IRBuilder<> &B,
2308 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002309 Function *Callee = CI->getCalledFunction();
2310 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002311
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002312 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002313 return nullptr;
2314 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002315 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2316 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002317 return Ret;
2318 }
2319 return nullptr;
2320}
2321
2322Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
2323 if (CI->isNoBuiltin())
2324 return nullptr;
2325
2326 LibFunc::Func Func;
2327 Function *Callee = CI->getCalledFunction();
2328 StringRef FuncName = Callee->getName();
2329 IRBuilder<> Builder(CI);
2330 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2331
2332 // First, check that this is a known library functions.
2333 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func))
2334 return nullptr;
2335
2336 // We never change the calling convention.
2337 if (!ignoreCallingConv(Func) && !isCallingConvC)
2338 return nullptr;
2339
2340 switch (Func) {
2341 case LibFunc::memcpy_chk:
2342 return optimizeMemCpyChk(CI, Builder);
2343 case LibFunc::memmove_chk:
2344 return optimizeMemMoveChk(CI, Builder);
2345 case LibFunc::memset_chk:
2346 return optimizeMemSetChk(CI, Builder);
2347 case LibFunc::stpcpy_chk:
2348 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002349 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002350 case LibFunc::stpncpy_chk:
2351 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002352 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002353 default:
2354 break;
2355 }
2356 return nullptr;
2357}
2358
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002359FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2360 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2361 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}