blob: 8ea632546c7d49682f6f3f740a58525c95f06f4c [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Meador Ingedf796f82012-10-13 16:45:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000030#include "llvm/IR/PatternMatch.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000031#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000041 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000043
Sanjay Patela92fa442014-10-22 15:29:23 +000044static cl::opt<bool>
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
Chris Bienemanad070d02014-09-17 20:55:46 +000055static bool ignoreCallingConv(LibFunc::Func Func) {
Davide Italianob883b012015-11-12 23:39:00 +000056 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000058}
59
Meador Inged589ac62012-10-31 03:33:06 +000060/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
61/// value is equal or not-equal to zero.
62static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000063 for (User *U : V->users()) {
64 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000065 if (IC->isEquality())
66 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
67 if (C->isNullValue())
68 continue;
69 // Unknown instruction.
70 return false;
71 }
72 return true;
73}
74
Meador Inge56edbc92012-11-11 03:51:48 +000075/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
76/// comparisons with With.
77static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000078 for (User *U : V->users()) {
79 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000080 if (IC->isEquality() && IC->getOperand(1) == With)
81 continue;
82 // Unknown instruction.
83 return false;
84 }
85 return true;
86}
87
Meador Inge08ca1152012-11-26 20:37:20 +000088static bool callHasFloatingPointArgument(const CallInst *CI) {
89 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
90 it != e; ++it) {
91 if ((*it)->getType()->isFloatingPointTy())
92 return true;
93 }
94 return false;
95}
96
Benjamin Kramer2702caa2013-08-31 18:19:35 +000097/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000098/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000099static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
100 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
101 LibFunc::Func LongDoubleFn) {
102 switch (Ty->getTypeID()) {
103 case Type::FloatTyID:
104 return TLI->has(FloatFn);
105 case Type::DoubleTyID:
106 return TLI->has(DoubleFn);
107 default:
108 return TLI->has(LongDoubleFn);
109 }
110}
111
Davide Italianoa904e522015-10-29 02:58:44 +0000112/// \brief Check whether we can use unsafe floating point math for
113/// the function passed as input.
114static bool canUseUnsafeFPMath(Function *F) {
115
116 // FIXME: For finer-grain optimization, we need intrinsics to have the same
117 // fast-math flag decorations that are applied to FP instructions. For now,
118 // we have to rely on the function-level unsafe-fp-math attribute to do this
119 // optimization because there's no other way to express that the sqrt can be
120 // reassociated.
121 if (F->hasFnAttribute("unsafe-fp-math")) {
122 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
123 if (Attr.getValueAsString() == "true")
124 return true;
125 }
126 return false;
127}
128
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000129/// \brief Returns whether \p F matches the signature expected for the
130/// string/memory copying library function \p Func.
131/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
132/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000133static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
134 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000135 FunctionType *FT = F->getFunctionType();
136 LLVMContext &Context = F->getContext();
137 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000138 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000139 unsigned NumParams = FT->getNumParams();
140
141 // All string libfuncs return the same type as the first parameter.
142 if (FT->getReturnType() != FT->getParamType(0))
143 return false;
144
145 switch (Func) {
146 default:
147 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
148 case LibFunc::stpncpy_chk:
149 case LibFunc::strncpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpncpy:
152 case LibFunc::strncpy: {
153 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
155 return false;
156 break;
157 }
158 case LibFunc::strcpy_chk:
159 case LibFunc::stpcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::stpcpy:
162 case LibFunc::strcpy: {
163 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
164 FT->getParamType(0) != PCharTy)
165 return false;
166 break;
167 }
168 case LibFunc::memmove_chk:
169 case LibFunc::memcpy_chk:
170 --NumParams; // fallthrough
171 case LibFunc::memmove:
172 case LibFunc::memcpy: {
173 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
174 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
175 return false;
176 break;
177 }
178 case LibFunc::memset_chk:
179 --NumParams; // fallthrough
180 case LibFunc::memset: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
183 return false;
184 break;
185 }
186 }
187 // If this is a fortified libcall, the last parameter is a size_t.
188 if (NumParams == FT->getNumParams() - 1)
189 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
190 return true;
191}
192
Meador Inged589ac62012-10-31 03:33:06 +0000193//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000194// String and Memory Library Call Optimizations
195//===----------------------------------------------------------------------===//
196
Chris Bienemanad070d02014-09-17 20:55:46 +0000197Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
198 Function *Callee = CI->getCalledFunction();
199 // Verify the "strcat" function prototype.
200 FunctionType *FT = Callee->getFunctionType();
201 if (FT->getNumParams() != 2||
202 FT->getReturnType() != B.getInt8PtrTy() ||
203 FT->getParamType(0) != FT->getReturnType() ||
204 FT->getParamType(1) != FT->getReturnType())
205 return nullptr;
206
207 // Extract some information from the instruction
208 Value *Dst = CI->getArgOperand(0);
209 Value *Src = CI->getArgOperand(1);
210
211 // See if we can get the length of the input string.
212 uint64_t Len = GetStringLength(Src);
213 if (Len == 0)
214 return nullptr;
215 --Len; // Unbias length.
216
217 // Handle the simple, do-nothing case: strcat(x, "") -> x
218 if (Len == 0)
219 return Dst;
220
Chris Bienemanad070d02014-09-17 20:55:46 +0000221 return emitStrLenMemCpy(Src, Dst, Len, B);
222}
223
224Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
225 IRBuilder<> &B) {
226 // We need to find the end of the destination string. That's where the
227 // memory is to be moved to. We just generate a call to strlen.
228 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
229 if (!DstLen)
230 return nullptr;
231
232 // Now that we have the destination's length, we must index into the
233 // destination's pointer to get the actual memcpy destination (end of
234 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000235 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000236
237 // We have enough information to now generate the memcpy call to do the
238 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239 B.CreateMemCpy(CpyDst, Src,
240 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
241 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000242 return Dst;
243}
244
245Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
246 Function *Callee = CI->getCalledFunction();
247 // Verify the "strncat" function prototype.
248 FunctionType *FT = Callee->getFunctionType();
249 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
250 FT->getParamType(0) != FT->getReturnType() ||
251 FT->getParamType(1) != FT->getReturnType() ||
252 !FT->getParamType(2)->isIntegerTy())
253 return nullptr;
254
255 // Extract some information from the instruction
256 Value *Dst = CI->getArgOperand(0);
257 Value *Src = CI->getArgOperand(1);
258 uint64_t Len;
259
260 // We don't do anything if length is not constant
261 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
262 Len = LengthArg->getZExtValue();
263 else
264 return nullptr;
265
266 // See if we can get the length of the input string.
267 uint64_t SrcLen = GetStringLength(Src);
268 if (SrcLen == 0)
269 return nullptr;
270 --SrcLen; // Unbias length.
271
272 // Handle the simple, do-nothing cases:
273 // strncat(x, "", c) -> x
274 // strncat(x, c, 0) -> x
275 if (SrcLen == 0 || Len == 0)
276 return Dst;
277
Chris Bienemanad070d02014-09-17 20:55:46 +0000278 // We don't optimize this case
279 if (Len < SrcLen)
280 return nullptr;
281
282 // strncat(x, s, c) -> strcat(x, s)
283 // s is constant so the strcat can be optimized further
284 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
285}
286
287Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
288 Function *Callee = CI->getCalledFunction();
289 // Verify the "strchr" function prototype.
290 FunctionType *FT = Callee->getFunctionType();
291 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
292 FT->getParamType(0) != FT->getReturnType() ||
293 !FT->getParamType(1)->isIntegerTy(32))
294 return nullptr;
295
296 Value *SrcStr = CI->getArgOperand(0);
297
298 // If the second operand is non-constant, see if we can compute the length
299 // of the input string and turn this into memchr.
300 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
301 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000302 uint64_t Len = GetStringLength(SrcStr);
303 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
304 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000305
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
307 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
308 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000309 }
310
Chris Bienemanad070d02014-09-17 20:55:46 +0000311 // Otherwise, the character is a constant, see if the first argument is
312 // a string literal. If so, we can constant fold.
313 StringRef Str;
314 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000316 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000317 return nullptr;
318 }
319
320 // Compute the offset, make sure to handle the case when we're searching for
321 // zero (a weird way to spell strlen).
322 size_t I = (0xFF & CharC->getSExtValue()) == 0
323 ? Str.size()
324 : Str.find(CharC->getSExtValue());
325 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
326 return Constant::getNullValue(CI->getType());
327
328 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000329 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000330}
331
332Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
333 Function *Callee = CI->getCalledFunction();
334 // Verify the "strrchr" function prototype.
335 FunctionType *FT = Callee->getFunctionType();
336 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
337 FT->getParamType(0) != FT->getReturnType() ||
338 !FT->getParamType(1)->isIntegerTy(32))
339 return nullptr;
340
341 Value *SrcStr = CI->getArgOperand(0);
342 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
343
344 // Cannot fold anything if we're not looking for a constant.
345 if (!CharC)
346 return nullptr;
347
348 StringRef Str;
349 if (!getConstantStringInfo(SrcStr, Str)) {
350 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000351 if (CharC->isZero())
352 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000353 return nullptr;
354 }
355
356 // Compute the offset.
357 size_t I = (0xFF & CharC->getSExtValue()) == 0
358 ? Str.size()
359 : Str.rfind(CharC->getSExtValue());
360 if (I == StringRef::npos) // Didn't find the char. Return null.
361 return Constant::getNullValue(CI->getType());
362
363 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000364 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000365}
366
367Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
368 Function *Callee = CI->getCalledFunction();
369 // Verify the "strcmp" function prototype.
370 FunctionType *FT = Callee->getFunctionType();
371 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
372 FT->getParamType(0) != FT->getParamType(1) ||
373 FT->getParamType(0) != B.getInt8PtrTy())
374 return nullptr;
375
376 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
377 if (Str1P == Str2P) // strcmp(x,x) -> 0
378 return ConstantInt::get(CI->getType(), 0);
379
380 StringRef Str1, Str2;
381 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
382 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
383
384 // strcmp(x, y) -> cnst (if both x and y are constant strings)
385 if (HasStr1 && HasStr2)
386 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
387
388 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
389 return B.CreateNeg(
390 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
391
392 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
393 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
394
395 // strcmp(P, "x") -> memcmp(P, "x", 2)
396 uint64_t Len1 = GetStringLength(Str1P);
397 uint64_t Len2 = GetStringLength(Str2P);
398 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000399 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000401 std::min(Len1, Len2)),
402 B, DL, TLI);
403 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000404
Chris Bienemanad070d02014-09-17 20:55:46 +0000405 return nullptr;
406}
407
408Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
409 Function *Callee = CI->getCalledFunction();
410 // Verify the "strncmp" function prototype.
411 FunctionType *FT = Callee->getFunctionType();
412 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
413 FT->getParamType(0) != FT->getParamType(1) ||
414 FT->getParamType(0) != B.getInt8PtrTy() ||
415 !FT->getParamType(2)->isIntegerTy())
416 return nullptr;
417
418 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
419 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
420 return ConstantInt::get(CI->getType(), 0);
421
422 // Get the length argument if it is constant.
423 uint64_t Length;
424 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
425 Length = LengthArg->getZExtValue();
426 else
427 return nullptr;
428
429 if (Length == 0) // strncmp(x,y,0) -> 0
430 return ConstantInt::get(CI->getType(), 0);
431
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000432 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000433 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
434
435 StringRef Str1, Str2;
436 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
437 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
438
439 // strncmp(x, y) -> cnst (if both x and y are constant strings)
440 if (HasStr1 && HasStr2) {
441 StringRef SubStr1 = Str1.substr(0, Length);
442 StringRef SubStr2 = Str2.substr(0, Length);
443 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
444 }
445
446 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
447 return B.CreateNeg(
448 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
449
450 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
451 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
452
453 return nullptr;
454}
455
456Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
457 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000458
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000460 return nullptr;
461
462 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
463 if (Dst == Src) // strcpy(x,x) -> x
464 return Src;
465
Chris Bienemanad070d02014-09-17 20:55:46 +0000466 // See if we can get the length of the input string.
467 uint64_t Len = GetStringLength(Src);
468 if (Len == 0)
469 return nullptr;
470
471 // We have enough information to now generate the memcpy call to do the
472 // copy for us. Make a memcpy to copy the nul byte with align = 1.
473 B.CreateMemCpy(Dst, Src,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000475 return Dst;
476}
477
478Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
479 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000480 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000481 return nullptr;
482
483 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
484 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
485 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000486 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000487 }
488
489 // See if we can get the length of the input string.
490 uint64_t Len = GetStringLength(Src);
491 if (Len == 0)
492 return nullptr;
493
Davide Italianob7487e62015-11-02 23:07:14 +0000494 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000495 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000496 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000497 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000498
499 // We have enough information to now generate the memcpy call to do the
500 // copy for us. Make a memcpy to copy the nul byte with align = 1.
501 B.CreateMemCpy(Dst, Src, LenV, 1);
502 return DstEnd;
503}
504
505Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
506 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000507 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000508 return nullptr;
509
510 Value *Dst = CI->getArgOperand(0);
511 Value *Src = CI->getArgOperand(1);
512 Value *LenOp = CI->getArgOperand(2);
513
514 // See if we can get the length of the input string.
515 uint64_t SrcLen = GetStringLength(Src);
516 if (SrcLen == 0)
517 return nullptr;
518 --SrcLen;
519
520 if (SrcLen == 0) {
521 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
522 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000523 return Dst;
524 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000525
Chris Bienemanad070d02014-09-17 20:55:46 +0000526 uint64_t Len;
527 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
528 Len = LengthArg->getZExtValue();
529 else
530 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000531
Chris Bienemanad070d02014-09-17 20:55:46 +0000532 if (Len == 0)
533 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000534
Chris Bienemanad070d02014-09-17 20:55:46 +0000535 // Let strncpy handle the zero padding
536 if (Len > SrcLen + 1)
537 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000538
Davide Italianob7487e62015-11-02 23:07:14 +0000539 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000540 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000541 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000542
Chris Bienemanad070d02014-09-17 20:55:46 +0000543 return Dst;
544}
Meador Inge7fb2f732012-10-13 16:45:32 +0000545
Chris Bienemanad070d02014-09-17 20:55:46 +0000546Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
547 Function *Callee = CI->getCalledFunction();
548 FunctionType *FT = Callee->getFunctionType();
549 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
550 !FT->getReturnType()->isIntegerTy())
551 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000552
Chris Bienemanad070d02014-09-17 20:55:46 +0000553 Value *Src = CI->getArgOperand(0);
554
555 // Constant folding: strlen("xyz") -> 3
556 if (uint64_t Len = GetStringLength(Src))
557 return ConstantInt::get(CI->getType(), Len - 1);
558
559 // strlen(x?"foo":"bars") --> x ? 3 : 4
560 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
561 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
562 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
563 if (LenTrue && LenFalse) {
564 Function *Caller = CI->getParent()->getParent();
565 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
566 SI->getDebugLoc(),
567 "folded strlen(select) to select of constants");
568 return B.CreateSelect(SI->getCondition(),
569 ConstantInt::get(CI->getType(), LenTrue - 1),
570 ConstantInt::get(CI->getType(), LenFalse - 1));
571 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000572 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000573
Chris Bienemanad070d02014-09-17 20:55:46 +0000574 // strlen(x) != 0 --> *x != 0
575 // strlen(x) == 0 --> *x == 0
576 if (isOnlyUsedInZeroEqualityComparison(CI))
577 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000578
Chris Bienemanad070d02014-09-17 20:55:46 +0000579 return nullptr;
580}
Meador Inge17418502012-10-13 16:45:37 +0000581
Chris Bienemanad070d02014-09-17 20:55:46 +0000582Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
583 Function *Callee = CI->getCalledFunction();
584 FunctionType *FT = Callee->getFunctionType();
585 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
586 FT->getParamType(1) != FT->getParamType(0) ||
587 FT->getReturnType() != FT->getParamType(0))
588 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000589
Chris Bienemanad070d02014-09-17 20:55:46 +0000590 StringRef S1, S2;
591 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
592 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000593
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000594 // strpbrk(s, "") -> nullptr
595 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000596 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
597 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000598
Chris Bienemanad070d02014-09-17 20:55:46 +0000599 // Constant folding.
600 if (HasS1 && HasS2) {
601 size_t I = S1.find_first_of(S2);
602 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000603 return Constant::getNullValue(CI->getType());
604
David Blaikie3909da72015-03-30 20:42:56 +0000605 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000606 }
Meador Inge17418502012-10-13 16:45:37 +0000607
Chris Bienemanad070d02014-09-17 20:55:46 +0000608 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000609 if (HasS2 && S2.size() == 1)
610 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000611
612 return nullptr;
613}
614
615Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
616 Function *Callee = CI->getCalledFunction();
617 FunctionType *FT = Callee->getFunctionType();
618 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
619 !FT->getParamType(0)->isPointerTy() ||
620 !FT->getParamType(1)->isPointerTy())
621 return nullptr;
622
623 Value *EndPtr = CI->getArgOperand(1);
624 if (isa<ConstantPointerNull>(EndPtr)) {
625 // With a null EndPtr, this function won't capture the main argument.
626 // It would be readonly too, except that it still may write to errno.
627 CI->addAttribute(1, Attribute::NoCapture);
628 }
629
630 return nullptr;
631}
632
633Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
634 Function *Callee = CI->getCalledFunction();
635 FunctionType *FT = Callee->getFunctionType();
636 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
639 return nullptr;
640
641 StringRef S1, S2;
642 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
644
645 // strspn(s, "") -> 0
646 // strspn("", s) -> 0
647 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
648 return Constant::getNullValue(CI->getType());
649
650 // Constant folding.
651 if (HasS1 && HasS2) {
652 size_t Pos = S1.find_first_not_of(S2);
653 if (Pos == StringRef::npos)
654 Pos = S1.size();
655 return ConstantInt::get(CI->getType(), Pos);
656 }
657
658 return nullptr;
659}
660
661Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
662 Function *Callee = CI->getCalledFunction();
663 FunctionType *FT = Callee->getFunctionType();
664 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
665 FT->getParamType(1) != FT->getParamType(0) ||
666 !FT->getReturnType()->isIntegerTy())
667 return nullptr;
668
669 StringRef S1, S2;
670 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
671 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
672
673 // strcspn("", s) -> 0
674 if (HasS1 && S1.empty())
675 return Constant::getNullValue(CI->getType());
676
677 // Constant folding.
678 if (HasS1 && HasS2) {
679 size_t Pos = S1.find_first_of(S2);
680 if (Pos == StringRef::npos)
681 Pos = S1.size();
682 return ConstantInt::get(CI->getType(), Pos);
683 }
684
685 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000686 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000687 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
688
689 return nullptr;
690}
691
692Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
693 Function *Callee = CI->getCalledFunction();
694 FunctionType *FT = Callee->getFunctionType();
695 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
696 !FT->getParamType(1)->isPointerTy() ||
697 !FT->getReturnType()->isPointerTy())
698 return nullptr;
699
700 // fold strstr(x, x) -> x.
701 if (CI->getArgOperand(0) == CI->getArgOperand(1))
702 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
703
704 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000705 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
707 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000708 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000709 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
710 StrLen, B, DL, TLI);
711 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000712 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000713 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
714 ICmpInst *Old = cast<ICmpInst>(*UI++);
715 Value *Cmp =
716 B.CreateICmp(Old->getPredicate(), StrNCmp,
717 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
718 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000719 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 return CI;
721 }
Meador Inge17418502012-10-13 16:45:37 +0000722
Chris Bienemanad070d02014-09-17 20:55:46 +0000723 // See if either input string is a constant string.
724 StringRef SearchStr, ToFindStr;
725 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
726 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
727
728 // fold strstr(x, "") -> x.
729 if (HasStr2 && ToFindStr.empty())
730 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
731
732 // If both strings are known, constant fold it.
733 if (HasStr1 && HasStr2) {
734 size_t Offset = SearchStr.find(ToFindStr);
735
736 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000737 return Constant::getNullValue(CI->getType());
738
Chris Bienemanad070d02014-09-17 20:55:46 +0000739 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
740 Value *Result = CastToCStr(CI->getArgOperand(0), B);
741 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
742 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000743 }
Meador Inge17418502012-10-13 16:45:37 +0000744
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 // fold strstr(x, "y") -> strchr(x, 'y').
746 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000747 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000748 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
749 }
750 return nullptr;
751}
Meador Inge40b6fac2012-10-15 03:47:37 +0000752
Benjamin Kramer691363e2015-03-21 15:36:21 +0000753Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
754 Function *Callee = CI->getCalledFunction();
755 FunctionType *FT = Callee->getFunctionType();
756 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
757 !FT->getParamType(1)->isIntegerTy(32) ||
758 !FT->getParamType(2)->isIntegerTy() ||
759 !FT->getReturnType()->isPointerTy())
760 return nullptr;
761
762 Value *SrcStr = CI->getArgOperand(0);
763 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
764 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
765
766 // memchr(x, y, 0) -> null
767 if (LenC && LenC->isNullValue())
768 return Constant::getNullValue(CI->getType());
769
Benjamin Kramer7857d722015-03-21 21:09:33 +0000770 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000771 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000772 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000773 return nullptr;
774
775 // Truncate the string to LenC. If Str is smaller than LenC we will still only
776 // scan the string, as reading past the end of it is undefined and we can just
777 // return null if we don't find the char.
778 Str = Str.substr(0, LenC->getZExtValue());
779
Benjamin Kramer7857d722015-03-21 21:09:33 +0000780 // If the char is variable but the input str and length are not we can turn
781 // this memchr call into a simple bit field test. Of course this only works
782 // when the return value is only checked against null.
783 //
784 // It would be really nice to reuse switch lowering here but we can't change
785 // the CFG at this point.
786 //
787 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
788 // after bounds check.
789 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000790 unsigned char Max =
791 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
792 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000793
794 // Make sure the bit field we're about to create fits in a register on the
795 // target.
796 // FIXME: On a 64 bit architecture this prevents us from using the
797 // interesting range of alpha ascii chars. We could do better by emitting
798 // two bitfields or shifting the range by 64 if no lower chars are used.
799 if (!DL.fitsInLegalInteger(Max + 1))
800 return nullptr;
801
802 // For the bit field use a power-of-2 type with at least 8 bits to avoid
803 // creating unnecessary illegal types.
804 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
805
806 // Now build the bit field.
807 APInt Bitfield(Width, 0);
808 for (char C : Str)
809 Bitfield.setBit((unsigned char)C);
810 Value *BitfieldC = B.getInt(Bitfield);
811
812 // First check that the bit field access is within bounds.
813 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
814 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
815 "memchr.bounds");
816
817 // Create code that checks if the given bit is set in the field.
818 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
819 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
820
821 // Finally merge both checks and cast to pointer type. The inttoptr
822 // implicitly zexts the i1 to intptr type.
823 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
824 }
825
826 // Check if all arguments are constants. If so, we can constant fold.
827 if (!CharC)
828 return nullptr;
829
Benjamin Kramer691363e2015-03-21 15:36:21 +0000830 // Compute the offset.
831 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
832 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
833 return Constant::getNullValue(CI->getType());
834
835 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000836 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000837}
838
Chris Bienemanad070d02014-09-17 20:55:46 +0000839Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
840 Function *Callee = CI->getCalledFunction();
841 FunctionType *FT = Callee->getFunctionType();
842 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
843 !FT->getParamType(1)->isPointerTy() ||
844 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000845 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000846
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000848
Chris Bienemanad070d02014-09-17 20:55:46 +0000849 if (LHS == RHS) // memcmp(s,s,x) -> 0
850 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000851
Chris Bienemanad070d02014-09-17 20:55:46 +0000852 // Make sure we have a constant length.
853 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
854 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000855 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000856 uint64_t Len = LenC->getZExtValue();
857
858 if (Len == 0) // memcmp(s1,s2,0) -> 0
859 return Constant::getNullValue(CI->getType());
860
861 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
862 if (Len == 1) {
863 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
864 CI->getType(), "lhsv");
865 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
866 CI->getType(), "rhsv");
867 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000868 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000869
Chad Rosierdc655322015-08-28 18:30:18 +0000870 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
871 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
872
873 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
874 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
875
876 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
877 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
878
879 Type *LHSPtrTy =
880 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
881 Type *RHSPtrTy =
882 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
883
884 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
885 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
886
887 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
888 }
889 }
890
Chris Bienemanad070d02014-09-17 20:55:46 +0000891 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
892 StringRef LHSStr, RHSStr;
893 if (getConstantStringInfo(LHS, LHSStr) &&
894 getConstantStringInfo(RHS, RHSStr)) {
895 // Make sure we're not reading out-of-bounds memory.
896 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000897 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000898 // Fold the memcmp and normalize the result. This way we get consistent
899 // results across multiple platforms.
900 uint64_t Ret = 0;
901 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
902 if (Cmp < 0)
903 Ret = -1;
904 else if (Cmp > 0)
905 Ret = 1;
906 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000907 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000908
Chris Bienemanad070d02014-09-17 20:55:46 +0000909 return nullptr;
910}
Meador Inge9a6a1902012-10-31 00:20:56 +0000911
Chris Bienemanad070d02014-09-17 20:55:46 +0000912Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
913 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000914
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000915 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000916 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000917
Chris Bienemanad070d02014-09-17 20:55:46 +0000918 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
919 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
920 CI->getArgOperand(2), 1);
921 return CI->getArgOperand(0);
922}
Meador Inge05a625a2012-10-31 14:58:26 +0000923
Chris Bienemanad070d02014-09-17 20:55:46 +0000924Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
925 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000926
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000927 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000928 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000929
Chris Bienemanad070d02014-09-17 20:55:46 +0000930 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
931 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
932 CI->getArgOperand(2), 1);
933 return CI->getArgOperand(0);
934}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000935
Chris Bienemanad070d02014-09-17 20:55:46 +0000936Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
937 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000938
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000940 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000941
Chris Bienemanad070d02014-09-17 20:55:46 +0000942 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
943 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
944 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
945 return CI->getArgOperand(0);
946}
Meador Inged4825782012-11-11 06:49:03 +0000947
Meador Inge193e0352012-11-13 04:16:17 +0000948//===----------------------------------------------------------------------===//
949// Math Library Optimizations
950//===----------------------------------------------------------------------===//
951
Matthias Braund34e4d22014-12-03 21:46:33 +0000952/// Return a variant of Val with float type.
953/// Currently this works in two cases: If Val is an FPExtension of a float
954/// value to something bigger, simply return the operand.
955/// If Val is a ConstantFP but can be converted to a float ConstantFP without
956/// loss of precision do so.
957static Value *valueHasFloatPrecision(Value *Val) {
958 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
959 Value *Op = Cast->getOperand(0);
960 if (Op->getType()->isFloatTy())
961 return Op;
962 }
963 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
964 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000965 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000966 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000967 &losesInfo);
968 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000969 return ConstantFP::get(Const->getContext(), F);
970 }
971 return nullptr;
972}
973
Meador Inge193e0352012-11-13 04:16:17 +0000974//===----------------------------------------------------------------------===//
975// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
976
Chris Bienemanad070d02014-09-17 20:55:46 +0000977Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
978 bool CheckRetType) {
979 Function *Callee = CI->getCalledFunction();
980 FunctionType *FT = Callee->getFunctionType();
981 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
982 !FT->getParamType(0)->isDoubleTy())
983 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000984
Chris Bienemanad070d02014-09-17 20:55:46 +0000985 if (CheckRetType) {
986 // Check if all the uses for function like 'sin' are converted to float.
987 for (User *U : CI->users()) {
988 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
989 if (!Cast || !Cast->getType()->isFloatTy())
990 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000991 }
Meador Inge193e0352012-11-13 04:16:17 +0000992 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000993
994 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000995 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
996 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000997 return nullptr;
998
999 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001000 if (Callee->isIntrinsic()) {
1001 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001002 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001003 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1004 V = B.CreateCall(F, V);
1005 } else {
1006 // The call is a library call rather than an intrinsic.
1007 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1008 }
1009
Chris Bienemanad070d02014-09-17 20:55:46 +00001010 return B.CreateFPExt(V, B.getDoubleTy());
1011}
Meador Inge193e0352012-11-13 04:16:17 +00001012
Yi Jiang6ab044e2013-12-16 22:42:40 +00001013// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001014Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1015 Function *Callee = CI->getCalledFunction();
1016 FunctionType *FT = Callee->getFunctionType();
1017 // Just make sure this has 2 arguments of the same FP type, which match the
1018 // result type.
1019 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1020 FT->getParamType(0) != FT->getParamType(1) ||
1021 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001022 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001023
Chris Bienemanad070d02014-09-17 20:55:46 +00001024 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001025 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1026 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1027 if (V1 == nullptr)
1028 return nullptr;
1029 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1030 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001031 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001032
1033 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001034 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001035 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001036 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1037 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001038 return B.CreateFPExt(V, B.getDoubleTy());
1039}
1040
1041Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1042 Function *Callee = CI->getCalledFunction();
1043 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001044 StringRef Name = Callee->getName();
1045 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001046 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001047
Chris Bienemanad070d02014-09-17 20:55:46 +00001048 FunctionType *FT = Callee->getFunctionType();
1049 // Just make sure this has 1 argument of FP type, which matches the
1050 // result type.
1051 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1052 !FT->getParamType(0)->isFloatingPointTy())
1053 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001054
Chris Bienemanad070d02014-09-17 20:55:46 +00001055 // cos(-x) -> cos(x)
1056 Value *Op1 = CI->getArgOperand(0);
1057 if (BinaryOperator::isFNeg(Op1)) {
1058 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1059 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1060 }
1061 return Ret;
1062}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001063
Chris Bienemanad070d02014-09-17 20:55:46 +00001064Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1065 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001066 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001067 StringRef Name = Callee->getName();
1068 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001069 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001070
Chris Bienemanad070d02014-09-17 20:55:46 +00001071 FunctionType *FT = Callee->getFunctionType();
1072 // Just make sure this has 2 arguments of the same FP type, which match the
1073 // result type.
1074 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1075 FT->getParamType(0) != FT->getParamType(1) ||
1076 !FT->getParamType(0)->isFloatingPointTy())
1077 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001078
Chris Bienemanad070d02014-09-17 20:55:46 +00001079 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1080 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1081 // pow(1.0, x) -> 1.0
1082 if (Op1C->isExactlyValue(1.0))
1083 return Op1C;
1084 // pow(2.0, x) -> exp2(x)
1085 if (Op1C->isExactlyValue(2.0) &&
1086 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1087 LibFunc::exp2l))
Davide Italianod9f87b42015-11-06 21:05:07 +00001088 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1089 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001090 // pow(10.0, x) -> exp10(x)
1091 if (Op1C->isExactlyValue(10.0) &&
1092 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1093 LibFunc::exp10l))
1094 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1095 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001096 }
1097
Davide Italianoc8a79132015-11-03 20:32:23 +00001098 // pow(exp(x), y) -> exp(x*y)
1099 // pow(exp2(x), y) -> exp2(x * y)
1100 // We enable these only under fast-math. Besides rounding
1101 // differences the transformation changes overflow and
1102 // underflow behavior quite dramatically.
1103 // Example: x = 1000, y = 0.001.
1104 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
1105 if (canUseUnsafeFPMath(CI->getParent()->getParent())) {
1106 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1107 IRBuilder<>::FastMathFlagGuard Guard(B);
1108 FastMathFlags FMF;
1109 FMF.setUnsafeAlgebra();
1110 B.SetFastMathFlags(FMF);
1111
1112 LibFunc::Func Func;
1113 Function *Callee = OpC->getCalledFunction();
1114 StringRef FuncName = Callee->getName();
1115
1116 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1117 (Func == LibFunc::exp || Func == LibFunc::exp2))
1118 return EmitUnaryFloatFnCall(
1119 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"), FuncName, B,
1120 Callee->getAttributes());
1121 }
1122 }
1123
Chris Bienemanad070d02014-09-17 20:55:46 +00001124 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1125 if (!Op2C)
1126 return Ret;
1127
1128 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1129 return ConstantFP::get(CI->getType(), 1.0);
1130
1131 if (Op2C->isExactlyValue(0.5) &&
1132 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1133 LibFunc::sqrtl) &&
1134 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1135 LibFunc::fabsl)) {
1136 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1137 // This is faster than calling pow, and still handles negative zero
1138 // and negative infinity correctly.
1139 // TODO: In fast-math mode, this could be just sqrt(x).
1140 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1141 Value *Inf = ConstantFP::getInfinity(CI->getType());
1142 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1143 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1144 Value *FAbs =
1145 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1146 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1147 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1148 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001149 }
1150
Chris Bienemanad070d02014-09-17 20:55:46 +00001151 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1152 return Op1;
1153 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1154 return B.CreateFMul(Op1, Op1, "pow2");
1155 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1156 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1157 return nullptr;
1158}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001159
Chris Bienemanad070d02014-09-17 20:55:46 +00001160Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1161 Function *Callee = CI->getCalledFunction();
1162 Function *Caller = CI->getParent()->getParent();
Chris Bienemanad070d02014-09-17 20:55:46 +00001163 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001164 StringRef Name = Callee->getName();
1165 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001166 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001167
Chris Bienemanad070d02014-09-17 20:55:46 +00001168 FunctionType *FT = Callee->getFunctionType();
1169 // Just make sure this has 1 argument of FP type, which matches the
1170 // 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 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1177 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1178 LibFunc::Func LdExp = LibFunc::ldexpl;
1179 if (Op->getType()->isFloatTy())
1180 LdExp = LibFunc::ldexpf;
1181 else if (Op->getType()->isDoubleTy())
1182 LdExp = LibFunc::ldexp;
1183
1184 if (TLI->has(LdExp)) {
1185 Value *LdExpArg = nullptr;
1186 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1187 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1188 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1189 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1190 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1191 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1192 }
1193
1194 if (LdExpArg) {
1195 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1196 if (!Op->getType()->isFloatTy())
1197 One = ConstantExpr::getFPExtend(One, Op->getType());
1198
1199 Module *M = Caller->getParent();
1200 Value *Callee =
1201 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001202 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001203 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001204 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1205 CI->setCallingConv(F->getCallingConv());
1206
1207 return CI;
1208 }
1209 }
1210 return Ret;
1211}
1212
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001213Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1214 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001215 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001216 StringRef Name = Callee->getName();
1217 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001218 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001219
1220 FunctionType *FT = Callee->getFunctionType();
1221 // Make sure this has 1 argument of FP type which matches the result type.
1222 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1223 !FT->getParamType(0)->isFloatingPointTy())
1224 return Ret;
1225
1226 Value *Op = CI->getArgOperand(0);
1227 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1228 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1229 if (I->getOpcode() == Instruction::FMul)
1230 if (I->getOperand(0) == I->getOperand(1))
1231 return Op;
1232 }
1233 return Ret;
1234}
1235
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001236Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1237 // If we can shrink the call to a float function rather than a double
1238 // function, do that first.
1239 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001240 StringRef Name = Callee->getName();
1241 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1242 (Name == "fmax" && hasFloatVersion(Name))) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001243 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1244 if (Ret)
1245 return Ret;
1246 }
1247
1248 // Make sure this has 2 arguments of FP type which match the result type.
1249 FunctionType *FT = Callee->getFunctionType();
1250 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1251 FT->getParamType(0) != FT->getParamType(1) ||
1252 !FT->getParamType(0)->isFloatingPointTy())
1253 return nullptr;
1254
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001255 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001256 FastMathFlags FMF;
1257 Function *F = CI->getParent()->getParent();
Davide Italianoa904e522015-10-29 02:58:44 +00001258 if (canUseUnsafeFPMath(F)) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001259 // Unsafe algebra sets all fast-math-flags to true.
1260 FMF.setUnsafeAlgebra();
1261 } else {
1262 // At a minimum, no-nans-fp-math must be true.
Davide Italianoa904e522015-10-29 02:58:44 +00001263 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001264 if (Attr.getValueAsString() != "true")
1265 return nullptr;
1266 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1267 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001268 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001269 // might be impractical."
1270 FMF.setNoSignedZeros();
1271 FMF.setNoNaNs();
1272 }
1273 B.SetFastMathFlags(FMF);
1274
1275 // We have a relaxed floating-point environment. We can ignore NaN-handling
1276 // and transform to a compare and select. We do not have to consider errno or
1277 // exceptions, because fmin/fmax do not have those.
1278 Value *Op0 = CI->getArgOperand(0);
1279 Value *Op1 = CI->getArgOperand(1);
1280 Value *Cmp = Callee->getName().startswith("fmin") ?
1281 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1282 return B.CreateSelect(Cmp, Op0, Op1);
1283}
1284
Sanjay Patelc699a612014-10-16 18:48:17 +00001285Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1286 Function *Callee = CI->getCalledFunction();
1287
1288 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001289 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1290 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001291 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianoa904e522015-10-29 02:58:44 +00001292 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1293 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001294
Sanjay Patelc699a612014-10-16 18:48:17 +00001295 Value *Op = CI->getArgOperand(0);
1296 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1297 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1298 // We're looking for a repeated factor in a multiplication tree,
1299 // so we can do this fold: sqrt(x * x) -> fabs(x);
1300 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1301 Value *Op0 = I->getOperand(0);
1302 Value *Op1 = I->getOperand(1);
1303 Value *RepeatOp = nullptr;
1304 Value *OtherOp = nullptr;
1305 if (Op0 == Op1) {
1306 // Simple match: the operands of the multiply are identical.
1307 RepeatOp = Op0;
1308 } else {
1309 // Look for a more complicated pattern: one of the operands is itself
1310 // a multiply, so search for a common factor in that multiply.
1311 // Note: We don't bother looking any deeper than this first level or for
1312 // variations of this pattern because instcombine's visitFMUL and/or the
1313 // reassociation pass should give us this form.
1314 Value *OtherMul0, *OtherMul1;
1315 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1316 // Pattern: sqrt((x * y) * z)
1317 if (OtherMul0 == OtherMul1) {
1318 // Matched: sqrt((x * x) * z)
1319 RepeatOp = OtherMul0;
1320 OtherOp = Op1;
1321 }
1322 }
1323 }
1324 if (RepeatOp) {
1325 // Fast math flags for any created instructions should match the sqrt
1326 // and multiply.
1327 // FIXME: We're not checking the sqrt because it doesn't have
1328 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001329 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001330 B.SetFastMathFlags(I->getFastMathFlags());
1331 // If we found a repeated factor, hoist it out of the square root and
1332 // replace it with the fabs of that factor.
1333 Module *M = Callee->getParent();
1334 Type *ArgType = Op->getType();
1335 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1336 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1337 if (OtherOp) {
1338 // If we found a non-repeated factor, we still need to get its square
1339 // root. We then multiply that by the value that was simplified out
1340 // of the square root calculation.
1341 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1342 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1343 return B.CreateFMul(FabsCall, SqrtCall);
1344 }
1345 return FabsCall;
1346 }
1347 }
1348 }
1349 return Ret;
1350}
1351
Davide Italiano51507d22015-11-04 23:36:56 +00001352Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1353 Function *Callee = CI->getCalledFunction();
1354 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001355 StringRef Name = Callee->getName();
1356 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001357 Ret = optimizeUnaryDoubleFP(CI, B, true);
1358 FunctionType *FT = Callee->getFunctionType();
1359
1360 // Just make sure this has 1 argument of FP type, which matches the
1361 // result type.
1362 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1363 !FT->getParamType(0)->isFloatingPointTy())
1364 return Ret;
1365
1366 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1367 return Ret;
1368 Value *Op1 = CI->getArgOperand(0);
1369 auto *OpC = dyn_cast<CallInst>(Op1);
1370 if (!OpC)
1371 return Ret;
1372
1373 // tan(atan(x)) -> x
1374 // tanf(atanf(x)) -> x
1375 // tanl(atanl(x)) -> x
1376 LibFunc::Func Func;
1377 Function *F = OpC->getCalledFunction();
1378 StringRef FuncName = F->getName();
1379 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1380 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1381 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1382 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1383 Ret = OpC->getArgOperand(0);
1384 return Ret;
1385}
1386
Chris Bienemanad070d02014-09-17 20:55:46 +00001387static bool isTrigLibCall(CallInst *CI);
1388static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1389 bool UseFloat, Value *&Sin, Value *&Cos,
1390 Value *&SinCos);
1391
1392Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1393
1394 // Make sure the prototype is as expected, otherwise the rest of the
1395 // function is probably invalid and likely to abort.
1396 if (!isTrigLibCall(CI))
1397 return nullptr;
1398
1399 Value *Arg = CI->getArgOperand(0);
1400 SmallVector<CallInst *, 1> SinCalls;
1401 SmallVector<CallInst *, 1> CosCalls;
1402 SmallVector<CallInst *, 1> SinCosCalls;
1403
1404 bool IsFloat = Arg->getType()->isFloatTy();
1405
1406 // Look for all compatible sinpi, cospi and sincospi calls with the same
1407 // argument. If there are enough (in some sense) we can make the
1408 // substitution.
1409 for (User *U : Arg->users())
1410 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1411 SinCosCalls);
1412
1413 // It's only worthwhile if both sinpi and cospi are actually used.
1414 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1415 return nullptr;
1416
1417 Value *Sin, *Cos, *SinCos;
1418 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1419
1420 replaceTrigInsts(SinCalls, Sin);
1421 replaceTrigInsts(CosCalls, Cos);
1422 replaceTrigInsts(SinCosCalls, SinCos);
1423
1424 return nullptr;
1425}
1426
1427static bool isTrigLibCall(CallInst *CI) {
1428 Function *Callee = CI->getCalledFunction();
1429 FunctionType *FT = Callee->getFunctionType();
1430
1431 // We can only hope to do anything useful if we can ignore things like errno
1432 // and floating-point exceptions.
1433 bool AttributesSafe =
1434 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1435
1436 // Other than that we need float(float) or double(double)
1437 return AttributesSafe && FT->getNumParams() == 1 &&
1438 FT->getReturnType() == FT->getParamType(0) &&
1439 (FT->getParamType(0)->isFloatTy() ||
1440 FT->getParamType(0)->isDoubleTy());
1441}
1442
1443void
1444LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1445 SmallVectorImpl<CallInst *> &SinCalls,
1446 SmallVectorImpl<CallInst *> &CosCalls,
1447 SmallVectorImpl<CallInst *> &SinCosCalls) {
1448 CallInst *CI = dyn_cast<CallInst>(Val);
1449
1450 if (!CI)
1451 return;
1452
1453 Function *Callee = CI->getCalledFunction();
1454 StringRef FuncName = Callee->getName();
1455 LibFunc::Func Func;
1456 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1457 return;
1458
1459 if (IsFloat) {
1460 if (Func == LibFunc::sinpif)
1461 SinCalls.push_back(CI);
1462 else if (Func == LibFunc::cospif)
1463 CosCalls.push_back(CI);
1464 else if (Func == LibFunc::sincospif_stret)
1465 SinCosCalls.push_back(CI);
1466 } else {
1467 if (Func == LibFunc::sinpi)
1468 SinCalls.push_back(CI);
1469 else if (Func == LibFunc::cospi)
1470 CosCalls.push_back(CI);
1471 else if (Func == LibFunc::sincospi_stret)
1472 SinCosCalls.push_back(CI);
1473 }
1474}
1475
1476void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1477 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001478 for (CallInst *C : Calls)
1479 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001480}
1481
1482void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1483 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1484 Type *ArgTy = Arg->getType();
1485 Type *ResTy;
1486 StringRef Name;
1487
1488 Triple T(OrigCallee->getParent()->getTargetTriple());
1489 if (UseFloat) {
1490 Name = "__sincospif_stret";
1491
1492 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1493 // x86_64 can't use {float, float} since that would be returned in both
1494 // xmm0 and xmm1, which isn't what a real struct would do.
1495 ResTy = T.getArch() == Triple::x86_64
1496 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001497 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001498 } else {
1499 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001500 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001501 }
1502
1503 Module *M = OrigCallee->getParent();
1504 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001505 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001506
1507 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1508 // If the argument is an instruction, it must dominate all uses so put our
1509 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001510 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001511 } else {
1512 // Otherwise (e.g. for a constant) the beginning of the function is as
1513 // good a place as any.
1514 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1515 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1516 }
1517
1518 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1519
1520 if (SinCos->getType()->isStructTy()) {
1521 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1522 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1523 } else {
1524 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1525 "sinpi");
1526 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1527 "cospi");
1528 }
1529}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001530
Meador Inge7415f842012-11-25 20:45:27 +00001531//===----------------------------------------------------------------------===//
1532// Integer Library Call Optimizations
1533//===----------------------------------------------------------------------===//
1534
Davide Italiano396f3ee2015-10-31 23:17:45 +00001535static bool checkIntUnaryReturnAndParam(Function *Callee) {
1536 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001537 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1538 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001539}
1540
Chris Bienemanad070d02014-09-17 20:55:46 +00001541Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1542 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001543 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001544 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001545 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001546
Chris Bienemanad070d02014-09-17 20:55:46 +00001547 // Constant fold.
1548 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1549 if (CI->isZero()) // ffs(0) -> 0.
1550 return B.getInt32(0);
1551 // ffs(c) -> cttz(c)+1
1552 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001553 }
Meador Inge7415f842012-11-25 20:45:27 +00001554
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1556 Type *ArgType = Op->getType();
1557 Value *F =
1558 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001559 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1561 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001562
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1564 return B.CreateSelect(Cond, V, B.getInt32(0));
1565}
Meador Ingea0b6d872012-11-26 00:24:07 +00001566
Chris Bienemanad070d02014-09-17 20:55:46 +00001567Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1568 Function *Callee = CI->getCalledFunction();
1569 FunctionType *FT = Callee->getFunctionType();
1570 // We require integer(integer) where the types agree.
1571 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1572 FT->getParamType(0) != FT->getReturnType())
1573 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001574
Chris Bienemanad070d02014-09-17 20:55:46 +00001575 // abs(x) -> x >s -1 ? x : -x
1576 Value *Op = CI->getArgOperand(0);
1577 Value *Pos =
1578 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1579 Value *Neg = B.CreateNeg(Op, "neg");
1580 return B.CreateSelect(Pos, Op, Neg);
1581}
Meador Inge9a59ab62012-11-26 02:31:59 +00001582
Chris Bienemanad070d02014-09-17 20:55:46 +00001583Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001584 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001585 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001586
Chris Bienemanad070d02014-09-17 20:55:46 +00001587 // isdigit(c) -> (c-'0') <u 10
1588 Value *Op = CI->getArgOperand(0);
1589 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1590 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1591 return B.CreateZExt(Op, CI->getType());
1592}
Meador Ingea62a39e2012-11-26 03:10:07 +00001593
Chris Bienemanad070d02014-09-17 20:55:46 +00001594Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001595 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001596 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001597
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 // isascii(c) -> c <u 128
1599 Value *Op = CI->getArgOperand(0);
1600 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1601 return B.CreateZExt(Op, CI->getType());
1602}
1603
1604Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001605 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001606 return nullptr;
1607
1608 // toascii(c) -> c & 0x7f
1609 return B.CreateAnd(CI->getArgOperand(0),
1610 ConstantInt::get(CI->getType(), 0x7F));
1611}
Meador Inge604937d2012-11-26 03:38:52 +00001612
Meador Inge08ca1152012-11-26 20:37:20 +00001613//===----------------------------------------------------------------------===//
1614// Formatting and IO Library Call Optimizations
1615//===----------------------------------------------------------------------===//
1616
Chris Bienemanad070d02014-09-17 20:55:46 +00001617static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001618
Chris Bienemanad070d02014-09-17 20:55:46 +00001619Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1620 int StreamArg) {
1621 // Error reporting calls should be cold, mark them as such.
1622 // This applies even to non-builtin calls: it is only a hint and applies to
1623 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001624
Chris Bienemanad070d02014-09-17 20:55:46 +00001625 // This heuristic was suggested in:
1626 // Improving Static Branch Prediction in a Compiler
1627 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1628 // Proceedings of PACT'98, Oct. 1998, IEEE
1629 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001630
Chris Bienemanad070d02014-09-17 20:55:46 +00001631 if (!CI->hasFnAttr(Attribute::Cold) &&
1632 isReportingError(Callee, CI, StreamArg)) {
1633 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1634 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 return nullptr;
1637}
1638
1639static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001640 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001641 return false;
1642
1643 if (StreamArg < 0)
1644 return true;
1645
1646 // These functions might be considered cold, but only if their stream
1647 // argument is stderr.
1648
1649 if (StreamArg >= (int)CI->getNumArgOperands())
1650 return false;
1651 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1652 if (!LI)
1653 return false;
1654 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1655 if (!GV || !GV->isDeclaration())
1656 return false;
1657 return GV->getName() == "stderr";
1658}
1659
1660Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1661 // Check for a fixed format string.
1662 StringRef FormatStr;
1663 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001664 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001665
Chris Bienemanad070d02014-09-17 20:55:46 +00001666 // Empty format string -> noop.
1667 if (FormatStr.empty()) // Tolerate printf's declared void.
1668 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001669
Chris Bienemanad070d02014-09-17 20:55:46 +00001670 // Do not do any of the following transformations if the printf return value
1671 // is used, in general the printf return value is not compatible with either
1672 // putchar() or puts().
1673 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001674 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001675
1676 // printf("x") -> putchar('x'), even for '%'.
1677 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001678 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 if (CI->use_empty() || !Res)
1680 return Res;
1681 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001682 }
1683
Chris Bienemanad070d02014-09-17 20:55:46 +00001684 // printf("foo\n") --> puts("foo")
1685 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1686 FormatStr.find('%') == StringRef::npos) { // No format characters.
1687 // Create a string literal with no \n on it. We expect the constant merge
1688 // pass to be run after this pass, to merge duplicate strings.
1689 FormatStr = FormatStr.drop_back();
1690 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001691 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001692 return (CI->use_empty() || !NewCI)
1693 ? NewCI
1694 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1695 }
Meador Inge08ca1152012-11-26 20:37:20 +00001696
Chris Bienemanad070d02014-09-17 20:55:46 +00001697 // Optimize specific format strings.
1698 // printf("%c", chr) --> putchar(chr)
1699 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1700 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001701 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001702
Chris Bienemanad070d02014-09-17 20:55:46 +00001703 if (CI->use_empty() || !Res)
1704 return Res;
1705 return B.CreateIntCast(Res, CI->getType(), true);
1706 }
1707
1708 // printf("%s\n", str) --> puts(str)
1709 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1710 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001711 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001712 }
1713 return nullptr;
1714}
1715
1716Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1717
1718 Function *Callee = CI->getCalledFunction();
1719 // Require one fixed pointer argument and an integer/void result.
1720 FunctionType *FT = Callee->getFunctionType();
1721 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1722 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1723 return nullptr;
1724
1725 if (Value *V = optimizePrintFString(CI, B)) {
1726 return V;
1727 }
1728
1729 // printf(format, ...) -> iprintf(format, ...) if no floating point
1730 // arguments.
1731 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1732 Module *M = B.GetInsertBlock()->getParent()->getParent();
1733 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001734 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001735 CallInst *New = cast<CallInst>(CI->clone());
1736 New->setCalledFunction(IPrintFFn);
1737 B.Insert(New);
1738 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001739 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001740 return nullptr;
1741}
Meador Inge08ca1152012-11-26 20:37:20 +00001742
Chris Bienemanad070d02014-09-17 20:55:46 +00001743Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1744 // Check for a fixed format string.
1745 StringRef FormatStr;
1746 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001747 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001748
Chris Bienemanad070d02014-09-17 20:55:46 +00001749 // If we just have a format string (nothing else crazy) transform it.
1750 if (CI->getNumArgOperands() == 2) {
1751 // Make sure there's no % in the constant array. We could try to handle
1752 // %% -> % in the future if we cared.
1753 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1754 if (FormatStr[i] == '%')
1755 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001756
Chris Bienemanad070d02014-09-17 20:55:46 +00001757 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001758 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1759 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1760 FormatStr.size() + 1),
1761 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001762 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001763 }
Meador Ingef8e72502012-11-29 15:45:43 +00001764
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 // The remaining optimizations require the format string to be "%s" or "%c"
1766 // and have an extra operand.
1767 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1768 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001769 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001770
Chris Bienemanad070d02014-09-17 20:55:46 +00001771 // Decode the second character of the format string.
1772 if (FormatStr[1] == 'c') {
1773 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1774 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1775 return nullptr;
1776 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1777 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1778 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001779 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001780 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001781
Chris Bienemanad070d02014-09-17 20:55:46 +00001782 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001783 }
1784
Chris Bienemanad070d02014-09-17 20:55:46 +00001785 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001786 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1787 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1788 return nullptr;
1789
1790 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1791 if (!Len)
1792 return nullptr;
1793 Value *IncLen =
1794 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1795 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1796
1797 // The sprintf result is the unincremented number of bytes in the string.
1798 return B.CreateIntCast(Len, CI->getType(), false);
1799 }
1800 return nullptr;
1801}
1802
1803Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1804 Function *Callee = CI->getCalledFunction();
1805 // Require two fixed pointer arguments and an integer result.
1806 FunctionType *FT = Callee->getFunctionType();
1807 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1808 !FT->getParamType(1)->isPointerTy() ||
1809 !FT->getReturnType()->isIntegerTy())
1810 return nullptr;
1811
1812 if (Value *V = optimizeSPrintFString(CI, B)) {
1813 return V;
1814 }
1815
1816 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1817 // point arguments.
1818 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1819 Module *M = B.GetInsertBlock()->getParent()->getParent();
1820 Constant *SIPrintFFn =
1821 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1822 CallInst *New = cast<CallInst>(CI->clone());
1823 New->setCalledFunction(SIPrintFFn);
1824 B.Insert(New);
1825 return New;
1826 }
1827 return nullptr;
1828}
1829
1830Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1831 optimizeErrorReporting(CI, B, 0);
1832
1833 // All the optimizations depend on the format string.
1834 StringRef FormatStr;
1835 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1836 return nullptr;
1837
1838 // Do not do any of the following transformations if the fprintf return
1839 // value is used, in general the fprintf return value is not compatible
1840 // with fwrite(), fputc() or fputs().
1841 if (!CI->use_empty())
1842 return nullptr;
1843
1844 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1845 if (CI->getNumArgOperands() == 2) {
1846 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1847 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1848 return nullptr; // We found a format specifier.
1849
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 return EmitFWrite(
1851 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001852 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001853 CI->getArgOperand(0), B, DL, TLI);
1854 }
1855
1856 // The remaining optimizations require the format string to be "%s" or "%c"
1857 // and have an extra operand.
1858 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1859 CI->getNumArgOperands() < 3)
1860 return nullptr;
1861
1862 // Decode the second character of the format string.
1863 if (FormatStr[1] == 'c') {
1864 // fprintf(F, "%c", chr) --> fputc(chr, F)
1865 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1866 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001867 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001868 }
1869
1870 if (FormatStr[1] == 's') {
1871 // fprintf(F, "%s", str) --> fputs(str, F)
1872 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1873 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001874 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001875 }
1876 return nullptr;
1877}
1878
1879Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1880 Function *Callee = CI->getCalledFunction();
1881 // Require two fixed paramters as pointers and integer result.
1882 FunctionType *FT = Callee->getFunctionType();
1883 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1884 !FT->getParamType(1)->isPointerTy() ||
1885 !FT->getReturnType()->isIntegerTy())
1886 return nullptr;
1887
1888 if (Value *V = optimizeFPrintFString(CI, B)) {
1889 return V;
1890 }
1891
1892 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1893 // floating point arguments.
1894 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1895 Module *M = B.GetInsertBlock()->getParent()->getParent();
1896 Constant *FIPrintFFn =
1897 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1898 CallInst *New = cast<CallInst>(CI->clone());
1899 New->setCalledFunction(FIPrintFFn);
1900 B.Insert(New);
1901 return New;
1902 }
1903 return nullptr;
1904}
1905
1906Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1907 optimizeErrorReporting(CI, B, 3);
1908
1909 Function *Callee = CI->getCalledFunction();
1910 // Require a pointer, an integer, an integer, a pointer, returning integer.
1911 FunctionType *FT = Callee->getFunctionType();
1912 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1913 !FT->getParamType(1)->isIntegerTy() ||
1914 !FT->getParamType(2)->isIntegerTy() ||
1915 !FT->getParamType(3)->isPointerTy() ||
1916 !FT->getReturnType()->isIntegerTy())
1917 return nullptr;
1918
1919 // Get the element size and count.
1920 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1921 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1922 if (!SizeC || !CountC)
1923 return nullptr;
1924 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1925
1926 // If this is writing zero records, remove the call (it's a noop).
1927 if (Bytes == 0)
1928 return ConstantInt::get(CI->getType(), 0);
1929
1930 // If this is writing one byte, turn it into fputc.
1931 // This optimisation is only valid, if the return value is unused.
1932 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1933 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001934 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001935 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1936 }
1937
1938 return nullptr;
1939}
1940
1941Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1942 optimizeErrorReporting(CI, B, 1);
1943
1944 Function *Callee = CI->getCalledFunction();
1945
Chris Bienemanad070d02014-09-17 20:55:46 +00001946 // Require two pointers. Also, we can't optimize if return value is used.
1947 FunctionType *FT = Callee->getFunctionType();
1948 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1949 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1950 return nullptr;
1951
1952 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1953 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1954 if (!Len)
1955 return nullptr;
1956
1957 // Known to have no uses (see above).
1958 return EmitFWrite(
1959 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001960 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001961 CI->getArgOperand(1), B, DL, TLI);
1962}
1963
1964Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1965 Function *Callee = CI->getCalledFunction();
1966 // Require one fixed pointer argument and an integer/void result.
1967 FunctionType *FT = Callee->getFunctionType();
1968 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1969 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1970 return nullptr;
1971
1972 // Check for a constant string.
1973 StringRef Str;
1974 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1975 return nullptr;
1976
1977 if (Str.empty() && CI->use_empty()) {
1978 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001979 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001980 if (CI->use_empty() || !Res)
1981 return Res;
1982 return B.CreateIntCast(Res, CI->getType(), true);
1983 }
1984
1985 return nullptr;
1986}
1987
1988bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001989 LibFunc::Func Func;
1990 SmallString<20> FloatFuncName = FuncName;
1991 FloatFuncName += 'f';
1992 if (TLI->getLibFunc(FloatFuncName, Func))
1993 return TLI->has(Func);
1994 return false;
1995}
Meador Inge7fb2f732012-10-13 16:45:32 +00001996
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001997Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1998 IRBuilder<> &Builder) {
1999 LibFunc::Func Func;
2000 Function *Callee = CI->getCalledFunction();
2001 StringRef FuncName = Callee->getName();
2002
2003 // Check for string/memory library functions.
2004 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2005 // Make sure we never change the calling convention.
2006 assert((ignoreCallingConv(Func) ||
2007 CI->getCallingConv() == llvm::CallingConv::C) &&
2008 "Optimizing string/memory libcall would change the calling convention");
2009 switch (Func) {
2010 case LibFunc::strcat:
2011 return optimizeStrCat(CI, Builder);
2012 case LibFunc::strncat:
2013 return optimizeStrNCat(CI, Builder);
2014 case LibFunc::strchr:
2015 return optimizeStrChr(CI, Builder);
2016 case LibFunc::strrchr:
2017 return optimizeStrRChr(CI, Builder);
2018 case LibFunc::strcmp:
2019 return optimizeStrCmp(CI, Builder);
2020 case LibFunc::strncmp:
2021 return optimizeStrNCmp(CI, Builder);
2022 case LibFunc::strcpy:
2023 return optimizeStrCpy(CI, Builder);
2024 case LibFunc::stpcpy:
2025 return optimizeStpCpy(CI, Builder);
2026 case LibFunc::strncpy:
2027 return optimizeStrNCpy(CI, Builder);
2028 case LibFunc::strlen:
2029 return optimizeStrLen(CI, Builder);
2030 case LibFunc::strpbrk:
2031 return optimizeStrPBrk(CI, Builder);
2032 case LibFunc::strtol:
2033 case LibFunc::strtod:
2034 case LibFunc::strtof:
2035 case LibFunc::strtoul:
2036 case LibFunc::strtoll:
2037 case LibFunc::strtold:
2038 case LibFunc::strtoull:
2039 return optimizeStrTo(CI, Builder);
2040 case LibFunc::strspn:
2041 return optimizeStrSpn(CI, Builder);
2042 case LibFunc::strcspn:
2043 return optimizeStrCSpn(CI, Builder);
2044 case LibFunc::strstr:
2045 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002046 case LibFunc::memchr:
2047 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002048 case LibFunc::memcmp:
2049 return optimizeMemCmp(CI, Builder);
2050 case LibFunc::memcpy:
2051 return optimizeMemCpy(CI, Builder);
2052 case LibFunc::memmove:
2053 return optimizeMemMove(CI, Builder);
2054 case LibFunc::memset:
2055 return optimizeMemSet(CI, Builder);
2056 default:
2057 break;
2058 }
2059 }
2060 return nullptr;
2061}
2062
Chris Bienemanad070d02014-09-17 20:55:46 +00002063Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2064 if (CI->isNoBuiltin())
2065 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002066
Meador Inge20255ef2013-03-12 00:08:29 +00002067 LibFunc::Func Func;
2068 Function *Callee = CI->getCalledFunction();
2069 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002070 IRBuilder<> Builder(CI);
2071 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002072
Sanjay Patela92fa442014-10-22 15:29:23 +00002073 // Command-line parameter overrides function attribute.
2074 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2075 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002076 else if (canUseUnsafeFPMath(Callee))
2077 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002078
Sanjay Patel848309d2014-10-23 21:52:45 +00002079 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002080 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002081 if (!isCallingConvC)
2082 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002083 switch (II->getIntrinsicID()) {
2084 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002085 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002086 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002087 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002088 case Intrinsic::fabs:
2089 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002090 case Intrinsic::sqrt:
2091 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002092 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002093 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002094 }
2095 }
2096
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002097 // Also try to simplify calls to fortified library functions.
2098 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2099 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002100 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002101 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2102 // Use an IR Builder from SimplifiedCI if available instead of CI
2103 // to guarantee we reach all uses we might replace later on.
2104 IRBuilder<> TmpBuilder(SimplifiedCI);
2105 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002106 // If we were able to further simplify, remove the now redundant call.
2107 SimplifiedCI->replaceAllUsesWith(V);
2108 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002109 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002110 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002111 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002112 return SimplifiedFortifiedCI;
2113 }
2114
Meador Inge20255ef2013-03-12 00:08:29 +00002115 // Then check for known library functions.
2116 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002117 // We never change the calling convention.
2118 if (!ignoreCallingConv(Func) && !isCallingConvC)
2119 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002120 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2121 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002122 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002123 case LibFunc::cosf:
2124 case LibFunc::cos:
2125 case LibFunc::cosl:
2126 return optimizeCos(CI, Builder);
2127 case LibFunc::sinpif:
2128 case LibFunc::sinpi:
2129 case LibFunc::cospif:
2130 case LibFunc::cospi:
2131 return optimizeSinCosPi(CI, Builder);
2132 case LibFunc::powf:
2133 case LibFunc::pow:
2134 case LibFunc::powl:
2135 return optimizePow(CI, Builder);
2136 case LibFunc::exp2l:
2137 case LibFunc::exp2:
2138 case LibFunc::exp2f:
2139 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002140 case LibFunc::fabsf:
2141 case LibFunc::fabs:
2142 case LibFunc::fabsl:
2143 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002144 case LibFunc::sqrtf:
2145 case LibFunc::sqrt:
2146 case LibFunc::sqrtl:
2147 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002148 case LibFunc::ffs:
2149 case LibFunc::ffsl:
2150 case LibFunc::ffsll:
2151 return optimizeFFS(CI, Builder);
2152 case LibFunc::abs:
2153 case LibFunc::labs:
2154 case LibFunc::llabs:
2155 return optimizeAbs(CI, Builder);
2156 case LibFunc::isdigit:
2157 return optimizeIsDigit(CI, Builder);
2158 case LibFunc::isascii:
2159 return optimizeIsAscii(CI, Builder);
2160 case LibFunc::toascii:
2161 return optimizeToAscii(CI, Builder);
2162 case LibFunc::printf:
2163 return optimizePrintF(CI, Builder);
2164 case LibFunc::sprintf:
2165 return optimizeSPrintF(CI, Builder);
2166 case LibFunc::fprintf:
2167 return optimizeFPrintF(CI, Builder);
2168 case LibFunc::fwrite:
2169 return optimizeFWrite(CI, Builder);
2170 case LibFunc::fputs:
2171 return optimizeFPuts(CI, Builder);
2172 case LibFunc::puts:
2173 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002174 case LibFunc::tan:
2175 case LibFunc::tanf:
2176 case LibFunc::tanl:
2177 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002178 case LibFunc::perror:
2179 return optimizeErrorReporting(CI, Builder);
2180 case LibFunc::vfprintf:
2181 case LibFunc::fiprintf:
2182 return optimizeErrorReporting(CI, Builder, 0);
2183 case LibFunc::fputc:
2184 return optimizeErrorReporting(CI, Builder, 1);
2185 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002186 case LibFunc::floor:
2187 case LibFunc::rint:
2188 case LibFunc::round:
2189 case LibFunc::nearbyint:
2190 case LibFunc::trunc:
2191 if (hasFloatVersion(FuncName))
2192 return optimizeUnaryDoubleFP(CI, Builder, false);
2193 return nullptr;
2194 case LibFunc::acos:
2195 case LibFunc::acosh:
2196 case LibFunc::asin:
2197 case LibFunc::asinh:
2198 case LibFunc::atan:
2199 case LibFunc::atanh:
2200 case LibFunc::cbrt:
2201 case LibFunc::cosh:
2202 case LibFunc::exp:
2203 case LibFunc::exp10:
2204 case LibFunc::expm1:
2205 case LibFunc::log:
2206 case LibFunc::log10:
2207 case LibFunc::log1p:
2208 case LibFunc::log2:
2209 case LibFunc::logb:
2210 case LibFunc::sin:
2211 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002212 case LibFunc::tanh:
2213 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2214 return optimizeUnaryDoubleFP(CI, Builder, true);
2215 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002216 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002217 if (hasFloatVersion(FuncName))
2218 return optimizeBinaryDoubleFP(CI, Builder);
2219 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002220 case LibFunc::fminf:
2221 case LibFunc::fmin:
2222 case LibFunc::fminl:
2223 case LibFunc::fmaxf:
2224 case LibFunc::fmax:
2225 case LibFunc::fmaxl:
2226 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002227 default:
2228 return nullptr;
2229 }
Meador Inge20255ef2013-03-12 00:08:29 +00002230 }
Craig Topperf40110f2014-04-25 05:29:35 +00002231 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002232}
2233
Chandler Carruth92803822015-01-21 02:11:59 +00002234LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002235 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002236 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002237 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002238 Replacer(Replacer) {}
2239
2240void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2241 // Indirect through the replacer used in this instance.
2242 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002243}
2244
Meador Ingedfb08a22013-06-20 19:48:07 +00002245// TODO:
2246// Additional cases that we need to add to this file:
2247//
2248// cbrt:
2249// * cbrt(expN(X)) -> expN(x/3)
2250// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002251// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002252//
2253// exp, expf, expl:
2254// * exp(log(x)) -> x
2255//
2256// log, logf, logl:
2257// * log(exp(x)) -> x
2258// * log(x**y) -> y*log(x)
2259// * log(exp(y)) -> y*log(e)
2260// * log(exp2(y)) -> y*log(2)
2261// * log(exp10(y)) -> y*log(10)
2262// * log(sqrt(x)) -> 0.5*log(x)
2263// * log(pow(x,y)) -> y*log(x)
2264//
2265// lround, lroundf, lroundl:
2266// * lround(cnst) -> cnst'
2267//
2268// pow, powf, powl:
2269// * pow(exp(x),y) -> exp(x*y)
2270// * pow(sqrt(x),y) -> pow(x,y*0.5)
2271// * pow(pow(x,y),z)-> pow(x,y*z)
2272//
2273// round, roundf, roundl:
2274// * round(cnst) -> cnst'
2275//
2276// signbit:
2277// * signbit(cnst) -> cnst'
2278// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2279//
2280// sqrt, sqrtf, sqrtl:
2281// * sqrt(expN(x)) -> expN(x*0.5)
2282// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2283// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2284//
Meador Ingedfb08a22013-06-20 19:48:07 +00002285// tan, tanf, tanl:
2286// * tan(atan(x)) -> x
2287//
2288// trunc, truncf, truncl:
2289// * trunc(cnst) -> cnst'
2290//
2291//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002292
2293//===----------------------------------------------------------------------===//
2294// Fortified Library Call Optimizations
2295//===----------------------------------------------------------------------===//
2296
2297bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2298 unsigned ObjSizeOp,
2299 unsigned SizeOp,
2300 bool isString) {
2301 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2302 return true;
2303 if (ConstantInt *ObjSizeCI =
2304 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2305 if (ObjSizeCI->isAllOnesValue())
2306 return true;
2307 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2308 if (OnlyLowerUnknownSize)
2309 return false;
2310 if (isString) {
2311 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2312 // If the length is 0 we don't know how long it is and so we can't
2313 // remove the check.
2314 if (Len == 0)
2315 return false;
2316 return ObjSizeCI->getZExtValue() >= Len;
2317 }
2318 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2319 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2320 }
2321 return false;
2322}
2323
2324Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2325 Function *Callee = CI->getCalledFunction();
2326
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002327 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002328 return nullptr;
2329
2330 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2331 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2332 CI->getArgOperand(2), 1);
2333 return CI->getArgOperand(0);
2334 }
2335 return nullptr;
2336}
2337
2338Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2339 Function *Callee = CI->getCalledFunction();
2340
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002341 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002342 return nullptr;
2343
2344 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2345 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
2346 CI->getArgOperand(2), 1);
2347 return CI->getArgOperand(0);
2348 }
2349 return nullptr;
2350}
2351
2352Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2353 Function *Callee = CI->getCalledFunction();
2354
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002355 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002356 return nullptr;
2357
2358 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2359 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2360 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2361 return CI->getArgOperand(0);
2362 }
2363 return nullptr;
2364}
2365
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002366Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2367 IRBuilder<> &B,
2368 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002369 Function *Callee = CI->getCalledFunction();
2370 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002371 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002372
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002373 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002374 return nullptr;
2375
2376 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2377 *ObjSize = CI->getArgOperand(2);
2378
2379 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002380 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002381 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002382 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002383 }
2384
2385 // If a) we don't have any length information, or b) we know this will
2386 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2387 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2388 // TODO: It might be nice to get a maximum length out of the possible
2389 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002390 if (isFortifiedCallFoldable(CI, 2, 1, true))
2391 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002392
David Blaikie65fab6d2015-04-03 21:32:06 +00002393 if (OnlyLowerUnknownSize)
2394 return nullptr;
2395
2396 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2397 uint64_t Len = GetStringLength(Src);
2398 if (Len == 0)
2399 return nullptr;
2400
2401 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2402 Value *LenV = ConstantInt::get(SizeTTy, Len);
2403 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2404 // If the function was an __stpcpy_chk, and we were able to fold it into
2405 // a __memcpy_chk, we still need to return the correct end pointer.
2406 if (Ret && Func == LibFunc::stpcpy_chk)
2407 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2408 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002409}
2410
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002411Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2412 IRBuilder<> &B,
2413 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414 Function *Callee = CI->getCalledFunction();
2415 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002417 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002418 return nullptr;
2419 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002420 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2421 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002422 return Ret;
2423 }
2424 return nullptr;
2425}
2426
2427Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002428 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2429 // Some clang users checked for _chk libcall availability using:
2430 // __has_builtin(__builtin___memcpy_chk)
2431 // When compiling with -fno-builtin, this is always true.
2432 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2433 // end up with fortified libcalls, which isn't acceptable in a freestanding
2434 // environment which only provides their non-fortified counterparts.
2435 //
2436 // Until we change clang and/or teach external users to check for availability
2437 // differently, disregard the "nobuiltin" attribute and TLI::has.
2438 //
2439 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002440
2441 LibFunc::Func Func;
2442 Function *Callee = CI->getCalledFunction();
2443 StringRef FuncName = Callee->getName();
2444 IRBuilder<> Builder(CI);
2445 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2446
2447 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002448 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002449 return nullptr;
2450
2451 // We never change the calling convention.
2452 if (!ignoreCallingConv(Func) && !isCallingConvC)
2453 return nullptr;
2454
2455 switch (Func) {
2456 case LibFunc::memcpy_chk:
2457 return optimizeMemCpyChk(CI, Builder);
2458 case LibFunc::memmove_chk:
2459 return optimizeMemMoveChk(CI, Builder);
2460 case LibFunc::memset_chk:
2461 return optimizeMemSetChk(CI, Builder);
2462 case LibFunc::stpcpy_chk:
2463 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002464 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002465 case LibFunc::stpncpy_chk:
2466 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002467 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002468 default:
2469 break;
2470 }
2471 return nullptr;
2472}
2473
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002474FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2475 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2476 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}