blob: 956bd08d852a1c6fa8f712b90bb91562b843f8c4 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000031#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000034#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000040 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
41 cl::init(false),
42 cl::desc("Enable unsafe double to float "
43 "shrinking for math lib calls"));
44
45
Meador Ingedf796f82012-10-13 16:45:24 +000046//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000047// Helper Functions
48//===----------------------------------------------------------------------===//
49
David L. Jonesd21529f2017-01-23 23:16:46 +000050static bool ignoreCallingConv(LibFunc Func) {
51 return Func == LibFunc_abs || Func == LibFunc_labs ||
52 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000053}
54
Sam Parker214f7bf2016-09-13 12:10:14 +000055static bool isCallingConvCCompatible(CallInst *CI) {
56 switch(CI->getCallingConv()) {
57 default:
58 return false;
59 case llvm::CallingConv::C:
60 return true;
61 case llvm::CallingConv::ARM_APCS:
62 case llvm::CallingConv::ARM_AAPCS:
63 case llvm::CallingConv::ARM_AAPCS_VFP: {
64
65 // The iOS ABI diverges from the standard in some cases, so for now don't
66 // try to simplify those calls.
67 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
68 return false;
69
70 auto *FuncTy = CI->getFunctionType();
71
72 if (!FuncTy->getReturnType()->isPointerTy() &&
73 !FuncTy->getReturnType()->isIntegerTy() &&
74 !FuncTy->getReturnType()->isVoidTy())
75 return false;
76
77 for (auto Param : FuncTy->params()) {
78 if (!Param->isPointerTy() && !Param->isIntegerTy())
79 return false;
80 }
81 return true;
82 }
83 }
84 return false;
85}
86
Sanjay Pateld707db92015-12-31 16:10:49 +000087/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000088static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000089 for (User *U : V->users()) {
90 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000091 if (IC->isEquality())
92 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
93 if (C->isNullValue())
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Sanjay Pateld707db92015-12-31 16:10:49 +0000101/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +0000102static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000103 for (User *U : V->users()) {
104 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +0000105 if (IC->isEquality() && IC->getOperand(1) == With)
106 continue;
107 // Unknown instruction.
108 return false;
109 }
110 return true;
111}
112
Meador Inge08ca1152012-11-26 20:37:20 +0000113static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000114 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000115 return OI->getType()->isFloatingPointTy();
116 });
Meador Inge08ca1152012-11-26 20:37:20 +0000117}
118
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000119/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000120/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000121static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000122 LibFunc DoubleFn, LibFunc FloatFn,
123 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000124 switch (Ty->getTypeID()) {
125 case Type::FloatTyID:
126 return TLI->has(FloatFn);
127 case Type::DoubleTyID:
128 return TLI->has(DoubleFn);
129 default:
130 return TLI->has(LongDoubleFn);
131 }
132}
133
Meador Inged589ac62012-10-31 03:33:06 +0000134//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000135// String and Memory Library Call Optimizations
136//===----------------------------------------------------------------------===//
137
Chris Bienemanad070d02014-09-17 20:55:46 +0000138Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000139 // Extract some information from the instruction
140 Value *Dst = CI->getArgOperand(0);
141 Value *Src = CI->getArgOperand(1);
142
143 // See if we can get the length of the input string.
144 uint64_t Len = GetStringLength(Src);
145 if (Len == 0)
146 return nullptr;
147 --Len; // Unbias length.
148
149 // Handle the simple, do-nothing case: strcat(x, "") -> x
150 if (Len == 0)
151 return Dst;
152
Chris Bienemanad070d02014-09-17 20:55:46 +0000153 return emitStrLenMemCpy(Src, Dst, Len, B);
154}
155
156Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
157 IRBuilder<> &B) {
158 // We need to find the end of the destination string. That's where the
159 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000160 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000161 if (!DstLen)
162 return nullptr;
163
164 // Now that we have the destination's length, we must index into the
165 // destination's pointer to get the actual memcpy destination (end of
166 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000167 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000168
169 // We have enough information to now generate the memcpy call to do the
170 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171 B.CreateMemCpy(CpyDst, Src,
172 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000173 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000174 return Dst;
175}
176
177Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000178 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000179 Value *Dst = CI->getArgOperand(0);
180 Value *Src = CI->getArgOperand(1);
181 uint64_t Len;
182
Sanjay Pateld707db92015-12-31 16:10:49 +0000183 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000184 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
185 Len = LengthArg->getZExtValue();
186 else
187 return nullptr;
188
189 // See if we can get the length of the input string.
190 uint64_t SrcLen = GetStringLength(Src);
191 if (SrcLen == 0)
192 return nullptr;
193 --SrcLen; // Unbias length.
194
195 // Handle the simple, do-nothing cases:
196 // strncat(x, "", c) -> x
197 // strncat(x, c, 0) -> x
198 if (SrcLen == 0 || Len == 0)
199 return Dst;
200
Sanjay Pateld707db92015-12-31 16:10:49 +0000201 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000202 if (Len < SrcLen)
203 return nullptr;
204
205 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000206 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
208}
209
210Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
211 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000212 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000213 Value *SrcStr = CI->getArgOperand(0);
214
215 // If the second operand is non-constant, see if we can compute the length
216 // of the input string and turn this into memchr.
217 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
218 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000219 uint64_t Len = GetStringLength(SrcStr);
220 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
221 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000222
Sanjay Pateld3112a52016-01-19 19:46:10 +0000223 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
225 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000226 }
227
Chris Bienemanad070d02014-09-17 20:55:46 +0000228 // Otherwise, the character is a constant, see if the first argument is
229 // a string literal. If so, we can constant fold.
230 StringRef Str;
231 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000233 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000234 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000235 return nullptr;
236 }
237
238 // Compute the offset, make sure to handle the case when we're searching for
239 // zero (a weird way to spell strlen).
240 size_t I = (0xFF & CharC->getSExtValue()) == 0
241 ? Str.size()
242 : Str.find(CharC->getSExtValue());
243 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
244 return Constant::getNullValue(CI->getType());
245
246 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000247 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000248}
249
250Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000251 Value *SrcStr = CI->getArgOperand(0);
252 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
253
254 // Cannot fold anything if we're not looking for a constant.
255 if (!CharC)
256 return nullptr;
257
258 StringRef Str;
259 if (!getConstantStringInfo(SrcStr, Str)) {
260 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000261 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000262 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000263 return nullptr;
264 }
265
266 // Compute the offset.
267 size_t I = (0xFF & CharC->getSExtValue()) == 0
268 ? Str.size()
269 : Str.rfind(CharC->getSExtValue());
270 if (I == StringRef::npos) // Didn't find the char. Return null.
271 return Constant::getNullValue(CI->getType());
272
273 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000274 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000275}
276
277Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000278 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
279 if (Str1P == Str2P) // strcmp(x,x) -> 0
280 return ConstantInt::get(CI->getType(), 0);
281
282 StringRef Str1, Str2;
283 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
284 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
285
286 // strcmp(x, y) -> cnst (if both x and y are constant strings)
287 if (HasStr1 && HasStr2)
288 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
289
290 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
291 return B.CreateNeg(
292 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
293
294 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
295 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
296
297 // strcmp(P, "x") -> memcmp(P, "x", 2)
298 uint64_t Len1 = GetStringLength(Str1P);
299 uint64_t Len2 = GetStringLength(Str2P);
300 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000301 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000302 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000303 std::min(Len1, Len2)),
304 B, DL, TLI);
305 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000306
Chris Bienemanad070d02014-09-17 20:55:46 +0000307 return nullptr;
308}
309
310Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000311 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
312 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
313 return ConstantInt::get(CI->getType(), 0);
314
315 // Get the length argument if it is constant.
316 uint64_t Length;
317 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
318 Length = LengthArg->getZExtValue();
319 else
320 return nullptr;
321
322 if (Length == 0) // strncmp(x,y,0) -> 0
323 return ConstantInt::get(CI->getType(), 0);
324
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000326 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000327
328 StringRef Str1, Str2;
329 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
330 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
331
332 // strncmp(x, y) -> cnst (if both x and y are constant strings)
333 if (HasStr1 && HasStr2) {
334 StringRef SubStr1 = Str1.substr(0, Length);
335 StringRef SubStr2 = Str2.substr(0, Length);
336 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
337 }
338
339 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
340 return B.CreateNeg(
341 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
342
343 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
344 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
345
346 return nullptr;
347}
348
349Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000350 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
351 if (Dst == Src) // strcpy(x,x) -> x
352 return Src;
353
Chris Bienemanad070d02014-09-17 20:55:46 +0000354 // See if we can get the length of the input string.
355 uint64_t Len = GetStringLength(Src);
356 if (Len == 0)
357 return nullptr;
358
359 // We have enough information to now generate the memcpy call to do the
360 // copy for us. Make a memcpy to copy the nul byte with align = 1.
361 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000362 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000363 return Dst;
364}
365
366Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
367 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
369 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000370 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000371 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000372 }
373
374 // See if we can get the length of the input string.
375 uint64_t Len = GetStringLength(Src);
376 if (Len == 0)
377 return nullptr;
378
Davide Italianob7487e62015-11-02 23:07:14 +0000379 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000381 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
382 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000383
384 // We have enough information to now generate the memcpy call to do the
385 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000386 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000387 return DstEnd;
388}
389
390Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
391 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000392 Value *Dst = CI->getArgOperand(0);
393 Value *Src = CI->getArgOperand(1);
394 Value *LenOp = CI->getArgOperand(2);
395
396 // See if we can get the length of the input string.
397 uint64_t SrcLen = GetStringLength(Src);
398 if (SrcLen == 0)
399 return nullptr;
400 --SrcLen;
401
402 if (SrcLen == 0) {
403 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
404 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000405 return Dst;
406 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000407
Chris Bienemanad070d02014-09-17 20:55:46 +0000408 uint64_t Len;
409 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
410 Len = LengthArg->getZExtValue();
411 else
412 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000413
Chris Bienemanad070d02014-09-17 20:55:46 +0000414 if (Len == 0)
415 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000416
Chris Bienemanad070d02014-09-17 20:55:46 +0000417 // Let strncpy handle the zero padding
418 if (Len > SrcLen + 1)
419 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000420
Davide Italianob7487e62015-11-02 23:07:14 +0000421 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000422 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000423 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000424
Chris Bienemanad070d02014-09-17 20:55:46 +0000425 return Dst;
426}
Meador Inge7fb2f732012-10-13 16:45:32 +0000427
Chris Bienemanad070d02014-09-17 20:55:46 +0000428Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000429 Value *Src = CI->getArgOperand(0);
430
431 // Constant folding: strlen("xyz") -> 3
432 if (uint64_t Len = GetStringLength(Src))
433 return ConstantInt::get(CI->getType(), Len - 1);
434
David L Kreitzer752c1442016-04-13 14:31:06 +0000435 // If s is a constant pointer pointing to a string literal, we can fold
436 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
437 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
438 // We only try to simplify strlen when the pointer s points to an array
439 // of i8. Otherwise, we would need to scale the offset x before doing the
440 // subtraction. This will make the optimization more complex, and it's not
441 // very useful because calling strlen for a pointer of other types is
442 // very uncommon.
443 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
444 if (!isGEPBasedOnPointerToString(GEP))
445 return nullptr;
446
447 StringRef Str;
448 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
449 size_t NullTermIdx = Str.find('\0');
450
451 // If the string does not have '\0', leave it to strlen to compute
452 // its length.
453 if (NullTermIdx == StringRef::npos)
454 return nullptr;
455
456 Value *Offset = GEP->getOperand(2);
457 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
458 APInt KnownZero(BitWidth, 0);
459 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000460 computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
461 nullptr);
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 KnownZero.flipAllBits();
463 size_t ArrSize =
464 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
465
466 // KnownZero's bits are flipped, so zeros in KnownZero now represent
467 // bits known to be zeros in Offset, and ones in KnowZero represent
468 // bits unknown in Offset. Therefore, Offset is known to be in range
469 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
470 // unsigned-less-than NullTermIdx.
471 //
472 // If Offset is not provably in the range [0, NullTermIdx], we can still
473 // optimize if we can prove that the program has undefined behavior when
474 // Offset is outside that range. That is the case when GEP->getOperand(0)
475 // is a pointer to an object whose memory extent is NullTermIdx+1.
476 if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
477 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
478 NullTermIdx == ArrSize - 1))
479 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
480 Offset);
481 }
482
483 return nullptr;
484 }
485
Chris Bienemanad070d02014-09-17 20:55:46 +0000486 // strlen(x?"foo":"bars") --> x ? 3 : 4
487 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
488 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
489 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
490 if (LenTrue && LenFalse) {
491 Function *Caller = CI->getParent()->getParent();
492 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
493 SI->getDebugLoc(),
494 "folded strlen(select) to select of constants");
495 return B.CreateSelect(SI->getCondition(),
496 ConstantInt::get(CI->getType(), LenTrue - 1),
497 ConstantInt::get(CI->getType(), LenFalse - 1));
498 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000499 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000500
Chris Bienemanad070d02014-09-17 20:55:46 +0000501 // strlen(x) != 0 --> *x != 0
502 // strlen(x) == 0 --> *x == 0
503 if (isOnlyUsedInZeroEqualityComparison(CI))
504 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000505
Chris Bienemanad070d02014-09-17 20:55:46 +0000506 return nullptr;
507}
Meador Inge17418502012-10-13 16:45:37 +0000508
Chris Bienemanad070d02014-09-17 20:55:46 +0000509Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000510 StringRef S1, S2;
511 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
512 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000513
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000514 // strpbrk(s, "") -> nullptr
515 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
517 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000518
Chris Bienemanad070d02014-09-17 20:55:46 +0000519 // Constant folding.
520 if (HasS1 && HasS2) {
521 size_t I = S1.find_first_of(S2);
522 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000523 return Constant::getNullValue(CI->getType());
524
Sanjay Pateld707db92015-12-31 16:10:49 +0000525 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
526 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000527 }
Meador Inge17418502012-10-13 16:45:37 +0000528
Chris Bienemanad070d02014-09-17 20:55:46 +0000529 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000530 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000531 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000532
533 return nullptr;
534}
535
536Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000537 Value *EndPtr = CI->getArgOperand(1);
538 if (isa<ConstantPointerNull>(EndPtr)) {
539 // With a null EndPtr, this function won't capture the main argument.
540 // It would be readonly too, except that it still may write to errno.
541 CI->addAttribute(1, Attribute::NoCapture);
542 }
543
544 return nullptr;
545}
546
547Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 StringRef S1, S2;
549 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
550 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
551
552 // strspn(s, "") -> 0
553 // strspn("", s) -> 0
554 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
555 return Constant::getNullValue(CI->getType());
556
557 // Constant folding.
558 if (HasS1 && HasS2) {
559 size_t Pos = S1.find_first_not_of(S2);
560 if (Pos == StringRef::npos)
561 Pos = S1.size();
562 return ConstantInt::get(CI->getType(), Pos);
563 }
564
565 return nullptr;
566}
567
568Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000569 StringRef S1, S2;
570 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
571 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
572
573 // strcspn("", s) -> 0
574 if (HasS1 && S1.empty())
575 return Constant::getNullValue(CI->getType());
576
577 // Constant folding.
578 if (HasS1 && HasS2) {
579 size_t Pos = S1.find_first_of(S2);
580 if (Pos == StringRef::npos)
581 Pos = S1.size();
582 return ConstantInt::get(CI->getType(), Pos);
583 }
584
585 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000587 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000588
589 return nullptr;
590}
591
592Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000593 // fold strstr(x, x) -> x.
594 if (CI->getArgOperand(0) == CI->getArgOperand(1))
595 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
596
597 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000598 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000599 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000600 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000601 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000602 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000603 StrLen, B, DL, TLI);
604 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000605 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
607 ICmpInst *Old = cast<ICmpInst>(*UI++);
608 Value *Cmp =
609 B.CreateICmp(Old->getPredicate(), StrNCmp,
610 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
611 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000612 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000613 return CI;
614 }
Meador Inge17418502012-10-13 16:45:37 +0000615
Chris Bienemanad070d02014-09-17 20:55:46 +0000616 // See if either input string is a constant string.
617 StringRef SearchStr, ToFindStr;
618 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
619 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
620
621 // fold strstr(x, "") -> x.
622 if (HasStr2 && ToFindStr.empty())
623 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
624
625 // If both strings are known, constant fold it.
626 if (HasStr1 && HasStr2) {
627 size_t Offset = SearchStr.find(ToFindStr);
628
629 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000630 return Constant::getNullValue(CI->getType());
631
Chris Bienemanad070d02014-09-17 20:55:46 +0000632 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000633 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
635 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000636 }
Meador Inge17418502012-10-13 16:45:37 +0000637
Chris Bienemanad070d02014-09-17 20:55:46 +0000638 // fold strstr(x, "y") -> strchr(x, 'y').
639 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000640 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
642 }
643 return nullptr;
644}
Meador Inge40b6fac2012-10-15 03:47:37 +0000645
Benjamin Kramer691363e2015-03-21 15:36:21 +0000646Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000647 Value *SrcStr = CI->getArgOperand(0);
648 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
649 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
650
651 // memchr(x, y, 0) -> null
652 if (LenC && LenC->isNullValue())
653 return Constant::getNullValue(CI->getType());
654
Benjamin Kramer7857d722015-03-21 21:09:33 +0000655 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000656 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000657 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000658 return nullptr;
659
660 // Truncate the string to LenC. If Str is smaller than LenC we will still only
661 // scan the string, as reading past the end of it is undefined and we can just
662 // return null if we don't find the char.
663 Str = Str.substr(0, LenC->getZExtValue());
664
Benjamin Kramer7857d722015-03-21 21:09:33 +0000665 // If the char is variable but the input str and length are not we can turn
666 // this memchr call into a simple bit field test. Of course this only works
667 // when the return value is only checked against null.
668 //
669 // It would be really nice to reuse switch lowering here but we can't change
670 // the CFG at this point.
671 //
672 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
673 // after bounds check.
674 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000675 unsigned char Max =
676 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
677 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000678
679 // Make sure the bit field we're about to create fits in a register on the
680 // target.
681 // FIXME: On a 64 bit architecture this prevents us from using the
682 // interesting range of alpha ascii chars. We could do better by emitting
683 // two bitfields or shifting the range by 64 if no lower chars are used.
684 if (!DL.fitsInLegalInteger(Max + 1))
685 return nullptr;
686
687 // For the bit field use a power-of-2 type with at least 8 bits to avoid
688 // creating unnecessary illegal types.
689 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
690
691 // Now build the bit field.
692 APInt Bitfield(Width, 0);
693 for (char C : Str)
694 Bitfield.setBit((unsigned char)C);
695 Value *BitfieldC = B.getInt(Bitfield);
696
697 // First check that the bit field access is within bounds.
698 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
699 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
700 "memchr.bounds");
701
702 // Create code that checks if the given bit is set in the field.
703 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
704 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
705
706 // Finally merge both checks and cast to pointer type. The inttoptr
707 // implicitly zexts the i1 to intptr type.
708 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
709 }
710
711 // Check if all arguments are constants. If so, we can constant fold.
712 if (!CharC)
713 return nullptr;
714
Benjamin Kramer691363e2015-03-21 15:36:21 +0000715 // Compute the offset.
716 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
717 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
718 return Constant::getNullValue(CI->getType());
719
720 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000721 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000722}
723
Chris Bienemanad070d02014-09-17 20:55:46 +0000724Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000725 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000726
Chris Bienemanad070d02014-09-17 20:55:46 +0000727 if (LHS == RHS) // memcmp(s,s,x) -> 0
728 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000729
Chris Bienemanad070d02014-09-17 20:55:46 +0000730 // Make sure we have a constant length.
731 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
732 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000733 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 uint64_t Len = LenC->getZExtValue();
735
736 if (Len == 0) // memcmp(s1,s2,0) -> 0
737 return Constant::getNullValue(CI->getType());
738
739 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
740 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000741 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000743 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000744 CI->getType(), "rhsv");
745 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000746 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000747
Chad Rosierdc655322015-08-28 18:30:18 +0000748 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
749 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
750
751 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
752 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
753
754 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
755 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
756
757 Type *LHSPtrTy =
758 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
759 Type *RHSPtrTy =
760 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
761
Sanjay Pateld707db92015-12-31 16:10:49 +0000762 Value *LHSV =
763 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
764 Value *RHSV =
765 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000766
767 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
768 }
769 }
770
Chris Bienemanad070d02014-09-17 20:55:46 +0000771 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
772 StringRef LHSStr, RHSStr;
773 if (getConstantStringInfo(LHS, LHSStr) &&
774 getConstantStringInfo(RHS, RHSStr)) {
775 // Make sure we're not reading out-of-bounds memory.
776 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000777 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000778 // Fold the memcmp and normalize the result. This way we get consistent
779 // results across multiple platforms.
780 uint64_t Ret = 0;
781 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
782 if (Cmp < 0)
783 Ret = -1;
784 else if (Cmp > 0)
785 Ret = 1;
786 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000787 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000788
Chris Bienemanad070d02014-09-17 20:55:46 +0000789 return nullptr;
790}
Meador Inge9a6a1902012-10-31 00:20:56 +0000791
Chris Bienemanad070d02014-09-17 20:55:46 +0000792Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000793 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
794 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000795 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000796 return CI->getArgOperand(0);
797}
Meador Inge05a625a2012-10-31 14:58:26 +0000798
Chris Bienemanad070d02014-09-17 20:55:46 +0000799Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000800 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
801 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000802 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000803 return CI->getArgOperand(0);
804}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000805
Sanjay Patel980b2802016-01-26 16:17:24 +0000806// TODO: Does this belong in BuildLibCalls or should all of those similar
807// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000808static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000809 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000810 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000811 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
812 return nullptr;
813
814 Module *M = B.GetInsertBlock()->getModule();
815 const DataLayout &DL = M->getDataLayout();
816 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
817 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000818 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000819 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
820
821 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
822 CI->setCallingConv(F->getCallingConv());
823
824 return CI;
825}
826
827/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
828static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
829 const TargetLibraryInfo &TLI) {
830 // This has to be a memset of zeros (bzero).
831 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
832 if (!FillValue || FillValue->getZExtValue() != 0)
833 return nullptr;
834
835 // TODO: We should handle the case where the malloc has more than one use.
836 // This is necessary to optimize common patterns such as when the result of
837 // the malloc is checked against null or when a memset intrinsic is used in
838 // place of a memset library call.
839 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
840 if (!Malloc || !Malloc->hasOneUse())
841 return nullptr;
842
843 // Is the inner call really malloc()?
844 Function *InnerCallee = Malloc->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +0000845 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000846 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000847 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000848 return nullptr;
849
Sanjay Patel980b2802016-01-26 16:17:24 +0000850 // The memset must cover the same number of bytes that are malloc'd.
851 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
852 return nullptr;
853
854 // Replace the malloc with a calloc. We need the data layout to know what the
855 // actual size of a 'size_t' parameter is.
856 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
857 const DataLayout &DL = Malloc->getModule()->getDataLayout();
858 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
859 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
860 Malloc->getArgOperand(0), Malloc->getAttributes(),
861 B, TLI);
862 if (!Calloc)
863 return nullptr;
864
865 Malloc->replaceAllUsesWith(Calloc);
866 Malloc->eraseFromParent();
867
868 return Calloc;
869}
870
Chris Bienemanad070d02014-09-17 20:55:46 +0000871Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000872 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
873 return Calloc;
874
Chris Bienemanad070d02014-09-17 20:55:46 +0000875 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
876 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
877 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
878 return CI->getArgOperand(0);
879}
Meador Inged4825782012-11-11 06:49:03 +0000880
Meador Inge193e0352012-11-13 04:16:17 +0000881//===----------------------------------------------------------------------===//
882// Math Library Optimizations
883//===----------------------------------------------------------------------===//
884
Matthias Braund34e4d22014-12-03 21:46:33 +0000885/// Return a variant of Val with float type.
886/// Currently this works in two cases: If Val is an FPExtension of a float
887/// value to something bigger, simply return the operand.
888/// If Val is a ConstantFP but can be converted to a float ConstantFP without
889/// loss of precision do so.
890static Value *valueHasFloatPrecision(Value *Val) {
891 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
892 Value *Op = Cast->getOperand(0);
893 if (Op->getType()->isFloatTy())
894 return Op;
895 }
896 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
897 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000898 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000899 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000900 &losesInfo);
901 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000902 return ConstantFP::get(Const->getContext(), F);
903 }
904 return nullptr;
905}
906
Sanjay Patel4e971da2016-01-21 18:01:57 +0000907/// Shrink double -> float for unary functions like 'floor'.
908static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
909 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000910 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000911 // We know this libcall has a valid prototype, but we don't know which.
912 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000913 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000914
Chris Bienemanad070d02014-09-17 20:55:46 +0000915 if (CheckRetType) {
916 // Check if all the uses for function like 'sin' are converted to float.
917 for (User *U : CI->users()) {
918 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
919 if (!Cast || !Cast->getType()->isFloatTy())
920 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000921 }
Meador Inge193e0352012-11-13 04:16:17 +0000922 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000923
924 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000925 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
926 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000927 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000928
929 // Propagate fast-math flags from the existing call to the new call.
930 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000931 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000932
933 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000934 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000935 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000936 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000937 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
938 V = B.CreateCall(F, V);
939 } else {
940 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000941 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000942 }
943
Chris Bienemanad070d02014-09-17 20:55:46 +0000944 return B.CreateFPExt(V, B.getDoubleTy());
945}
Meador Inge193e0352012-11-13 04:16:17 +0000946
Matt Arsenault954a6242017-01-23 23:55:08 +0000947// Replace a libcall \p CI with a call to intrinsic \p IID
948static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
949 // Propagate fast-math flags from the existing call to the new call.
950 IRBuilder<>::FastMathFlagGuard Guard(B);
951 B.setFastMathFlags(CI->getFastMathFlags());
952
953 Module *M = CI->getModule();
954 Value *V = CI->getArgOperand(0);
955 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
956 CallInst *NewCall = B.CreateCall(F, V);
957 NewCall->takeName(CI);
958 return NewCall;
959}
960
Sanjay Patel4e971da2016-01-21 18:01:57 +0000961/// Shrink double -> float for binary functions like 'fmin/fmax'.
962static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000963 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000964 // We know this libcall has a valid prototype, but we don't know which.
965 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000966 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000967
Chris Bienemanad070d02014-09-17 20:55:46 +0000968 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000969 // or fmin(1.0, (double)floatval), then we convert it to fminf.
970 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
971 if (V1 == nullptr)
972 return nullptr;
973 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
974 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000975 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000976
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000977 // Propagate fast-math flags from the existing call to the new call.
978 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000979 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000980
Chris Bienemanad070d02014-09-17 20:55:46 +0000981 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +0000982 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +0000983 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +0000984 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +0000985 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000986 return B.CreateFPExt(V, B.getDoubleTy());
987}
988
989Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
990 Function *Callee = CI->getCalledFunction();
991 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +0000992 StringRef Name = Callee->getName();
993 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +0000994 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +0000995
Chris Bienemanad070d02014-09-17 20:55:46 +0000996 // cos(-x) -> cos(x)
997 Value *Op1 = CI->getArgOperand(0);
998 if (BinaryOperator::isFNeg(Op1)) {
999 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1000 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1001 }
1002 return Ret;
1003}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001004
Weiming Zhao82130722015-12-04 22:00:47 +00001005static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1006 // Multiplications calculated using Addition Chains.
1007 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1008
1009 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1010
1011 if (InnerChain[Exp])
1012 return InnerChain[Exp];
1013
1014 static const unsigned AddChain[33][2] = {
1015 {0, 0}, // Unused.
1016 {0, 0}, // Unused (base case = pow1).
1017 {1, 1}, // Unused (pre-computed).
1018 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1019 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1020 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1021 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1022 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1023 };
1024
1025 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1026 getPow(InnerChain, AddChain[Exp][1], B));
1027 return InnerChain[Exp];
1028}
1029
Chris Bienemanad070d02014-09-17 20:55:46 +00001030Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1031 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001032 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001033 StringRef Name = Callee->getName();
1034 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001035 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001036
Chris Bienemanad070d02014-09-17 20:55:46 +00001037 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001038
1039 // pow(1.0, x) -> 1.0
1040 if (match(Op1, m_SpecificFP(1.0)))
1041 return Op1;
1042 // pow(2.0, x) -> llvm.exp2(x)
1043 if (match(Op1, m_SpecificFP(2.0))) {
1044 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1045 CI->getType());
1046 return B.CreateCall(Exp2, Op2, "exp2");
1047 }
1048
1049 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1050 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001051 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001052 // pow(10.0, x) -> exp10(x)
1053 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001054 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1055 LibFunc_exp10l))
1056 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001057 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001058 }
1059
Sanjay Patel6002e782016-01-12 17:30:37 +00001060 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001061 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001062 // We enable these only with fast-math. Besides rounding differences, the
1063 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001064 // Example: x = 1000, y = 0.001.
1065 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001066 auto *OpC = dyn_cast<CallInst>(Op1);
1067 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001068 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001069 Function *OpCCallee = OpC->getCalledFunction();
1070 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001071 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001072 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001073 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001074 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001075 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001076 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001077 }
1078 }
1079
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1081 if (!Op2C)
1082 return Ret;
1083
1084 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1085 return ConstantFP::get(CI->getType(), 1.0);
1086
Davide Italiano472684e2017-01-09 21:55:23 +00001087 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001088 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1089 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001090 // If -ffast-math:
1091 // pow(x, -0.5) -> 1.0 / sqrt(x)
1092 if (CI->hasUnsafeAlgebra()) {
1093 IRBuilder<>::FastMathFlagGuard Guard(B);
1094 B.setFastMathFlags(CI->getFastMathFlags());
1095
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001096 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1097 // intrinsic, so we match errno semantics. We also should check that the
1098 // target can in fact lower the sqrt intrinsic -- we currently have no way
1099 // to ask this question other than asking whether the target has a sqrt
1100 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001101 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001102 Callee->getAttributes());
1103
1104 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1105 }
1106 }
1107
Chris Bienemanad070d02014-09-17 20:55:46 +00001108 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001109 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1110 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001111
1112 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001113 if (CI->hasUnsafeAlgebra()) {
1114 IRBuilder<>::FastMathFlagGuard Guard(B);
1115 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001116
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001117 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1118 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001119 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001120 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001121 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001122
Chris Bienemanad070d02014-09-17 20:55:46 +00001123 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1124 // This is faster than calling pow, and still handles negative zero
1125 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001126 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1127 Value *Inf = ConstantFP::getInfinity(CI->getType());
1128 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001129
1130 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1131 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001132 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001133
1134 Module *M = Callee->getParent();
1135 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1136 CI->getType());
1137 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1138
Chris Bienemanad070d02014-09-17 20:55:46 +00001139 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1140 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1141 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001142 }
1143
Chris Bienemanad070d02014-09-17 20:55:46 +00001144 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1145 return Op1;
1146 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1147 return B.CreateFMul(Op1, Op1, "pow2");
1148 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1149 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001150
1151 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001152 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001153 APFloat V = abs(Op2C->getValueAPF());
1154 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1155 // This transformation applies to integer exponents only.
1156 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1157 !V.isInteger())
1158 return nullptr;
1159
Davide Italianof8711f02017-01-10 18:02:05 +00001160 // Propagate fast math flags.
1161 IRBuilder<>::FastMathFlagGuard Guard(B);
1162 B.setFastMathFlags(CI->getFastMathFlags());
1163
Weiming Zhao82130722015-12-04 22:00:47 +00001164 // We will memoize intermediate products of the Addition Chain.
1165 Value *InnerChain[33] = {nullptr};
1166 InnerChain[1] = Op1;
1167 InnerChain[2] = B.CreateFMul(Op1, Op1);
1168
1169 // We cannot readily convert a non-double type (like float) to a double.
1170 // So we first convert V to something which could be converted to double.
1171 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001172 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001173
Weiming Zhao82130722015-12-04 22:00:47 +00001174 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1175 // For negative exponents simply compute the reciprocal.
1176 if (Op2C->isNegative())
1177 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1178 return FMul;
1179 }
1180
Chris Bienemanad070d02014-09-17 20:55:46 +00001181 return nullptr;
1182}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001183
Chris Bienemanad070d02014-09-17 20:55:46 +00001184Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1185 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001186 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001187 StringRef Name = Callee->getName();
1188 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001189 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001190
Chris Bienemanad070d02014-09-17 20:55:46 +00001191 Value *Op = CI->getArgOperand(0);
1192 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1193 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001194 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001195 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001196 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001197 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001198 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001199
1200 if (TLI->has(LdExp)) {
1201 Value *LdExpArg = nullptr;
1202 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1203 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1204 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1205 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1206 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1207 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1208 }
1209
1210 if (LdExpArg) {
1211 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1212 if (!Op->getType()->isFloatTy())
1213 One = ConstantExpr::getFPExtend(One, Op->getType());
1214
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001215 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001216 Value *NewCallee =
1217 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001218 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001219 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001220 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1221 CI->setCallingConv(F->getCallingConv());
1222
1223 return CI;
1224 }
1225 }
1226 return Ret;
1227}
1228
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001229Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001230 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001231 // If we can shrink the call to a float function rather than a double
1232 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001233 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001234 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1235 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001236 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001237
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001238 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001239 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001240 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001241 // Unsafe algebra sets all fast-math-flags to true.
1242 FMF.setUnsafeAlgebra();
1243 } else {
1244 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001245 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001246 return nullptr;
1247 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1248 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001249 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001250 // might be impractical."
1251 FMF.setNoSignedZeros();
1252 FMF.setNoNaNs();
1253 }
Sanjay Patela2528152016-01-12 18:03:37 +00001254 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001255
1256 // We have a relaxed floating-point environment. We can ignore NaN-handling
1257 // and transform to a compare and select. We do not have to consider errno or
1258 // exceptions, because fmin/fmax do not have those.
1259 Value *Op0 = CI->getArgOperand(0);
1260 Value *Op1 = CI->getArgOperand(1);
1261 Value *Cmp = Callee->getName().startswith("fmin") ?
1262 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1263 return B.CreateSelect(Cmp, Op0, Op1);
1264}
1265
Davide Italianob8b71332015-11-29 20:58:04 +00001266Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1267 Function *Callee = CI->getCalledFunction();
1268 Value *Ret = nullptr;
1269 StringRef Name = Callee->getName();
1270 if (UnsafeFPShrink && hasFloatVersion(Name))
1271 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001272
Sanjay Patele896ede2016-01-11 23:31:48 +00001273 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001274 return Ret;
1275 Value *Op1 = CI->getArgOperand(0);
1276 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001277
1278 // The earlier call must also be unsafe in order to do these transforms.
1279 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001280 return Ret;
1281
1282 // log(pow(x,y)) -> y*log(x)
1283 // This is only applicable to log, log2, log10.
1284 if (Name != "log" && Name != "log2" && Name != "log10")
1285 return Ret;
1286
1287 IRBuilder<>::FastMathFlagGuard Guard(B);
1288 FastMathFlags FMF;
1289 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001290 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001291
David L. Jonesd21529f2017-01-23 23:16:46 +00001292 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001293 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001294 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001295 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001296 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001297 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001298 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001299
1300 // log(exp2(y)) -> y*log(2)
1301 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001302 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001303 return B.CreateFMul(
1304 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001305 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001306 Callee->getName(), B, Callee->getAttributes()),
1307 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001308 return Ret;
1309}
1310
Sanjay Patelc699a612014-10-16 18:48:17 +00001311Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1312 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001313 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001314 // TODO: Once we have a way (other than checking for the existince of the
1315 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1316 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001317 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001318 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001319 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001320
1321 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001322 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001323
Sanjay Patelc2d64612016-01-06 20:52:21 +00001324 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1325 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1326 return Ret;
1327
1328 // We're looking for a repeated factor in a multiplication tree,
1329 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001330 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001331 Value *Op0 = I->getOperand(0);
1332 Value *Op1 = I->getOperand(1);
1333 Value *RepeatOp = nullptr;
1334 Value *OtherOp = nullptr;
1335 if (Op0 == Op1) {
1336 // Simple match: the operands of the multiply are identical.
1337 RepeatOp = Op0;
1338 } else {
1339 // Look for a more complicated pattern: one of the operands is itself
1340 // a multiply, so search for a common factor in that multiply.
1341 // Note: We don't bother looking any deeper than this first level or for
1342 // variations of this pattern because instcombine's visitFMUL and/or the
1343 // reassociation pass should give us this form.
1344 Value *OtherMul0, *OtherMul1;
1345 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1346 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001347 if (OtherMul0 == OtherMul1 &&
1348 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001349 // Matched: sqrt((x * x) * z)
1350 RepeatOp = OtherMul0;
1351 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001352 }
1353 }
1354 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001355 if (!RepeatOp)
1356 return Ret;
1357
1358 // Fast math flags for any created instructions should match the sqrt
1359 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001360 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001361 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001362
Sanjay Patelc2d64612016-01-06 20:52:21 +00001363 // If we found a repeated factor, hoist it out of the square root and
1364 // replace it with the fabs of that factor.
1365 Module *M = Callee->getParent();
1366 Type *ArgType = I->getType();
1367 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1368 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1369 if (OtherOp) {
1370 // If we found a non-repeated factor, we still need to get its square
1371 // root. We then multiply that by the value that was simplified out
1372 // of the square root calculation.
1373 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1374 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1375 return B.CreateFMul(FabsCall, SqrtCall);
1376 }
1377 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001378}
1379
Sanjay Patelcddcd722016-01-06 19:23:35 +00001380// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001381Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1382 Function *Callee = CI->getCalledFunction();
1383 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001384 StringRef Name = Callee->getName();
1385 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001386 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001387
Davide Italiano51507d22015-11-04 23:36:56 +00001388 Value *Op1 = CI->getArgOperand(0);
1389 auto *OpC = dyn_cast<CallInst>(Op1);
1390 if (!OpC)
1391 return Ret;
1392
Sanjay Patelcddcd722016-01-06 19:23:35 +00001393 // Both calls must allow unsafe optimizations in order to remove them.
1394 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1395 return Ret;
1396
Davide Italiano51507d22015-11-04 23:36:56 +00001397 // tan(atan(x)) -> x
1398 // tanf(atanf(x)) -> x
1399 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001400 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001401 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001402 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001403 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1404 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1405 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001406 Ret = OpC->getArgOperand(0);
1407 return Ret;
1408}
1409
Sanjay Patel57747212016-01-21 23:38:43 +00001410static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001411 // We can only hope to do anything useful if we can ignore things like errno
1412 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001413 // We already checked the prototype.
1414 return CI->hasFnAttr(Attribute::NoUnwind) &&
1415 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001416}
1417
Chris Bienemanad070d02014-09-17 20:55:46 +00001418static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1419 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001420 Value *&SinCos) {
1421 Type *ArgTy = Arg->getType();
1422 Type *ResTy;
1423 StringRef Name;
1424
1425 Triple T(OrigCallee->getParent()->getTargetTriple());
1426 if (UseFloat) {
1427 Name = "__sincospif_stret";
1428
1429 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1430 // x86_64 can't use {float, float} since that would be returned in both
1431 // xmm0 and xmm1, which isn't what a real struct would do.
1432 ResTy = T.getArch() == Triple::x86_64
1433 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1434 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1435 } else {
1436 Name = "__sincospi_stret";
1437 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1438 }
1439
1440 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001441 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001442 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001443
1444 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1445 // If the argument is an instruction, it must dominate all uses so put our
1446 // sincos call there.
1447 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1448 } else {
1449 // Otherwise (e.g. for a constant) the beginning of the function is as
1450 // good a place as any.
1451 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1452 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1453 }
1454
1455 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1456
1457 if (SinCos->getType()->isStructTy()) {
1458 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1459 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1460 } else {
1461 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1462 "sinpi");
1463 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1464 "cospi");
1465 }
1466}
Chris Bienemanad070d02014-09-17 20:55:46 +00001467
1468Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001469 // Make sure the prototype is as expected, otherwise the rest of the
1470 // function is probably invalid and likely to abort.
1471 if (!isTrigLibCall(CI))
1472 return nullptr;
1473
1474 Value *Arg = CI->getArgOperand(0);
1475 SmallVector<CallInst *, 1> SinCalls;
1476 SmallVector<CallInst *, 1> CosCalls;
1477 SmallVector<CallInst *, 1> SinCosCalls;
1478
1479 bool IsFloat = Arg->getType()->isFloatTy();
1480
1481 // Look for all compatible sinpi, cospi and sincospi calls with the same
1482 // argument. If there are enough (in some sense) we can make the
1483 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001484 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001485 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001486 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001487
1488 // It's only worthwhile if both sinpi and cospi are actually used.
1489 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1490 return nullptr;
1491
1492 Value *Sin, *Cos, *SinCos;
1493 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1494
Davide Italianof024a562016-12-16 02:28:38 +00001495 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1496 Value *Res) {
1497 for (CallInst *C : Calls)
1498 replaceAllUsesWith(C, Res);
1499 };
1500
Chris Bienemanad070d02014-09-17 20:55:46 +00001501 replaceTrigInsts(SinCalls, Sin);
1502 replaceTrigInsts(CosCalls, Cos);
1503 replaceTrigInsts(SinCosCalls, SinCos);
1504
1505 return nullptr;
1506}
1507
David Majnemerabae6b52016-03-19 04:53:02 +00001508void LibCallSimplifier::classifyArgUse(
1509 Value *Val, Function *F, bool IsFloat,
1510 SmallVectorImpl<CallInst *> &SinCalls,
1511 SmallVectorImpl<CallInst *> &CosCalls,
1512 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001513 CallInst *CI = dyn_cast<CallInst>(Val);
1514
1515 if (!CI)
1516 return;
1517
David Majnemerabae6b52016-03-19 04:53:02 +00001518 // Don't consider calls in other functions.
1519 if (CI->getFunction() != F)
1520 return;
1521
Chris Bienemanad070d02014-09-17 20:55:46 +00001522 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001523 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001524 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001525 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001526 return;
1527
1528 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001529 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001530 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001531 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001532 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001533 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001534 SinCosCalls.push_back(CI);
1535 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001536 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001537 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001538 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001539 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001540 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001541 SinCosCalls.push_back(CI);
1542 }
1543}
1544
Meador Inge7415f842012-11-25 20:45:27 +00001545//===----------------------------------------------------------------------===//
1546// Integer Library Call Optimizations
1547//===----------------------------------------------------------------------===//
1548
Chris Bienemanad070d02014-09-17 20:55:46 +00001549Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001550 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001551 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001552 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001553 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1554 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001555 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001556 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1557 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001558
Chris Bienemanad070d02014-09-17 20:55:46 +00001559 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1560 return B.CreateSelect(Cond, V, B.getInt32(0));
1561}
Meador Ingea0b6d872012-11-26 00:24:07 +00001562
Davide Italiano85ad36b2016-12-15 23:45:11 +00001563Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1564 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1565 Value *Op = CI->getArgOperand(0);
1566 Type *ArgType = Op->getType();
1567 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1568 Intrinsic::ctlz, ArgType);
1569 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1570 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1571 V);
1572 return B.CreateIntCast(V, CI->getType(), false);
1573}
1574
Chris Bienemanad070d02014-09-17 20:55:46 +00001575Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001576 // abs(x) -> x >s -1 ? x : -x
1577 Value *Op = CI->getArgOperand(0);
1578 Value *Pos =
1579 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1580 Value *Neg = B.CreateNeg(Op, "neg");
1581 return B.CreateSelect(Pos, Op, Neg);
1582}
Meador Inge9a59ab62012-11-26 02:31:59 +00001583
Chris Bienemanad070d02014-09-17 20:55:46 +00001584Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001585 // isdigit(c) -> (c-'0') <u 10
1586 Value *Op = CI->getArgOperand(0);
1587 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1588 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1589 return B.CreateZExt(Op, CI->getType());
1590}
Meador Ingea62a39e2012-11-26 03:10:07 +00001591
Chris Bienemanad070d02014-09-17 20:55:46 +00001592Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001593 // isascii(c) -> c <u 128
1594 Value *Op = CI->getArgOperand(0);
1595 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1596 return B.CreateZExt(Op, CI->getType());
1597}
1598
1599Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001600 // toascii(c) -> c & 0x7f
1601 return B.CreateAnd(CI->getArgOperand(0),
1602 ConstantInt::get(CI->getType(), 0x7F));
1603}
Meador Inge604937d2012-11-26 03:38:52 +00001604
Meador Inge08ca1152012-11-26 20:37:20 +00001605//===----------------------------------------------------------------------===//
1606// Formatting and IO Library Call Optimizations
1607//===----------------------------------------------------------------------===//
1608
Chris Bienemanad070d02014-09-17 20:55:46 +00001609static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001610
Chris Bienemanad070d02014-09-17 20:55:46 +00001611Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1612 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001613 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001614 // Error reporting calls should be cold, mark them as such.
1615 // This applies even to non-builtin calls: it is only a hint and applies to
1616 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001617
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 // This heuristic was suggested in:
1619 // Improving Static Branch Prediction in a Compiler
1620 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1621 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001622 if (!CI->hasFnAttr(Attribute::Cold) &&
1623 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001624 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001625 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001626
Chris Bienemanad070d02014-09-17 20:55:46 +00001627 return nullptr;
1628}
1629
1630static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001631 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001632 return false;
1633
1634 if (StreamArg < 0)
1635 return true;
1636
1637 // These functions might be considered cold, but only if their stream
1638 // argument is stderr.
1639
1640 if (StreamArg >= (int)CI->getNumArgOperands())
1641 return false;
1642 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1643 if (!LI)
1644 return false;
1645 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1646 if (!GV || !GV->isDeclaration())
1647 return false;
1648 return GV->getName() == "stderr";
1649}
1650
1651Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1652 // Check for a fixed format string.
1653 StringRef FormatStr;
1654 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001655 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001656
Chris Bienemanad070d02014-09-17 20:55:46 +00001657 // Empty format string -> noop.
1658 if (FormatStr.empty()) // Tolerate printf's declared void.
1659 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001660
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 // Do not do any of the following transformations if the printf return value
1662 // is used, in general the printf return value is not compatible with either
1663 // putchar() or puts().
1664 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001665 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001666
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001667 // printf("x") -> putchar('x'), even for "%" and "%%".
1668 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001669 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001670
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001671 // printf("%s", "a") --> putchar('a')
1672 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1673 StringRef ChrStr;
1674 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1675 return nullptr;
1676 if (ChrStr.size() != 1)
1677 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001678 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001679 }
1680
Chris Bienemanad070d02014-09-17 20:55:46 +00001681 // printf("foo\n") --> puts("foo")
1682 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1683 FormatStr.find('%') == StringRef::npos) { // No format characters.
1684 // Create a string literal with no \n on it. We expect the constant merge
1685 // pass to be run after this pass, to merge duplicate strings.
1686 FormatStr = FormatStr.drop_back();
1687 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001688 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001689 }
Meador Inge08ca1152012-11-26 20:37:20 +00001690
Chris Bienemanad070d02014-09-17 20:55:46 +00001691 // Optimize specific format strings.
1692 // printf("%c", chr) --> putchar(chr)
1693 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001694 CI->getArgOperand(1)->getType()->isIntegerTy())
1695 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001696
1697 // printf("%s\n", str) --> puts(str)
1698 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001699 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001700 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001701 return nullptr;
1702}
1703
1704Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1705
1706 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001707 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001708 if (Value *V = optimizePrintFString(CI, B)) {
1709 return V;
1710 }
1711
1712 // printf(format, ...) -> iprintf(format, ...) if no floating point
1713 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001714 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001715 Module *M = B.GetInsertBlock()->getParent()->getParent();
1716 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001717 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001718 CallInst *New = cast<CallInst>(CI->clone());
1719 New->setCalledFunction(IPrintFFn);
1720 B.Insert(New);
1721 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001722 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001723 return nullptr;
1724}
Meador Inge08ca1152012-11-26 20:37:20 +00001725
Chris Bienemanad070d02014-09-17 20:55:46 +00001726Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1727 // Check for a fixed format string.
1728 StringRef FormatStr;
1729 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001730 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001731
Chris Bienemanad070d02014-09-17 20:55:46 +00001732 // If we just have a format string (nothing else crazy) transform it.
1733 if (CI->getNumArgOperands() == 2) {
1734 // Make sure there's no % in the constant array. We could try to handle
1735 // %% -> % in the future if we cared.
1736 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1737 if (FormatStr[i] == '%')
1738 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001739
Chris Bienemanad070d02014-09-17 20:55:46 +00001740 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001741 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1742 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1743 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001744 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001745 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001746 }
Meador Ingef8e72502012-11-29 15:45:43 +00001747
Chris Bienemanad070d02014-09-17 20:55:46 +00001748 // The remaining optimizations require the format string to be "%s" or "%c"
1749 // and have an extra operand.
1750 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1751 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001752 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001753
Chris Bienemanad070d02014-09-17 20:55:46 +00001754 // Decode the second character of the format string.
1755 if (FormatStr[1] == 'c') {
1756 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1757 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1758 return nullptr;
1759 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001760 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001761 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001762 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001763 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001764
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001766 }
1767
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1770 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1771 return nullptr;
1772
Sanjay Pateld3112a52016-01-19 19:46:10 +00001773 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001774 if (!Len)
1775 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001776 Value *IncLen =
1777 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1778 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001779
1780 // The sprintf result is the unincremented number of bytes in the string.
1781 return B.CreateIntCast(Len, CI->getType(), false);
1782 }
1783 return nullptr;
1784}
1785
1786Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1787 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001788 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 if (Value *V = optimizeSPrintFString(CI, B)) {
1790 return V;
1791 }
1792
1793 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1794 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001795 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001796 Module *M = B.GetInsertBlock()->getParent()->getParent();
1797 Constant *SIPrintFFn =
1798 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1799 CallInst *New = cast<CallInst>(CI->clone());
1800 New->setCalledFunction(SIPrintFFn);
1801 B.Insert(New);
1802 return New;
1803 }
1804 return nullptr;
1805}
1806
1807Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1808 optimizeErrorReporting(CI, B, 0);
1809
1810 // All the optimizations depend on the format string.
1811 StringRef FormatStr;
1812 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1813 return nullptr;
1814
1815 // Do not do any of the following transformations if the fprintf return
1816 // value is used, in general the fprintf return value is not compatible
1817 // with fwrite(), fputc() or fputs().
1818 if (!CI->use_empty())
1819 return nullptr;
1820
1821 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1822 if (CI->getNumArgOperands() == 2) {
1823 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1824 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1825 return nullptr; // We found a format specifier.
1826
Sanjay Pateld3112a52016-01-19 19:46:10 +00001827 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001829 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001830 CI->getArgOperand(0), B, DL, TLI);
1831 }
1832
1833 // The remaining optimizations require the format string to be "%s" or "%c"
1834 // and have an extra operand.
1835 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1836 CI->getNumArgOperands() < 3)
1837 return nullptr;
1838
1839 // Decode the second character of the format string.
1840 if (FormatStr[1] == 'c') {
1841 // fprintf(F, "%c", chr) --> fputc(chr, F)
1842 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1843 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001844 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001845 }
1846
1847 if (FormatStr[1] == 's') {
1848 // fprintf(F, "%s", str) --> fputs(str, F)
1849 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1850 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001851 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001852 }
1853 return nullptr;
1854}
1855
1856Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1857 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001858 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001859 if (Value *V = optimizeFPrintFString(CI, B)) {
1860 return V;
1861 }
1862
1863 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1864 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001865 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001866 Module *M = B.GetInsertBlock()->getParent()->getParent();
1867 Constant *FIPrintFFn =
1868 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1869 CallInst *New = cast<CallInst>(CI->clone());
1870 New->setCalledFunction(FIPrintFFn);
1871 B.Insert(New);
1872 return New;
1873 }
1874 return nullptr;
1875}
1876
1877Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1878 optimizeErrorReporting(CI, B, 3);
1879
Chris Bienemanad070d02014-09-17 20:55:46 +00001880 // Get the element size and count.
1881 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1882 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1883 if (!SizeC || !CountC)
1884 return nullptr;
1885 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1886
1887 // If this is writing zero records, remove the call (it's a noop).
1888 if (Bytes == 0)
1889 return ConstantInt::get(CI->getType(), 0);
1890
1891 // If this is writing one byte, turn it into fputc.
1892 // This optimisation is only valid, if the return value is unused.
1893 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001894 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1895 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001896 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1897 }
1898
1899 return nullptr;
1900}
1901
1902Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1903 optimizeErrorReporting(CI, B, 1);
1904
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001905 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1906 // requires more arguments and thus extra MOVs are required.
1907 if (CI->getParent()->getParent()->optForSize())
1908 return nullptr;
1909
Ahmed Bougachad765a822016-04-27 19:04:35 +00001910 // We can't optimize if return value is used.
1911 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001912 return nullptr;
1913
1914 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1915 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1916 if (!Len)
1917 return nullptr;
1918
1919 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001920 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001921 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001922 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001923 CI->getArgOperand(1), B, DL, TLI);
1924}
1925
1926Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001927 // Check for a constant string.
1928 StringRef Str;
1929 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1930 return nullptr;
1931
1932 if (Str.empty() && CI->use_empty()) {
1933 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001934 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001935 if (CI->use_empty() || !Res)
1936 return Res;
1937 return B.CreateIntCast(Res, CI->getType(), true);
1938 }
1939
1940 return nullptr;
1941}
1942
1943bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001944 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001945 SmallString<20> FloatFuncName = FuncName;
1946 FloatFuncName += 'f';
1947 if (TLI->getLibFunc(FloatFuncName, Func))
1948 return TLI->has(Func);
1949 return false;
1950}
Meador Inge7fb2f732012-10-13 16:45:32 +00001951
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001952Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1953 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001954 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001955 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001956 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001957 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001958 // Make sure we never change the calling convention.
1959 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001960 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001961 "Optimizing string/memory libcall would change the calling convention");
1962 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001963 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001964 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001965 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001966 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001967 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001968 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001969 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001970 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001971 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001972 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001973 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001974 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001975 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001976 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001977 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001978 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001979 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001980 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001981 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001982 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001983 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001984 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001985 case LibFunc_strtol:
1986 case LibFunc_strtod:
1987 case LibFunc_strtof:
1988 case LibFunc_strtoul:
1989 case LibFunc_strtoll:
1990 case LibFunc_strtold:
1991 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001992 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001993 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001994 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001995 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001996 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001997 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002000 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002001 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002003 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002004 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002005 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002006 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002007 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002008 return optimizeMemSet(CI, Builder);
2009 default:
2010 break;
2011 }
2012 }
2013 return nullptr;
2014}
2015
Chris Bienemanad070d02014-09-17 20:55:46 +00002016Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2017 if (CI->isNoBuiltin())
2018 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002019
David L. Jonesd21529f2017-01-23 23:16:46 +00002020 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002021 Function *Callee = CI->getCalledFunction();
2022 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002023
2024 SmallVector<OperandBundleDef, 2> OpBundles;
2025 CI->getOperandBundlesAsDefs(OpBundles);
2026 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002027 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002028
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002029 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002030 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2031 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002032 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002033 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002034
Sanjay Patel848309d2014-10-23 21:52:45 +00002035 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002036 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002037 if (!isCallingConvC)
2038 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002039 switch (II->getIntrinsicID()) {
2040 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002041 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002042 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002043 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002044 case Intrinsic::log:
2045 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002046 case Intrinsic::sqrt:
2047 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002048 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002049 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002050 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002051 }
2052 }
2053
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002054 // Also try to simplify calls to fortified library functions.
2055 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2056 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002057 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002058 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2059 // Use an IR Builder from SimplifiedCI if available instead of CI
2060 // to guarantee we reach all uses we might replace later on.
2061 IRBuilder<> TmpBuilder(SimplifiedCI);
2062 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002063 // If we were able to further simplify, remove the now redundant call.
2064 SimplifiedCI->replaceAllUsesWith(V);
2065 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002066 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002067 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002068 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002069 return SimplifiedFortifiedCI;
2070 }
2071
Meador Inge20255ef2013-03-12 00:08:29 +00002072 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002073 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002074 // We never change the calling convention.
2075 if (!ignoreCallingConv(Func) && !isCallingConvC)
2076 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002077 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2078 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002079 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002080 case LibFunc_cosf:
2081 case LibFunc_cos:
2082 case LibFunc_cosl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002083 return optimizeCos(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002084 case LibFunc_sinpif:
2085 case LibFunc_sinpi:
2086 case LibFunc_cospif:
2087 case LibFunc_cospi:
Chris Bienemanad070d02014-09-17 20:55:46 +00002088 return optimizeSinCosPi(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002089 case LibFunc_powf:
2090 case LibFunc_pow:
2091 case LibFunc_powl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002092 return optimizePow(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002093 case LibFunc_exp2l:
2094 case LibFunc_exp2:
2095 case LibFunc_exp2f:
Chris Bienemanad070d02014-09-17 20:55:46 +00002096 return optimizeExp2(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002097 case LibFunc_fabsf:
2098 case LibFunc_fabs:
2099 case LibFunc_fabsl:
Matt Arsenault954a6242017-01-23 23:55:08 +00002100 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
David L. Jonesd21529f2017-01-23 23:16:46 +00002101 case LibFunc_sqrtf:
2102 case LibFunc_sqrt:
2103 case LibFunc_sqrtl:
Sanjay Patelc699a612014-10-16 18:48:17 +00002104 return optimizeSqrt(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002105 case LibFunc_ffs:
2106 case LibFunc_ffsl:
2107 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002108 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002109 case LibFunc_fls:
2110 case LibFunc_flsl:
2111 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002112 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002113 case LibFunc_abs:
2114 case LibFunc_labs:
2115 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002116 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002117 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002118 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002119 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002120 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002121 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002122 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002123 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002124 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002125 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002126 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002127 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002128 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002129 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002130 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002131 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002132 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002133 case LibFunc_log:
2134 case LibFunc_log10:
2135 case LibFunc_log1p:
2136 case LibFunc_log2:
2137 case LibFunc_logb:
Davide Italianob8b71332015-11-29 20:58:04 +00002138 return optimizeLog(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002139 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002140 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002141 case LibFunc_tan:
2142 case LibFunc_tanf:
2143 case LibFunc_tanl:
Davide Italiano51507d22015-11-04 23:36:56 +00002144 return optimizeTan(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002145 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002146 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002147 case LibFunc_vfprintf:
2148 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002149 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002150 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002151 return optimizeErrorReporting(CI, Builder, 1);
David L. Jonesd21529f2017-01-23 23:16:46 +00002152 case LibFunc_ceil:
Matt Arsenault954a6242017-01-23 23:55:08 +00002153 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
David L. Jonesd21529f2017-01-23 23:16:46 +00002154 case LibFunc_floor:
Matt Arsenault954a6242017-01-23 23:55:08 +00002155 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
David L. Jonesd21529f2017-01-23 23:16:46 +00002156 case LibFunc_round:
Matt Arsenault954a6242017-01-23 23:55:08 +00002157 return replaceUnaryCall(CI, Builder, Intrinsic::round);
David L. Jonesd21529f2017-01-23 23:16:46 +00002158 case LibFunc_nearbyint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002159 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002160 case LibFunc_rint:
2161 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
David L. Jonesd21529f2017-01-23 23:16:46 +00002162 case LibFunc_trunc:
Matt Arsenault954a6242017-01-23 23:55:08 +00002163 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
David L. Jonesd21529f2017-01-23 23:16:46 +00002164 case LibFunc_acos:
2165 case LibFunc_acosh:
2166 case LibFunc_asin:
2167 case LibFunc_asinh:
2168 case LibFunc_atan:
2169 case LibFunc_atanh:
2170 case LibFunc_cbrt:
2171 case LibFunc_cosh:
2172 case LibFunc_exp:
2173 case LibFunc_exp10:
2174 case LibFunc_expm1:
2175 case LibFunc_sin:
2176 case LibFunc_sinh:
2177 case LibFunc_tanh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002178 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2179 return optimizeUnaryDoubleFP(CI, Builder, true);
2180 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002181 case LibFunc_copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002182 if (hasFloatVersion(FuncName))
2183 return optimizeBinaryDoubleFP(CI, Builder);
2184 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002185 case LibFunc_fminf:
2186 case LibFunc_fmin:
2187 case LibFunc_fminl:
2188 case LibFunc_fmaxf:
2189 case LibFunc_fmax:
2190 case LibFunc_fmaxl:
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002191 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002192 default:
2193 return nullptr;
2194 }
Meador Inge20255ef2013-03-12 00:08:29 +00002195 }
Craig Topperf40110f2014-04-25 05:29:35 +00002196 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002197}
2198
Chandler Carruth92803822015-01-21 02:11:59 +00002199LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002200 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002201 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002202 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002203 Replacer(Replacer) {}
2204
2205void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2206 // Indirect through the replacer used in this instance.
2207 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002208}
2209
Meador Ingedfb08a22013-06-20 19:48:07 +00002210// TODO:
2211// Additional cases that we need to add to this file:
2212//
2213// cbrt:
2214// * cbrt(expN(X)) -> expN(x/3)
2215// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002216// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002217//
2218// exp, expf, expl:
2219// * exp(log(x)) -> x
2220//
2221// log, logf, logl:
2222// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002223// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002224// * log(exp10(y)) -> y*log(10)
2225// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002226//
Meador Ingedfb08a22013-06-20 19:48:07 +00002227// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002228// * pow(sqrt(x),y) -> pow(x,y*0.5)
2229// * pow(pow(x,y),z)-> pow(x,y*z)
2230//
Meador Ingedfb08a22013-06-20 19:48:07 +00002231// signbit:
2232// * signbit(cnst) -> cnst'
2233// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2234//
2235// sqrt, sqrtf, sqrtl:
2236// * sqrt(expN(x)) -> expN(x*0.5)
2237// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2238// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2239//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002240
2241//===----------------------------------------------------------------------===//
2242// Fortified Library Call Optimizations
2243//===----------------------------------------------------------------------===//
2244
2245bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2246 unsigned ObjSizeOp,
2247 unsigned SizeOp,
2248 bool isString) {
2249 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2250 return true;
2251 if (ConstantInt *ObjSizeCI =
2252 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2253 if (ObjSizeCI->isAllOnesValue())
2254 return true;
2255 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2256 if (OnlyLowerUnknownSize)
2257 return false;
2258 if (isString) {
2259 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2260 // If the length is 0 we don't know how long it is and so we can't
2261 // remove the check.
2262 if (Len == 0)
2263 return false;
2264 return ObjSizeCI->getZExtValue() >= Len;
2265 }
2266 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2267 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2268 }
2269 return false;
2270}
2271
Sanjay Pateld707db92015-12-31 16:10:49 +00002272Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2273 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002274 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2275 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002276 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002277 return CI->getArgOperand(0);
2278 }
2279 return nullptr;
2280}
2281
Sanjay Pateld707db92015-12-31 16:10:49 +00002282Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2283 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002284 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2285 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002286 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002287 return CI->getArgOperand(0);
2288 }
2289 return nullptr;
2290}
2291
Sanjay Pateld707db92015-12-31 16:10:49 +00002292Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2293 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002294 // TODO: Try foldMallocMemset() here.
2295
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002296 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2297 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2298 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2299 return CI->getArgOperand(0);
2300 }
2301 return nullptr;
2302}
2303
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002304Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2305 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002306 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002307 Function *Callee = CI->getCalledFunction();
2308 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002309 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002310 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2311 *ObjSize = CI->getArgOperand(2);
2312
2313 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002314 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002315 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002316 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002317 }
2318
2319 // If a) we don't have any length information, or b) we know this will
2320 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2321 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2322 // TODO: It might be nice to get a maximum length out of the possible
2323 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002324 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002325 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002326
David Blaikie65fab6d2015-04-03 21:32:06 +00002327 if (OnlyLowerUnknownSize)
2328 return nullptr;
2329
2330 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2331 uint64_t Len = GetStringLength(Src);
2332 if (Len == 0)
2333 return nullptr;
2334
2335 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2336 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002337 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002338 // If the function was an __stpcpy_chk, and we were able to fold it into
2339 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002340 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002341 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2342 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002343}
2344
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002345Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2346 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002347 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002348 Function *Callee = CI->getCalledFunction();
2349 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002350 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002351 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002352 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002353 return Ret;
2354 }
2355 return nullptr;
2356}
2357
2358Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002359 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2360 // Some clang users checked for _chk libcall availability using:
2361 // __has_builtin(__builtin___memcpy_chk)
2362 // When compiling with -fno-builtin, this is always true.
2363 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2364 // end up with fortified libcalls, which isn't acceptable in a freestanding
2365 // environment which only provides their non-fortified counterparts.
2366 //
2367 // Until we change clang and/or teach external users to check for availability
2368 // differently, disregard the "nobuiltin" attribute and TLI::has.
2369 //
2370 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002371
David L. Jonesd21529f2017-01-23 23:16:46 +00002372 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002373 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002374
2375 SmallVector<OperandBundleDef, 2> OpBundles;
2376 CI->getOperandBundlesAsDefs(OpBundles);
2377 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002378 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002379
Ahmed Bougachad765a822016-04-27 19:04:35 +00002380 // First, check that this is a known library functions and that the prototype
2381 // is correct.
2382 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002383 return nullptr;
2384
2385 // We never change the calling convention.
2386 if (!ignoreCallingConv(Func) && !isCallingConvC)
2387 return nullptr;
2388
2389 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002390 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002391 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002392 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002393 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002394 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002395 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002396 case LibFunc_stpcpy_chk:
2397 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002398 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002399 case LibFunc_stpncpy_chk:
2400 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002401 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002402 default:
2403 break;
2404 }
2405 return nullptr;
2406}
2407
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002408FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2409 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2410 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}