blob: 2640c1f447a705462f81a1154c506971a3ab9abb [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();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000845 if (!InnerCallee)
846 return nullptr;
847
David L. Jonesd21529f2017-01-23 23:16:46 +0000848 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000849 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000850 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000851 return nullptr;
852
Sanjay Patel980b2802016-01-26 16:17:24 +0000853 // The memset must cover the same number of bytes that are malloc'd.
854 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
855 return nullptr;
856
857 // Replace the malloc with a calloc. We need the data layout to know what the
858 // actual size of a 'size_t' parameter is.
859 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
860 const DataLayout &DL = Malloc->getModule()->getDataLayout();
861 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
862 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
863 Malloc->getArgOperand(0), Malloc->getAttributes(),
864 B, TLI);
865 if (!Calloc)
866 return nullptr;
867
868 Malloc->replaceAllUsesWith(Calloc);
869 Malloc->eraseFromParent();
870
871 return Calloc;
872}
873
Chris Bienemanad070d02014-09-17 20:55:46 +0000874Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000875 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
876 return Calloc;
877
Chris Bienemanad070d02014-09-17 20:55:46 +0000878 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
879 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
880 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
881 return CI->getArgOperand(0);
882}
Meador Inged4825782012-11-11 06:49:03 +0000883
Meador Inge193e0352012-11-13 04:16:17 +0000884//===----------------------------------------------------------------------===//
885// Math Library Optimizations
886//===----------------------------------------------------------------------===//
887
Matthias Braund34e4d22014-12-03 21:46:33 +0000888/// Return a variant of Val with float type.
889/// Currently this works in two cases: If Val is an FPExtension of a float
890/// value to something bigger, simply return the operand.
891/// If Val is a ConstantFP but can be converted to a float ConstantFP without
892/// loss of precision do so.
893static Value *valueHasFloatPrecision(Value *Val) {
894 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
895 Value *Op = Cast->getOperand(0);
896 if (Op->getType()->isFloatTy())
897 return Op;
898 }
899 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
900 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000901 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000902 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000903 &losesInfo);
904 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000905 return ConstantFP::get(Const->getContext(), F);
906 }
907 return nullptr;
908}
909
Sanjay Patel4e971da2016-01-21 18:01:57 +0000910/// Shrink double -> float for unary functions like 'floor'.
911static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
912 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000913 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000914 // We know this libcall has a valid prototype, but we don't know which.
915 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000916 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000917
Chris Bienemanad070d02014-09-17 20:55:46 +0000918 if (CheckRetType) {
919 // Check if all the uses for function like 'sin' are converted to float.
920 for (User *U : CI->users()) {
921 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
922 if (!Cast || !Cast->getType()->isFloatTy())
923 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000924 }
Meador Inge193e0352012-11-13 04:16:17 +0000925 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000926
927 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000928 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
929 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000930 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000931
Andrew Ng1606fc02017-04-25 12:36:14 +0000932 // If call isn't an intrinsic, check that it isn't within a function with the
933 // same name as the float version of this call.
934 //
935 // e.g. inline float expf(float val) { return (float) exp((double) val); }
936 //
937 // A similar such definition exists in the MinGW-w64 math.h header file which
938 // when compiled with -O2 -ffast-math causes the generation of infinite loops
939 // where expf is called.
940 if (!Callee->isIntrinsic()) {
941 const Function *F = CI->getFunction();
942 StringRef FName = F->getName();
943 StringRef CalleeName = Callee->getName();
944 if ((FName.size() == (CalleeName.size() + 1)) &&
945 (FName.back() == 'f') &&
946 FName.startswith(CalleeName))
947 return nullptr;
948 }
949
Sanjay Patelaa231142015-12-31 21:52:31 +0000950 // Propagate fast-math flags from the existing call to the new call.
951 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000952 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000953
954 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000955 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000956 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000957 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000958 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
959 V = B.CreateCall(F, V);
960 } else {
961 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000962 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000963 }
964
Chris Bienemanad070d02014-09-17 20:55:46 +0000965 return B.CreateFPExt(V, B.getDoubleTy());
966}
Meador Inge193e0352012-11-13 04:16:17 +0000967
Matt Arsenault954a6242017-01-23 23:55:08 +0000968// Replace a libcall \p CI with a call to intrinsic \p IID
969static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
970 // Propagate fast-math flags from the existing call to the new call.
971 IRBuilder<>::FastMathFlagGuard Guard(B);
972 B.setFastMathFlags(CI->getFastMathFlags());
973
974 Module *M = CI->getModule();
975 Value *V = CI->getArgOperand(0);
976 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
977 CallInst *NewCall = B.CreateCall(F, V);
978 NewCall->takeName(CI);
979 return NewCall;
980}
981
Sanjay Patel4e971da2016-01-21 18:01:57 +0000982/// Shrink double -> float for binary functions like 'fmin/fmax'.
983static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000984 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000985 // We know this libcall has a valid prototype, but we don't know which.
986 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000987 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000988
Chris Bienemanad070d02014-09-17 20:55:46 +0000989 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000990 // or fmin(1.0, (double)floatval), then we convert it to fminf.
991 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
992 if (V1 == nullptr)
993 return nullptr;
994 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
995 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000996 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000997
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000998 // Propagate fast-math flags from the existing call to the new call.
999 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001000 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001001
Chris Bienemanad070d02014-09-17 20:55:46 +00001002 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001003 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001004 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001005 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001006 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001007 return B.CreateFPExt(V, B.getDoubleTy());
1008}
1009
1010Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1011 Function *Callee = CI->getCalledFunction();
1012 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001013 StringRef Name = Callee->getName();
1014 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001015 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001016
Chris Bienemanad070d02014-09-17 20:55:46 +00001017 // cos(-x) -> cos(x)
1018 Value *Op1 = CI->getArgOperand(0);
1019 if (BinaryOperator::isFNeg(Op1)) {
1020 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1021 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1022 }
1023 return Ret;
1024}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001025
Weiming Zhao82130722015-12-04 22:00:47 +00001026static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1027 // Multiplications calculated using Addition Chains.
1028 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1029
1030 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1031
1032 if (InnerChain[Exp])
1033 return InnerChain[Exp];
1034
1035 static const unsigned AddChain[33][2] = {
1036 {0, 0}, // Unused.
1037 {0, 0}, // Unused (base case = pow1).
1038 {1, 1}, // Unused (pre-computed).
1039 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1040 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1041 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1042 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1043 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1044 };
1045
1046 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1047 getPow(InnerChain, AddChain[Exp][1], B));
1048 return InnerChain[Exp];
1049}
1050
Chris Bienemanad070d02014-09-17 20:55:46 +00001051Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1052 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001053 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001054 StringRef Name = Callee->getName();
1055 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001056 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001057
Chris Bienemanad070d02014-09-17 20:55:46 +00001058 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001059
1060 // pow(1.0, x) -> 1.0
1061 if (match(Op1, m_SpecificFP(1.0)))
1062 return Op1;
1063 // pow(2.0, x) -> llvm.exp2(x)
1064 if (match(Op1, m_SpecificFP(2.0))) {
1065 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1066 CI->getType());
1067 return B.CreateCall(Exp2, Op2, "exp2");
1068 }
1069
1070 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1071 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001072 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001073 // pow(10.0, x) -> exp10(x)
1074 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001075 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1076 LibFunc_exp10l))
1077 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001078 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001079 }
1080
Sanjay Patel6002e782016-01-12 17:30:37 +00001081 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001082 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001083 // We enable these only with fast-math. Besides rounding differences, the
1084 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001085 // Example: x = 1000, y = 0.001.
1086 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001087 auto *OpC = dyn_cast<CallInst>(Op1);
1088 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001089 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001090 Function *OpCCallee = OpC->getCalledFunction();
1091 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001092 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001093 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001094 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001095 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001096 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001097 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001098 }
1099 }
1100
Chris Bienemanad070d02014-09-17 20:55:46 +00001101 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1102 if (!Op2C)
1103 return Ret;
1104
1105 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1106 return ConstantFP::get(CI->getType(), 1.0);
1107
Davide Italiano472684e2017-01-09 21:55:23 +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 Italiano472684e2017-01-09 21:55:23 +00001111 // If -ffast-math:
1112 // pow(x, -0.5) -> 1.0 / sqrt(x)
1113 if (CI->hasUnsafeAlgebra()) {
1114 IRBuilder<>::FastMathFlagGuard Guard(B);
1115 B.setFastMathFlags(CI->getFastMathFlags());
1116
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001117 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1118 // intrinsic, so we match errno semantics. We also should check that the
1119 // target can in fact lower the sqrt intrinsic -- we currently have no way
1120 // to ask this question other than asking whether the target has a sqrt
1121 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001122 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001123 Callee->getAttributes());
1124
1125 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1126 }
1127 }
1128
Chris Bienemanad070d02014-09-17 20:55:46 +00001129 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001130 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1131 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001132
1133 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001134 if (CI->hasUnsafeAlgebra()) {
1135 IRBuilder<>::FastMathFlagGuard Guard(B);
1136 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001137
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001138 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1139 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001140 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001141 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001142 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001143
Chris Bienemanad070d02014-09-17 20:55:46 +00001144 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1145 // This is faster than calling pow, and still handles negative zero
1146 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001147 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1148 Value *Inf = ConstantFP::getInfinity(CI->getType());
1149 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001150
1151 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1152 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001153 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001154
1155 Module *M = Callee->getParent();
1156 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1157 CI->getType());
1158 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1159
Chris Bienemanad070d02014-09-17 20:55:46 +00001160 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1161 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1162 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001163 }
1164
Chris Bienemanad070d02014-09-17 20:55:46 +00001165 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1166 return Op1;
1167 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1168 return B.CreateFMul(Op1, Op1, "pow2");
1169 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1170 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001171
1172 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001173 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001174 APFloat V = abs(Op2C->getValueAPF());
1175 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1176 // This transformation applies to integer exponents only.
1177 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1178 !V.isInteger())
1179 return nullptr;
1180
Davide Italianof8711f02017-01-10 18:02:05 +00001181 // Propagate fast math flags.
1182 IRBuilder<>::FastMathFlagGuard Guard(B);
1183 B.setFastMathFlags(CI->getFastMathFlags());
1184
Weiming Zhao82130722015-12-04 22:00:47 +00001185 // We will memoize intermediate products of the Addition Chain.
1186 Value *InnerChain[33] = {nullptr};
1187 InnerChain[1] = Op1;
1188 InnerChain[2] = B.CreateFMul(Op1, Op1);
1189
1190 // We cannot readily convert a non-double type (like float) to a double.
1191 // So we first convert V to something which could be converted to double.
1192 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001193 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001194
Weiming Zhao82130722015-12-04 22:00:47 +00001195 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1196 // For negative exponents simply compute the reciprocal.
1197 if (Op2C->isNegative())
1198 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1199 return FMul;
1200 }
1201
Chris Bienemanad070d02014-09-17 20:55:46 +00001202 return nullptr;
1203}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001204
Chris Bienemanad070d02014-09-17 20:55:46 +00001205Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1206 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001207 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001208 StringRef Name = Callee->getName();
1209 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001210 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001211
Chris Bienemanad070d02014-09-17 20:55:46 +00001212 Value *Op = CI->getArgOperand(0);
1213 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1214 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001215 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001216 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001217 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001218 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001219 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001220
1221 if (TLI->has(LdExp)) {
1222 Value *LdExpArg = nullptr;
1223 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1224 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1225 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1226 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1227 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1228 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1229 }
1230
1231 if (LdExpArg) {
1232 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1233 if (!Op->getType()->isFloatTy())
1234 One = ConstantExpr::getFPExtend(One, Op->getType());
1235
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001236 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001237 Value *NewCallee =
1238 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001239 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001240 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001241 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1242 CI->setCallingConv(F->getCallingConv());
1243
1244 return CI;
1245 }
1246 }
1247 return Ret;
1248}
1249
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001250Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001251 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001252 // If we can shrink the call to a float function rather than a double
1253 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001254 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001255 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1256 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001257 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001258
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001259 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001260 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001261 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001262 // Unsafe algebra sets all fast-math-flags to true.
1263 FMF.setUnsafeAlgebra();
1264 } else {
1265 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001266 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001267 return nullptr;
1268 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1269 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001270 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001271 // might be impractical."
1272 FMF.setNoSignedZeros();
1273 FMF.setNoNaNs();
1274 }
Sanjay Patela2528152016-01-12 18:03:37 +00001275 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001276
1277 // We have a relaxed floating-point environment. We can ignore NaN-handling
1278 // and transform to a compare and select. We do not have to consider errno or
1279 // exceptions, because fmin/fmax do not have those.
1280 Value *Op0 = CI->getArgOperand(0);
1281 Value *Op1 = CI->getArgOperand(1);
1282 Value *Cmp = Callee->getName().startswith("fmin") ?
1283 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1284 return B.CreateSelect(Cmp, Op0, Op1);
1285}
1286
Davide Italianob8b71332015-11-29 20:58:04 +00001287Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1288 Function *Callee = CI->getCalledFunction();
1289 Value *Ret = nullptr;
1290 StringRef Name = Callee->getName();
1291 if (UnsafeFPShrink && hasFloatVersion(Name))
1292 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001293
Sanjay Patele896ede2016-01-11 23:31:48 +00001294 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001295 return Ret;
1296 Value *Op1 = CI->getArgOperand(0);
1297 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001298
1299 // The earlier call must also be unsafe in order to do these transforms.
1300 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001301 return Ret;
1302
1303 // log(pow(x,y)) -> y*log(x)
1304 // This is only applicable to log, log2, log10.
1305 if (Name != "log" && Name != "log2" && Name != "log10")
1306 return Ret;
1307
1308 IRBuilder<>::FastMathFlagGuard Guard(B);
1309 FastMathFlags FMF;
1310 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001311 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001312
David L. Jonesd21529f2017-01-23 23:16:46 +00001313 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001314 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001315 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001316 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001317 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001318 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001319 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001320
1321 // log(exp2(y)) -> y*log(2)
1322 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001323 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001324 return B.CreateFMul(
1325 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001326 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001327 Callee->getName(), B, Callee->getAttributes()),
1328 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001329 return Ret;
1330}
1331
Sanjay Patelc699a612014-10-16 18:48:17 +00001332Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1333 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001334 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001335 // TODO: Once we have a way (other than checking for the existince of the
1336 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1337 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001338 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001339 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001340 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001341
1342 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001343 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001344
Sanjay Patelc2d64612016-01-06 20:52:21 +00001345 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1346 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1347 return Ret;
1348
1349 // We're looking for a repeated factor in a multiplication tree,
1350 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001351 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001352 Value *Op0 = I->getOperand(0);
1353 Value *Op1 = I->getOperand(1);
1354 Value *RepeatOp = nullptr;
1355 Value *OtherOp = nullptr;
1356 if (Op0 == Op1) {
1357 // Simple match: the operands of the multiply are identical.
1358 RepeatOp = Op0;
1359 } else {
1360 // Look for a more complicated pattern: one of the operands is itself
1361 // a multiply, so search for a common factor in that multiply.
1362 // Note: We don't bother looking any deeper than this first level or for
1363 // variations of this pattern because instcombine's visitFMUL and/or the
1364 // reassociation pass should give us this form.
1365 Value *OtherMul0, *OtherMul1;
1366 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1367 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001368 if (OtherMul0 == OtherMul1 &&
1369 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001370 // Matched: sqrt((x * x) * z)
1371 RepeatOp = OtherMul0;
1372 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001373 }
1374 }
1375 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001376 if (!RepeatOp)
1377 return Ret;
1378
1379 // Fast math flags for any created instructions should match the sqrt
1380 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001381 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001382 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001383
Sanjay Patelc2d64612016-01-06 20:52:21 +00001384 // If we found a repeated factor, hoist it out of the square root and
1385 // replace it with the fabs of that factor.
1386 Module *M = Callee->getParent();
1387 Type *ArgType = I->getType();
1388 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1389 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1390 if (OtherOp) {
1391 // If we found a non-repeated factor, we still need to get its square
1392 // root. We then multiply that by the value that was simplified out
1393 // of the square root calculation.
1394 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1395 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1396 return B.CreateFMul(FabsCall, SqrtCall);
1397 }
1398 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001399}
1400
Sanjay Patelcddcd722016-01-06 19:23:35 +00001401// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001402Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1403 Function *Callee = CI->getCalledFunction();
1404 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001405 StringRef Name = Callee->getName();
1406 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001407 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001408
Davide Italiano51507d22015-11-04 23:36:56 +00001409 Value *Op1 = CI->getArgOperand(0);
1410 auto *OpC = dyn_cast<CallInst>(Op1);
1411 if (!OpC)
1412 return Ret;
1413
Sanjay Patelcddcd722016-01-06 19:23:35 +00001414 // Both calls must allow unsafe optimizations in order to remove them.
1415 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1416 return Ret;
1417
Davide Italiano51507d22015-11-04 23:36:56 +00001418 // tan(atan(x)) -> x
1419 // tanf(atanf(x)) -> x
1420 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001421 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001422 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001423 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001424 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1425 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1426 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001427 Ret = OpC->getArgOperand(0);
1428 return Ret;
1429}
1430
Sanjay Patel57747212016-01-21 23:38:43 +00001431static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001432 // We can only hope to do anything useful if we can ignore things like errno
1433 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001434 // We already checked the prototype.
1435 return CI->hasFnAttr(Attribute::NoUnwind) &&
1436 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001437}
1438
Chris Bienemanad070d02014-09-17 20:55:46 +00001439static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1440 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001441 Value *&SinCos) {
1442 Type *ArgTy = Arg->getType();
1443 Type *ResTy;
1444 StringRef Name;
1445
1446 Triple T(OrigCallee->getParent()->getTargetTriple());
1447 if (UseFloat) {
1448 Name = "__sincospif_stret";
1449
1450 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1451 // x86_64 can't use {float, float} since that would be returned in both
1452 // xmm0 and xmm1, which isn't what a real struct would do.
1453 ResTy = T.getArch() == Triple::x86_64
1454 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1455 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1456 } else {
1457 Name = "__sincospi_stret";
1458 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1459 }
1460
1461 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001462 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001463 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001464
1465 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1466 // If the argument is an instruction, it must dominate all uses so put our
1467 // sincos call there.
1468 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1469 } else {
1470 // Otherwise (e.g. for a constant) the beginning of the function is as
1471 // good a place as any.
1472 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1473 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1474 }
1475
1476 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1477
1478 if (SinCos->getType()->isStructTy()) {
1479 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1480 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1481 } else {
1482 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1483 "sinpi");
1484 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1485 "cospi");
1486 }
1487}
Chris Bienemanad070d02014-09-17 20:55:46 +00001488
1489Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001490 // Make sure the prototype is as expected, otherwise the rest of the
1491 // function is probably invalid and likely to abort.
1492 if (!isTrigLibCall(CI))
1493 return nullptr;
1494
1495 Value *Arg = CI->getArgOperand(0);
1496 SmallVector<CallInst *, 1> SinCalls;
1497 SmallVector<CallInst *, 1> CosCalls;
1498 SmallVector<CallInst *, 1> SinCosCalls;
1499
1500 bool IsFloat = Arg->getType()->isFloatTy();
1501
1502 // Look for all compatible sinpi, cospi and sincospi calls with the same
1503 // argument. If there are enough (in some sense) we can make the
1504 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001505 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001506 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001507 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001508
1509 // It's only worthwhile if both sinpi and cospi are actually used.
1510 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1511 return nullptr;
1512
1513 Value *Sin, *Cos, *SinCos;
1514 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1515
Davide Italianof024a562016-12-16 02:28:38 +00001516 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1517 Value *Res) {
1518 for (CallInst *C : Calls)
1519 replaceAllUsesWith(C, Res);
1520 };
1521
Chris Bienemanad070d02014-09-17 20:55:46 +00001522 replaceTrigInsts(SinCalls, Sin);
1523 replaceTrigInsts(CosCalls, Cos);
1524 replaceTrigInsts(SinCosCalls, SinCos);
1525
1526 return nullptr;
1527}
1528
David Majnemerabae6b52016-03-19 04:53:02 +00001529void LibCallSimplifier::classifyArgUse(
1530 Value *Val, Function *F, bool IsFloat,
1531 SmallVectorImpl<CallInst *> &SinCalls,
1532 SmallVectorImpl<CallInst *> &CosCalls,
1533 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001534 CallInst *CI = dyn_cast<CallInst>(Val);
1535
1536 if (!CI)
1537 return;
1538
David Majnemerabae6b52016-03-19 04:53:02 +00001539 // Don't consider calls in other functions.
1540 if (CI->getFunction() != F)
1541 return;
1542
Chris Bienemanad070d02014-09-17 20:55:46 +00001543 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001544 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001545 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001546 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001547 return;
1548
1549 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001550 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001551 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001552 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001553 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001554 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 SinCosCalls.push_back(CI);
1556 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001557 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001558 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001559 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001561 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001562 SinCosCalls.push_back(CI);
1563 }
1564}
1565
Meador Inge7415f842012-11-25 20:45:27 +00001566//===----------------------------------------------------------------------===//
1567// Integer Library Call Optimizations
1568//===----------------------------------------------------------------------===//
1569
Chris Bienemanad070d02014-09-17 20:55:46 +00001570Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001572 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001573 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001574 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1575 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001576 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001577 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1578 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001579
Chris Bienemanad070d02014-09-17 20:55:46 +00001580 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1581 return B.CreateSelect(Cond, V, B.getInt32(0));
1582}
Meador Ingea0b6d872012-11-26 00:24:07 +00001583
Davide Italiano85ad36b2016-12-15 23:45:11 +00001584Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1585 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1586 Value *Op = CI->getArgOperand(0);
1587 Type *ArgType = Op->getType();
1588 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1589 Intrinsic::ctlz, ArgType);
1590 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1591 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1592 V);
1593 return B.CreateIntCast(V, CI->getType(), false);
1594}
1595
Chris Bienemanad070d02014-09-17 20:55:46 +00001596Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001597 // abs(x) -> x >s -1 ? x : -x
1598 Value *Op = CI->getArgOperand(0);
1599 Value *Pos =
1600 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1601 Value *Neg = B.CreateNeg(Op, "neg");
1602 return B.CreateSelect(Pos, Op, Neg);
1603}
Meador Inge9a59ab62012-11-26 02:31:59 +00001604
Chris Bienemanad070d02014-09-17 20:55:46 +00001605Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001606 // isdigit(c) -> (c-'0') <u 10
1607 Value *Op = CI->getArgOperand(0);
1608 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1609 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1610 return B.CreateZExt(Op, CI->getType());
1611}
Meador Ingea62a39e2012-11-26 03:10:07 +00001612
Chris Bienemanad070d02014-09-17 20:55:46 +00001613Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001614 // isascii(c) -> c <u 128
1615 Value *Op = CI->getArgOperand(0);
1616 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1617 return B.CreateZExt(Op, CI->getType());
1618}
1619
1620Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001621 // toascii(c) -> c & 0x7f
1622 return B.CreateAnd(CI->getArgOperand(0),
1623 ConstantInt::get(CI->getType(), 0x7F));
1624}
Meador Inge604937d2012-11-26 03:38:52 +00001625
Meador Inge08ca1152012-11-26 20:37:20 +00001626//===----------------------------------------------------------------------===//
1627// Formatting and IO Library Call Optimizations
1628//===----------------------------------------------------------------------===//
1629
Chris Bienemanad070d02014-09-17 20:55:46 +00001630static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001631
Chris Bienemanad070d02014-09-17 20:55:46 +00001632Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1633 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001634 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001635 // Error reporting calls should be cold, mark them as such.
1636 // This applies even to non-builtin calls: it is only a hint and applies to
1637 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001638
Chris Bienemanad070d02014-09-17 20:55:46 +00001639 // This heuristic was suggested in:
1640 // Improving Static Branch Prediction in a Compiler
1641 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1642 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001643 if (!CI->hasFnAttr(Attribute::Cold) &&
1644 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001645 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001647
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 return nullptr;
1649}
1650
1651static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001652 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001653 return false;
1654
1655 if (StreamArg < 0)
1656 return true;
1657
1658 // These functions might be considered cold, but only if their stream
1659 // argument is stderr.
1660
1661 if (StreamArg >= (int)CI->getNumArgOperands())
1662 return false;
1663 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1664 if (!LI)
1665 return false;
1666 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1667 if (!GV || !GV->isDeclaration())
1668 return false;
1669 return GV->getName() == "stderr";
1670}
1671
1672Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1673 // Check for a fixed format string.
1674 StringRef FormatStr;
1675 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001676 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001677
Chris Bienemanad070d02014-09-17 20:55:46 +00001678 // Empty format string -> noop.
1679 if (FormatStr.empty()) // Tolerate printf's declared void.
1680 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001681
Chris Bienemanad070d02014-09-17 20:55:46 +00001682 // Do not do any of the following transformations if the printf return value
1683 // is used, in general the printf return value is not compatible with either
1684 // putchar() or puts().
1685 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001686 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001687
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001688 // printf("x") -> putchar('x'), even for "%" and "%%".
1689 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001690 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001691
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001692 // printf("%s", "a") --> putchar('a')
1693 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1694 StringRef ChrStr;
1695 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1696 return nullptr;
1697 if (ChrStr.size() != 1)
1698 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001699 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001700 }
1701
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 // printf("foo\n") --> puts("foo")
1703 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1704 FormatStr.find('%') == StringRef::npos) { // No format characters.
1705 // Create a string literal with no \n on it. We expect the constant merge
1706 // pass to be run after this pass, to merge duplicate strings.
1707 FormatStr = FormatStr.drop_back();
1708 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001709 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001710 }
Meador Inge08ca1152012-11-26 20:37:20 +00001711
Chris Bienemanad070d02014-09-17 20:55:46 +00001712 // Optimize specific format strings.
1713 // printf("%c", chr) --> putchar(chr)
1714 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001715 CI->getArgOperand(1)->getType()->isIntegerTy())
1716 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001717
1718 // printf("%s\n", str) --> puts(str)
1719 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001720 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001721 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001722 return nullptr;
1723}
1724
1725Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1726
1727 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001728 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001729 if (Value *V = optimizePrintFString(CI, B)) {
1730 return V;
1731 }
1732
1733 // printf(format, ...) -> iprintf(format, ...) if no floating point
1734 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001735 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 Module *M = B.GetInsertBlock()->getParent()->getParent();
1737 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001738 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001739 CallInst *New = cast<CallInst>(CI->clone());
1740 New->setCalledFunction(IPrintFFn);
1741 B.Insert(New);
1742 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001743 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001744 return nullptr;
1745}
Meador Inge08ca1152012-11-26 20:37:20 +00001746
Chris Bienemanad070d02014-09-17 20:55:46 +00001747Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1748 // Check for a fixed format string.
1749 StringRef FormatStr;
1750 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001751 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001752
Chris Bienemanad070d02014-09-17 20:55:46 +00001753 // If we just have a format string (nothing else crazy) transform it.
1754 if (CI->getNumArgOperands() == 2) {
1755 // Make sure there's no % in the constant array. We could try to handle
1756 // %% -> % in the future if we cared.
1757 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1758 if (FormatStr[i] == '%')
1759 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001760
Chris Bienemanad070d02014-09-17 20:55:46 +00001761 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001762 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1763 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1764 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001765 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001766 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001767 }
Meador Ingef8e72502012-11-29 15:45:43 +00001768
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 // The remaining optimizations require the format string to be "%s" or "%c"
1770 // and have an extra operand.
1771 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1772 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001773 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001774
Chris Bienemanad070d02014-09-17 20:55:46 +00001775 // Decode the second character of the format string.
1776 if (FormatStr[1] == 'c') {
1777 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1778 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1779 return nullptr;
1780 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001781 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001782 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001783 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001784 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001785
Chris Bienemanad070d02014-09-17 20:55:46 +00001786 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001787 }
1788
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1791 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1792 return nullptr;
1793
Sanjay Pateld3112a52016-01-19 19:46:10 +00001794 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001795 if (!Len)
1796 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001797 Value *IncLen =
1798 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1799 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001800
1801 // The sprintf result is the unincremented number of bytes in the string.
1802 return B.CreateIntCast(Len, CI->getType(), false);
1803 }
1804 return nullptr;
1805}
1806
1807Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1808 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001809 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001810 if (Value *V = optimizeSPrintFString(CI, B)) {
1811 return V;
1812 }
1813
1814 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1815 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001816 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001817 Module *M = B.GetInsertBlock()->getParent()->getParent();
1818 Constant *SIPrintFFn =
1819 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1820 CallInst *New = cast<CallInst>(CI->clone());
1821 New->setCalledFunction(SIPrintFFn);
1822 B.Insert(New);
1823 return New;
1824 }
1825 return nullptr;
1826}
1827
1828Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1829 optimizeErrorReporting(CI, B, 0);
1830
1831 // All the optimizations depend on the format string.
1832 StringRef FormatStr;
1833 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1834 return nullptr;
1835
1836 // Do not do any of the following transformations if the fprintf return
1837 // value is used, in general the fprintf return value is not compatible
1838 // with fwrite(), fputc() or fputs().
1839 if (!CI->use_empty())
1840 return nullptr;
1841
1842 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1843 if (CI->getNumArgOperands() == 2) {
1844 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1845 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1846 return nullptr; // We found a format specifier.
1847
Sanjay Pateld3112a52016-01-19 19:46:10 +00001848 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001849 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001850 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001851 CI->getArgOperand(0), B, DL, TLI);
1852 }
1853
1854 // The remaining optimizations require the format string to be "%s" or "%c"
1855 // and have an extra operand.
1856 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1857 CI->getNumArgOperands() < 3)
1858 return nullptr;
1859
1860 // Decode the second character of the format string.
1861 if (FormatStr[1] == 'c') {
1862 // fprintf(F, "%c", chr) --> fputc(chr, F)
1863 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1864 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001865 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001866 }
1867
1868 if (FormatStr[1] == 's') {
1869 // fprintf(F, "%s", str) --> fputs(str, F)
1870 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1871 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001872 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 }
1874 return nullptr;
1875}
1876
1877Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1878 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001879 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001880 if (Value *V = optimizeFPrintFString(CI, B)) {
1881 return V;
1882 }
1883
1884 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1885 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001886 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001887 Module *M = B.GetInsertBlock()->getParent()->getParent();
1888 Constant *FIPrintFFn =
1889 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1890 CallInst *New = cast<CallInst>(CI->clone());
1891 New->setCalledFunction(FIPrintFFn);
1892 B.Insert(New);
1893 return New;
1894 }
1895 return nullptr;
1896}
1897
1898Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1899 optimizeErrorReporting(CI, B, 3);
1900
Chris Bienemanad070d02014-09-17 20:55:46 +00001901 // Get the element size and count.
1902 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1903 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1904 if (!SizeC || !CountC)
1905 return nullptr;
1906 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1907
1908 // If this is writing zero records, remove the call (it's a noop).
1909 if (Bytes == 0)
1910 return ConstantInt::get(CI->getType(), 0);
1911
1912 // If this is writing one byte, turn it into fputc.
1913 // This optimisation is only valid, if the return value is unused.
1914 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001915 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1916 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001917 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1918 }
1919
1920 return nullptr;
1921}
1922
1923Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1924 optimizeErrorReporting(CI, B, 1);
1925
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001926 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1927 // requires more arguments and thus extra MOVs are required.
1928 if (CI->getParent()->getParent()->optForSize())
1929 return nullptr;
1930
Ahmed Bougachad765a822016-04-27 19:04:35 +00001931 // We can't optimize if return value is used.
1932 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001933 return nullptr;
1934
1935 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1936 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1937 if (!Len)
1938 return nullptr;
1939
1940 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001941 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001942 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001943 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001944 CI->getArgOperand(1), B, DL, TLI);
1945}
1946
1947Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001948 // Check for a constant string.
1949 StringRef Str;
1950 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1951 return nullptr;
1952
1953 if (Str.empty() && CI->use_empty()) {
1954 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001955 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001956 if (CI->use_empty() || !Res)
1957 return Res;
1958 return B.CreateIntCast(Res, CI->getType(), true);
1959 }
1960
1961 return nullptr;
1962}
1963
1964bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001965 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001966 SmallString<20> FloatFuncName = FuncName;
1967 FloatFuncName += 'f';
1968 if (TLI->getLibFunc(FloatFuncName, Func))
1969 return TLI->has(Func);
1970 return false;
1971}
Meador Inge7fb2f732012-10-13 16:45:32 +00001972
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001973Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1974 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001975 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001976 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001977 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001978 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001979 // Make sure we never change the calling convention.
1980 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001981 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001982 "Optimizing string/memory libcall would change the calling convention");
1983 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001984 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001985 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001986 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001987 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001988 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001989 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001990 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001991 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001992 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001993 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001994 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001995 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001996 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001997 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001998 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001999 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002000 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002001 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002002 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002003 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002004 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002005 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002006 case LibFunc_strtol:
2007 case LibFunc_strtod:
2008 case LibFunc_strtof:
2009 case LibFunc_strtoul:
2010 case LibFunc_strtoll:
2011 case LibFunc_strtold:
2012 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002013 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002014 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002015 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002016 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002017 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002018 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002019 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002020 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002021 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002022 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002023 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002024 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002025 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002026 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002027 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002028 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002029 return optimizeMemSet(CI, Builder);
2030 default:
2031 break;
2032 }
2033 }
2034 return nullptr;
2035}
2036
Chris Bienemanad070d02014-09-17 20:55:46 +00002037Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2038 if (CI->isNoBuiltin())
2039 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002040
David L. Jonesd21529f2017-01-23 23:16:46 +00002041 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002042 Function *Callee = CI->getCalledFunction();
2043 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002044
2045 SmallVector<OperandBundleDef, 2> OpBundles;
2046 CI->getOperandBundlesAsDefs(OpBundles);
2047 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002048 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002049
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002050 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002051 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2052 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002053 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002054 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002055
Sanjay Patel848309d2014-10-23 21:52:45 +00002056 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002057 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002058 if (!isCallingConvC)
2059 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002060 switch (II->getIntrinsicID()) {
2061 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002062 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002063 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002064 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002065 case Intrinsic::log:
2066 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002067 case Intrinsic::sqrt:
2068 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002069 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002070 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002071 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002072 }
2073 }
2074
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002075 // Also try to simplify calls to fortified library functions.
2076 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2077 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002078 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002079 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2080 // Use an IR Builder from SimplifiedCI if available instead of CI
2081 // to guarantee we reach all uses we might replace later on.
2082 IRBuilder<> TmpBuilder(SimplifiedCI);
2083 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002084 // If we were able to further simplify, remove the now redundant call.
2085 SimplifiedCI->replaceAllUsesWith(V);
2086 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002087 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002088 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002089 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002090 return SimplifiedFortifiedCI;
2091 }
2092
Meador Inge20255ef2013-03-12 00:08:29 +00002093 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002094 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002095 // We never change the calling convention.
2096 if (!ignoreCallingConv(Func) && !isCallingConvC)
2097 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002098 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2099 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002100 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002101 case LibFunc_cosf:
2102 case LibFunc_cos:
2103 case LibFunc_cosl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002104 return optimizeCos(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002105 case LibFunc_sinpif:
2106 case LibFunc_sinpi:
2107 case LibFunc_cospif:
2108 case LibFunc_cospi:
Chris Bienemanad070d02014-09-17 20:55:46 +00002109 return optimizeSinCosPi(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002110 case LibFunc_powf:
2111 case LibFunc_pow:
2112 case LibFunc_powl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002113 return optimizePow(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002114 case LibFunc_exp2l:
2115 case LibFunc_exp2:
2116 case LibFunc_exp2f:
Chris Bienemanad070d02014-09-17 20:55:46 +00002117 return optimizeExp2(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002118 case LibFunc_fabsf:
2119 case LibFunc_fabs:
2120 case LibFunc_fabsl:
Matt Arsenault954a6242017-01-23 23:55:08 +00002121 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
David L. Jonesd21529f2017-01-23 23:16:46 +00002122 case LibFunc_sqrtf:
2123 case LibFunc_sqrt:
2124 case LibFunc_sqrtl:
Sanjay Patelc699a612014-10-16 18:48:17 +00002125 return optimizeSqrt(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002126 case LibFunc_ffs:
2127 case LibFunc_ffsl:
2128 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002129 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002130 case LibFunc_fls:
2131 case LibFunc_flsl:
2132 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002133 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002134 case LibFunc_abs:
2135 case LibFunc_labs:
2136 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002137 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002138 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002139 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002140 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002141 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002142 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002143 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002144 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002145 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002146 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002147 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002148 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002149 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002150 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002151 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002152 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002153 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002154 case LibFunc_log:
2155 case LibFunc_log10:
2156 case LibFunc_log1p:
2157 case LibFunc_log2:
2158 case LibFunc_logb:
Davide Italianob8b71332015-11-29 20:58:04 +00002159 return optimizeLog(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002160 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002161 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002162 case LibFunc_tan:
2163 case LibFunc_tanf:
2164 case LibFunc_tanl:
Davide Italiano51507d22015-11-04 23:36:56 +00002165 return optimizeTan(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002166 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002167 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002168 case LibFunc_vfprintf:
2169 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002170 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002171 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002172 return optimizeErrorReporting(CI, Builder, 1);
David L. Jonesd21529f2017-01-23 23:16:46 +00002173 case LibFunc_ceil:
Matt Arsenault954a6242017-01-23 23:55:08 +00002174 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
David L. Jonesd21529f2017-01-23 23:16:46 +00002175 case LibFunc_floor:
Matt Arsenault954a6242017-01-23 23:55:08 +00002176 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
David L. Jonesd21529f2017-01-23 23:16:46 +00002177 case LibFunc_round:
Matt Arsenault954a6242017-01-23 23:55:08 +00002178 return replaceUnaryCall(CI, Builder, Intrinsic::round);
David L. Jonesd21529f2017-01-23 23:16:46 +00002179 case LibFunc_nearbyint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002180 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002181 case LibFunc_rint:
2182 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
David L. Jonesd21529f2017-01-23 23:16:46 +00002183 case LibFunc_trunc:
Matt Arsenault954a6242017-01-23 23:55:08 +00002184 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
David L. Jonesd21529f2017-01-23 23:16:46 +00002185 case LibFunc_acos:
2186 case LibFunc_acosh:
2187 case LibFunc_asin:
2188 case LibFunc_asinh:
2189 case LibFunc_atan:
2190 case LibFunc_atanh:
2191 case LibFunc_cbrt:
2192 case LibFunc_cosh:
2193 case LibFunc_exp:
2194 case LibFunc_exp10:
2195 case LibFunc_expm1:
2196 case LibFunc_sin:
2197 case LibFunc_sinh:
2198 case LibFunc_tanh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002199 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2200 return optimizeUnaryDoubleFP(CI, Builder, true);
2201 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002202 case LibFunc_copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002203 if (hasFloatVersion(FuncName))
2204 return optimizeBinaryDoubleFP(CI, Builder);
2205 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002206 case LibFunc_fminf:
2207 case LibFunc_fmin:
2208 case LibFunc_fminl:
2209 case LibFunc_fmaxf:
2210 case LibFunc_fmax:
2211 case LibFunc_fmaxl:
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002212 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002213 default:
2214 return nullptr;
2215 }
Meador Inge20255ef2013-03-12 00:08:29 +00002216 }
Craig Topperf40110f2014-04-25 05:29:35 +00002217 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002218}
2219
Chandler Carruth92803822015-01-21 02:11:59 +00002220LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002221 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002222 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002223 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002224 Replacer(Replacer) {}
2225
2226void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2227 // Indirect through the replacer used in this instance.
2228 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002229}
2230
Meador Ingedfb08a22013-06-20 19:48:07 +00002231// TODO:
2232// Additional cases that we need to add to this file:
2233//
2234// cbrt:
2235// * cbrt(expN(X)) -> expN(x/3)
2236// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002237// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002238//
2239// exp, expf, expl:
2240// * exp(log(x)) -> x
2241//
2242// log, logf, logl:
2243// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002244// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002245// * log(exp10(y)) -> y*log(10)
2246// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002247//
Meador Ingedfb08a22013-06-20 19:48:07 +00002248// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002249// * pow(sqrt(x),y) -> pow(x,y*0.5)
2250// * pow(pow(x,y),z)-> pow(x,y*z)
2251//
Meador Ingedfb08a22013-06-20 19:48:07 +00002252// signbit:
2253// * signbit(cnst) -> cnst'
2254// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2255//
2256// sqrt, sqrtf, sqrtl:
2257// * sqrt(expN(x)) -> expN(x*0.5)
2258// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2259// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2260//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002261
2262//===----------------------------------------------------------------------===//
2263// Fortified Library Call Optimizations
2264//===----------------------------------------------------------------------===//
2265
2266bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2267 unsigned ObjSizeOp,
2268 unsigned SizeOp,
2269 bool isString) {
2270 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2271 return true;
2272 if (ConstantInt *ObjSizeCI =
2273 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2274 if (ObjSizeCI->isAllOnesValue())
2275 return true;
2276 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2277 if (OnlyLowerUnknownSize)
2278 return false;
2279 if (isString) {
2280 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2281 // If the length is 0 we don't know how long it is and so we can't
2282 // remove the check.
2283 if (Len == 0)
2284 return false;
2285 return ObjSizeCI->getZExtValue() >= Len;
2286 }
2287 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2288 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2289 }
2290 return false;
2291}
2292
Sanjay Pateld707db92015-12-31 16:10:49 +00002293Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2294 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002295 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2296 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002297 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002298 return CI->getArgOperand(0);
2299 }
2300 return nullptr;
2301}
2302
Sanjay Pateld707db92015-12-31 16:10:49 +00002303Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2304 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002305 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2306 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002307 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002308 return CI->getArgOperand(0);
2309 }
2310 return nullptr;
2311}
2312
Sanjay Pateld707db92015-12-31 16:10:49 +00002313Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2314 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002315 // TODO: Try foldMallocMemset() here.
2316
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002317 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2318 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2319 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2320 return CI->getArgOperand(0);
2321 }
2322 return nullptr;
2323}
2324
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002325Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2326 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002327 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002328 Function *Callee = CI->getCalledFunction();
2329 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002330 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002331 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2332 *ObjSize = CI->getArgOperand(2);
2333
2334 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002335 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002336 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002337 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002338 }
2339
2340 // If a) we don't have any length information, or b) we know this will
2341 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2342 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2343 // TODO: It might be nice to get a maximum length out of the possible
2344 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002345 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002346 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002347
David Blaikie65fab6d2015-04-03 21:32:06 +00002348 if (OnlyLowerUnknownSize)
2349 return nullptr;
2350
2351 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2352 uint64_t Len = GetStringLength(Src);
2353 if (Len == 0)
2354 return nullptr;
2355
2356 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2357 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002358 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002359 // If the function was an __stpcpy_chk, and we were able to fold it into
2360 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002361 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002362 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2363 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002364}
2365
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002366Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2367 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002368 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002369 Function *Callee = CI->getCalledFunction();
2370 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002371 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002372 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002373 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002374 return Ret;
2375 }
2376 return nullptr;
2377}
2378
2379Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002380 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2381 // Some clang users checked for _chk libcall availability using:
2382 // __has_builtin(__builtin___memcpy_chk)
2383 // When compiling with -fno-builtin, this is always true.
2384 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2385 // end up with fortified libcalls, which isn't acceptable in a freestanding
2386 // environment which only provides their non-fortified counterparts.
2387 //
2388 // Until we change clang and/or teach external users to check for availability
2389 // differently, disregard the "nobuiltin" attribute and TLI::has.
2390 //
2391 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002392
David L. Jonesd21529f2017-01-23 23:16:46 +00002393 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002394 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002395
2396 SmallVector<OperandBundleDef, 2> OpBundles;
2397 CI->getOperandBundlesAsDefs(OpBundles);
2398 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002399 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400
Ahmed Bougachad765a822016-04-27 19:04:35 +00002401 // First, check that this is a known library functions and that the prototype
2402 // is correct.
2403 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002404 return nullptr;
2405
2406 // We never change the calling convention.
2407 if (!ignoreCallingConv(Func) && !isCallingConvC)
2408 return nullptr;
2409
2410 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002411 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002412 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002413 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002415 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002417 case LibFunc_stpcpy_chk:
2418 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002419 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002420 case LibFunc_stpncpy_chk:
2421 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002422 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002423 default:
2424 break;
2425 }
2426 return nullptr;
2427}
2428
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002429FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2430 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2431 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}