blob: 4818939824e3a6a879aa1f9c1b3bc266102e9037 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000031#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000034#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000040 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
41 cl::init(false),
42 cl::desc("Enable unsafe double to float "
43 "shrinking for math lib calls"));
44
45
Meador Ingedf796f82012-10-13 16:45:24 +000046//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000047// Helper Functions
48//===----------------------------------------------------------------------===//
49
David L. Jonesd21529f2017-01-23 23:16:46 +000050static bool ignoreCallingConv(LibFunc Func) {
51 return Func == LibFunc_abs || Func == LibFunc_labs ||
52 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000053}
54
Sam Parker214f7bf2016-09-13 12:10:14 +000055static bool isCallingConvCCompatible(CallInst *CI) {
56 switch(CI->getCallingConv()) {
57 default:
58 return false;
59 case llvm::CallingConv::C:
60 return true;
61 case llvm::CallingConv::ARM_APCS:
62 case llvm::CallingConv::ARM_AAPCS:
63 case llvm::CallingConv::ARM_AAPCS_VFP: {
64
65 // The iOS ABI diverges from the standard in some cases, so for now don't
66 // try to simplify those calls.
67 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
68 return false;
69
70 auto *FuncTy = CI->getFunctionType();
71
72 if (!FuncTy->getReturnType()->isPointerTy() &&
73 !FuncTy->getReturnType()->isIntegerTy() &&
74 !FuncTy->getReturnType()->isVoidTy())
75 return false;
76
77 for (auto Param : FuncTy->params()) {
78 if (!Param->isPointerTy() && !Param->isIntegerTy())
79 return false;
80 }
81 return true;
82 }
83 }
84 return false;
85}
86
Sanjay Pateld707db92015-12-31 16:10:49 +000087/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000088static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000089 for (User *U : V->users()) {
90 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000091 if (IC->isEquality())
92 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
93 if (C->isNullValue())
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Sanjay Pateld707db92015-12-31 16:10:49 +0000101/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +0000102static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000103 for (User *U : V->users()) {
104 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +0000105 if (IC->isEquality() && IC->getOperand(1) == With)
106 continue;
107 // Unknown instruction.
108 return false;
109 }
110 return true;
111}
112
Meador Inge08ca1152012-11-26 20:37:20 +0000113static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000114 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000115 return OI->getType()->isFloatingPointTy();
116 });
Meador Inge08ca1152012-11-26 20:37:20 +0000117}
118
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000119/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000120/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000121static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000122 LibFunc DoubleFn, LibFunc FloatFn,
123 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000124 switch (Ty->getTypeID()) {
125 case Type::FloatTyID:
126 return TLI->has(FloatFn);
127 case Type::DoubleTyID:
128 return TLI->has(DoubleFn);
129 default:
130 return TLI->has(LongDoubleFn);
131 }
132}
133
Meador Inged589ac62012-10-31 03:33:06 +0000134//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000135// String and Memory Library Call Optimizations
136//===----------------------------------------------------------------------===//
137
Chris Bienemanad070d02014-09-17 20:55:46 +0000138Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000139 // Extract some information from the instruction
140 Value *Dst = CI->getArgOperand(0);
141 Value *Src = CI->getArgOperand(1);
142
143 // See if we can get the length of the input string.
144 uint64_t Len = GetStringLength(Src);
145 if (Len == 0)
146 return nullptr;
147 --Len; // Unbias length.
148
149 // Handle the simple, do-nothing case: strcat(x, "") -> x
150 if (Len == 0)
151 return Dst;
152
Chris Bienemanad070d02014-09-17 20:55:46 +0000153 return emitStrLenMemCpy(Src, Dst, Len, B);
154}
155
156Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
157 IRBuilder<> &B) {
158 // We need to find the end of the destination string. That's where the
159 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000160 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000161 if (!DstLen)
162 return nullptr;
163
164 // Now that we have the destination's length, we must index into the
165 // destination's pointer to get the actual memcpy destination (end of
166 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000167 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000168
169 // We have enough information to now generate the memcpy call to do the
170 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171 B.CreateMemCpy(CpyDst, Src,
172 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000173 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000174 return Dst;
175}
176
177Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000178 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000179 Value *Dst = CI->getArgOperand(0);
180 Value *Src = CI->getArgOperand(1);
181 uint64_t Len;
182
Sanjay Pateld707db92015-12-31 16:10:49 +0000183 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000184 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
185 Len = LengthArg->getZExtValue();
186 else
187 return nullptr;
188
189 // See if we can get the length of the input string.
190 uint64_t SrcLen = GetStringLength(Src);
191 if (SrcLen == 0)
192 return nullptr;
193 --SrcLen; // Unbias length.
194
195 // Handle the simple, do-nothing cases:
196 // strncat(x, "", c) -> x
197 // strncat(x, c, 0) -> x
198 if (SrcLen == 0 || Len == 0)
199 return Dst;
200
Sanjay Pateld707db92015-12-31 16:10:49 +0000201 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000202 if (Len < SrcLen)
203 return nullptr;
204
205 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000206 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
208}
209
210Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
211 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000212 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000213 Value *SrcStr = CI->getArgOperand(0);
214
215 // If the second operand is non-constant, see if we can compute the length
216 // of the input string and turn this into memchr.
217 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
218 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000219 uint64_t Len = GetStringLength(SrcStr);
220 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
221 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000222
Sanjay Pateld3112a52016-01-19 19:46:10 +0000223 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
225 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000226 }
227
Chris Bienemanad070d02014-09-17 20:55:46 +0000228 // Otherwise, the character is a constant, see if the first argument is
229 // a string literal. If so, we can constant fold.
230 StringRef Str;
231 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000233 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000234 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000235 return nullptr;
236 }
237
238 // Compute the offset, make sure to handle the case when we're searching for
239 // zero (a weird way to spell strlen).
240 size_t I = (0xFF & CharC->getSExtValue()) == 0
241 ? Str.size()
242 : Str.find(CharC->getSExtValue());
243 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
244 return Constant::getNullValue(CI->getType());
245
246 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000247 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000248}
249
250Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000251 Value *SrcStr = CI->getArgOperand(0);
252 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
253
254 // Cannot fold anything if we're not looking for a constant.
255 if (!CharC)
256 return nullptr;
257
258 StringRef Str;
259 if (!getConstantStringInfo(SrcStr, Str)) {
260 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000261 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000262 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000263 return nullptr;
264 }
265
266 // Compute the offset.
267 size_t I = (0xFF & CharC->getSExtValue()) == 0
268 ? Str.size()
269 : Str.rfind(CharC->getSExtValue());
270 if (I == StringRef::npos) // Didn't find the char. Return null.
271 return Constant::getNullValue(CI->getType());
272
273 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000274 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000275}
276
277Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000278 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
279 if (Str1P == Str2P) // strcmp(x,x) -> 0
280 return ConstantInt::get(CI->getType(), 0);
281
282 StringRef Str1, Str2;
283 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
284 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
285
286 // strcmp(x, y) -> cnst (if both x and y are constant strings)
287 if (HasStr1 && HasStr2)
288 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
289
290 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
291 return B.CreateNeg(
292 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
293
294 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
295 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
296
297 // strcmp(P, "x") -> memcmp(P, "x", 2)
298 uint64_t Len1 = GetStringLength(Str1P);
299 uint64_t Len2 = GetStringLength(Str2P);
300 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000301 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000302 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000303 std::min(Len1, Len2)),
304 B, DL, TLI);
305 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000306
Chris Bienemanad070d02014-09-17 20:55:46 +0000307 return nullptr;
308}
309
310Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000311 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
312 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
313 return ConstantInt::get(CI->getType(), 0);
314
315 // Get the length argument if it is constant.
316 uint64_t Length;
317 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
318 Length = LengthArg->getZExtValue();
319 else
320 return nullptr;
321
322 if (Length == 0) // strncmp(x,y,0) -> 0
323 return ConstantInt::get(CI->getType(), 0);
324
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000326 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000327
328 StringRef Str1, Str2;
329 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
330 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
331
332 // strncmp(x, y) -> cnst (if both x and y are constant strings)
333 if (HasStr1 && HasStr2) {
334 StringRef SubStr1 = Str1.substr(0, Length);
335 StringRef SubStr2 = Str2.substr(0, Length);
336 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
337 }
338
339 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
340 return B.CreateNeg(
341 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
342
343 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
344 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
345
346 return nullptr;
347}
348
349Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000350 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
351 if (Dst == Src) // strcpy(x,x) -> x
352 return Src;
353
Chris Bienemanad070d02014-09-17 20:55:46 +0000354 // See if we can get the length of the input string.
355 uint64_t Len = GetStringLength(Src);
356 if (Len == 0)
357 return nullptr;
358
359 // We have enough information to now generate the memcpy call to do the
360 // copy for us. Make a memcpy to copy the nul byte with align = 1.
361 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000362 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000363 return Dst;
364}
365
366Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
367 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
369 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000370 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000371 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000372 }
373
374 // See if we can get the length of the input string.
375 uint64_t Len = GetStringLength(Src);
376 if (Len == 0)
377 return nullptr;
378
Davide Italianob7487e62015-11-02 23:07:14 +0000379 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000381 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
382 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000383
384 // We have enough information to now generate the memcpy call to do the
385 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000386 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000387 return DstEnd;
388}
389
390Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
391 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000392 Value *Dst = CI->getArgOperand(0);
393 Value *Src = CI->getArgOperand(1);
394 Value *LenOp = CI->getArgOperand(2);
395
396 // See if we can get the length of the input string.
397 uint64_t SrcLen = GetStringLength(Src);
398 if (SrcLen == 0)
399 return nullptr;
400 --SrcLen;
401
402 if (SrcLen == 0) {
403 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
404 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000405 return Dst;
406 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000407
Chris Bienemanad070d02014-09-17 20:55:46 +0000408 uint64_t Len;
409 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
410 Len = LengthArg->getZExtValue();
411 else
412 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000413
Chris Bienemanad070d02014-09-17 20:55:46 +0000414 if (Len == 0)
415 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000416
Chris Bienemanad070d02014-09-17 20:55:46 +0000417 // Let strncpy handle the zero padding
418 if (Len > SrcLen + 1)
419 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000420
Davide Italianob7487e62015-11-02 23:07:14 +0000421 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000422 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000423 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000424
Chris Bienemanad070d02014-09-17 20:55:46 +0000425 return Dst;
426}
Meador Inge7fb2f732012-10-13 16:45:32 +0000427
Chris Bienemanad070d02014-09-17 20:55:46 +0000428Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000429 Value *Src = CI->getArgOperand(0);
430
431 // Constant folding: strlen("xyz") -> 3
432 if (uint64_t Len = GetStringLength(Src))
433 return ConstantInt::get(CI->getType(), Len - 1);
434
David L Kreitzer752c1442016-04-13 14:31:06 +0000435 // If s is a constant pointer pointing to a string literal, we can fold
436 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
437 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
438 // We only try to simplify strlen when the pointer s points to an array
439 // of i8. Otherwise, we would need to scale the offset x before doing the
440 // subtraction. This will make the optimization more complex, and it's not
441 // very useful because calling strlen for a pointer of other types is
442 // very uncommon.
443 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
444 if (!isGEPBasedOnPointerToString(GEP))
445 return nullptr;
446
447 StringRef Str;
448 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
449 size_t NullTermIdx = Str.find('\0');
450
451 // If the string does not have '\0', leave it to strlen to compute
452 // its length.
453 if (NullTermIdx == StringRef::npos)
454 return nullptr;
455
456 Value *Offset = GEP->getOperand(2);
457 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
458 APInt KnownZero(BitWidth, 0);
459 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000460 computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
461 nullptr);
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 KnownZero.flipAllBits();
463 size_t ArrSize =
464 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
465
466 // KnownZero's bits are flipped, so zeros in KnownZero now represent
467 // bits known to be zeros in Offset, and ones in KnowZero represent
468 // bits unknown in Offset. Therefore, Offset is known to be in range
469 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
470 // unsigned-less-than NullTermIdx.
471 //
472 // If Offset is not provably in the range [0, NullTermIdx], we can still
473 // optimize if we can prove that the program has undefined behavior when
474 // Offset is outside that range. That is the case when GEP->getOperand(0)
475 // is a pointer to an object whose memory extent is NullTermIdx+1.
476 if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
477 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
478 NullTermIdx == ArrSize - 1))
479 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
480 Offset);
481 }
482
483 return nullptr;
484 }
485
Chris Bienemanad070d02014-09-17 20:55:46 +0000486 // strlen(x?"foo":"bars") --> x ? 3 : 4
487 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
488 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
489 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
490 if (LenTrue && LenFalse) {
491 Function *Caller = CI->getParent()->getParent();
492 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
493 SI->getDebugLoc(),
494 "folded strlen(select) to select of constants");
495 return B.CreateSelect(SI->getCondition(),
496 ConstantInt::get(CI->getType(), LenTrue - 1),
497 ConstantInt::get(CI->getType(), LenFalse - 1));
498 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000499 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000500
Chris Bienemanad070d02014-09-17 20:55:46 +0000501 // strlen(x) != 0 --> *x != 0
502 // strlen(x) == 0 --> *x == 0
503 if (isOnlyUsedInZeroEqualityComparison(CI))
504 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000505
Chris Bienemanad070d02014-09-17 20:55:46 +0000506 return nullptr;
507}
Meador Inge17418502012-10-13 16:45:37 +0000508
Chris Bienemanad070d02014-09-17 20:55:46 +0000509Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000510 StringRef S1, S2;
511 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
512 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000513
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000514 // strpbrk(s, "") -> nullptr
515 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
517 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000518
Chris Bienemanad070d02014-09-17 20:55:46 +0000519 // Constant folding.
520 if (HasS1 && HasS2) {
521 size_t I = S1.find_first_of(S2);
522 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000523 return Constant::getNullValue(CI->getType());
524
Sanjay Pateld707db92015-12-31 16:10:49 +0000525 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
526 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000527 }
Meador Inge17418502012-10-13 16:45:37 +0000528
Chris Bienemanad070d02014-09-17 20:55:46 +0000529 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000530 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000531 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000532
533 return nullptr;
534}
535
536Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000537 Value *EndPtr = CI->getArgOperand(1);
538 if (isa<ConstantPointerNull>(EndPtr)) {
539 // With a null EndPtr, this function won't capture the main argument.
540 // It would be readonly too, except that it still may write to errno.
541 CI->addAttribute(1, Attribute::NoCapture);
542 }
543
544 return nullptr;
545}
546
547Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000548 StringRef S1, S2;
549 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
550 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
551
552 // strspn(s, "") -> 0
553 // strspn("", s) -> 0
554 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
555 return Constant::getNullValue(CI->getType());
556
557 // Constant folding.
558 if (HasS1 && HasS2) {
559 size_t Pos = S1.find_first_not_of(S2);
560 if (Pos == StringRef::npos)
561 Pos = S1.size();
562 return ConstantInt::get(CI->getType(), Pos);
563 }
564
565 return nullptr;
566}
567
568Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000569 StringRef S1, S2;
570 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
571 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
572
573 // strcspn("", s) -> 0
574 if (HasS1 && S1.empty())
575 return Constant::getNullValue(CI->getType());
576
577 // Constant folding.
578 if (HasS1 && HasS2) {
579 size_t Pos = S1.find_first_of(S2);
580 if (Pos == StringRef::npos)
581 Pos = S1.size();
582 return ConstantInt::get(CI->getType(), Pos);
583 }
584
585 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000587 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000588
589 return nullptr;
590}
591
592Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000593 // fold strstr(x, x) -> x.
594 if (CI->getArgOperand(0) == CI->getArgOperand(1))
595 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
596
597 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000598 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000599 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000600 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000601 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000602 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000603 StrLen, B, DL, TLI);
604 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000605 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
607 ICmpInst *Old = cast<ICmpInst>(*UI++);
608 Value *Cmp =
609 B.CreateICmp(Old->getPredicate(), StrNCmp,
610 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
611 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000612 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000613 return CI;
614 }
Meador Inge17418502012-10-13 16:45:37 +0000615
Chris Bienemanad070d02014-09-17 20:55:46 +0000616 // See if either input string is a constant string.
617 StringRef SearchStr, ToFindStr;
618 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
619 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
620
621 // fold strstr(x, "") -> x.
622 if (HasStr2 && ToFindStr.empty())
623 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
624
625 // If both strings are known, constant fold it.
626 if (HasStr1 && HasStr2) {
627 size_t Offset = SearchStr.find(ToFindStr);
628
629 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000630 return Constant::getNullValue(CI->getType());
631
Chris Bienemanad070d02014-09-17 20:55:46 +0000632 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000633 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
635 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000636 }
Meador Inge17418502012-10-13 16:45:37 +0000637
Chris Bienemanad070d02014-09-17 20:55:46 +0000638 // fold strstr(x, "y") -> strchr(x, 'y').
639 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000640 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
642 }
643 return nullptr;
644}
Meador Inge40b6fac2012-10-15 03:47:37 +0000645
Benjamin Kramer691363e2015-03-21 15:36:21 +0000646Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000647 Value *SrcStr = CI->getArgOperand(0);
648 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
649 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
650
651 // memchr(x, y, 0) -> null
652 if (LenC && LenC->isNullValue())
653 return Constant::getNullValue(CI->getType());
654
Benjamin Kramer7857d722015-03-21 21:09:33 +0000655 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000656 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000657 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000658 return nullptr;
659
660 // Truncate the string to LenC. If Str is smaller than LenC we will still only
661 // scan the string, as reading past the end of it is undefined and we can just
662 // return null if we don't find the char.
663 Str = Str.substr(0, LenC->getZExtValue());
664
Benjamin Kramer7857d722015-03-21 21:09:33 +0000665 // If the char is variable but the input str and length are not we can turn
666 // this memchr call into a simple bit field test. Of course this only works
667 // when the return value is only checked against null.
668 //
669 // It would be really nice to reuse switch lowering here but we can't change
670 // the CFG at this point.
671 //
672 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
673 // after bounds check.
674 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000675 unsigned char Max =
676 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
677 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000678
679 // Make sure the bit field we're about to create fits in a register on the
680 // target.
681 // FIXME: On a 64 bit architecture this prevents us from using the
682 // interesting range of alpha ascii chars. We could do better by emitting
683 // two bitfields or shifting the range by 64 if no lower chars are used.
684 if (!DL.fitsInLegalInteger(Max + 1))
685 return nullptr;
686
687 // For the bit field use a power-of-2 type with at least 8 bits to avoid
688 // creating unnecessary illegal types.
689 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
690
691 // Now build the bit field.
692 APInt Bitfield(Width, 0);
693 for (char C : Str)
694 Bitfield.setBit((unsigned char)C);
695 Value *BitfieldC = B.getInt(Bitfield);
696
697 // First check that the bit field access is within bounds.
698 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
699 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
700 "memchr.bounds");
701
702 // Create code that checks if the given bit is set in the field.
703 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
704 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
705
706 // Finally merge both checks and cast to pointer type. The inttoptr
707 // implicitly zexts the i1 to intptr type.
708 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
709 }
710
711 // Check if all arguments are constants. If so, we can constant fold.
712 if (!CharC)
713 return nullptr;
714
Benjamin Kramer691363e2015-03-21 15:36:21 +0000715 // Compute the offset.
716 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
717 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
718 return Constant::getNullValue(CI->getType());
719
720 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000721 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000722}
723
Chris Bienemanad070d02014-09-17 20:55:46 +0000724Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000725 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000726
Chris Bienemanad070d02014-09-17 20:55:46 +0000727 if (LHS == RHS) // memcmp(s,s,x) -> 0
728 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000729
Chris Bienemanad070d02014-09-17 20:55:46 +0000730 // Make sure we have a constant length.
731 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
732 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000733 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000734 uint64_t Len = LenC->getZExtValue();
735
736 if (Len == 0) // memcmp(s1,s2,0) -> 0
737 return Constant::getNullValue(CI->getType());
738
739 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
740 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000741 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000743 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000744 CI->getType(), "rhsv");
745 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000746 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000747
Chad Rosierdc655322015-08-28 18:30:18 +0000748 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
749 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
750
751 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
752 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
753
754 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
755 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
756
757 Type *LHSPtrTy =
758 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
759 Type *RHSPtrTy =
760 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
761
Sanjay Pateld707db92015-12-31 16:10:49 +0000762 Value *LHSV =
763 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
764 Value *RHSV =
765 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000766
767 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
768 }
769 }
770
Chris Bienemanad070d02014-09-17 20:55:46 +0000771 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
772 StringRef LHSStr, RHSStr;
773 if (getConstantStringInfo(LHS, LHSStr) &&
774 getConstantStringInfo(RHS, RHSStr)) {
775 // Make sure we're not reading out-of-bounds memory.
776 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000777 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000778 // Fold the memcmp and normalize the result. This way we get consistent
779 // results across multiple platforms.
780 uint64_t Ret = 0;
781 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
782 if (Cmp < 0)
783 Ret = -1;
784 else if (Cmp > 0)
785 Ret = 1;
786 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000787 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000788
Chris Bienemanad070d02014-09-17 20:55:46 +0000789 return nullptr;
790}
Meador Inge9a6a1902012-10-31 00:20:56 +0000791
Chris Bienemanad070d02014-09-17 20:55:46 +0000792Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000793 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
794 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000795 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000796 return CI->getArgOperand(0);
797}
Meador Inge05a625a2012-10-31 14:58:26 +0000798
Chris Bienemanad070d02014-09-17 20:55:46 +0000799Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000800 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
801 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000802 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000803 return CI->getArgOperand(0);
804}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000805
Sanjay Patel980b2802016-01-26 16:17:24 +0000806// TODO: Does this belong in BuildLibCalls or should all of those similar
807// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000808static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000809 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000810 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000811 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
812 return nullptr;
813
814 Module *M = B.GetInsertBlock()->getModule();
815 const DataLayout &DL = M->getDataLayout();
816 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
817 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000818 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000819 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
820
821 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
822 CI->setCallingConv(F->getCallingConv());
823
824 return CI;
825}
826
827/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
828static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
829 const TargetLibraryInfo &TLI) {
830 // This has to be a memset of zeros (bzero).
831 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
832 if (!FillValue || FillValue->getZExtValue() != 0)
833 return nullptr;
834
835 // TODO: We should handle the case where the malloc has more than one use.
836 // This is necessary to optimize common patterns such as when the result of
837 // the malloc is checked against null or when a memset intrinsic is used in
838 // place of a memset library call.
839 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
840 if (!Malloc || !Malloc->hasOneUse())
841 return nullptr;
842
843 // Is the inner call really malloc()?
844 Function *InnerCallee = Malloc->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +0000845 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000846 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000847 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000848 return nullptr;
849
Sanjay Patel980b2802016-01-26 16:17:24 +0000850 // The memset must cover the same number of bytes that are malloc'd.
851 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
852 return nullptr;
853
854 // Replace the malloc with a calloc. We need the data layout to know what the
855 // actual size of a 'size_t' parameter is.
856 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
857 const DataLayout &DL = Malloc->getModule()->getDataLayout();
858 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
859 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
860 Malloc->getArgOperand(0), Malloc->getAttributes(),
861 B, TLI);
862 if (!Calloc)
863 return nullptr;
864
865 Malloc->replaceAllUsesWith(Calloc);
866 Malloc->eraseFromParent();
867
868 return Calloc;
869}
870
Chris Bienemanad070d02014-09-17 20:55:46 +0000871Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000872 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
873 return Calloc;
874
Chris Bienemanad070d02014-09-17 20:55:46 +0000875 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
876 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
877 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
878 return CI->getArgOperand(0);
879}
Meador Inged4825782012-11-11 06:49:03 +0000880
Meador Inge193e0352012-11-13 04:16:17 +0000881//===----------------------------------------------------------------------===//
882// Math Library Optimizations
883//===----------------------------------------------------------------------===//
884
Matthias Braund34e4d22014-12-03 21:46:33 +0000885/// Return a variant of Val with float type.
886/// Currently this works in two cases: If Val is an FPExtension of a float
887/// value to something bigger, simply return the operand.
888/// If Val is a ConstantFP but can be converted to a float ConstantFP without
889/// loss of precision do so.
890static Value *valueHasFloatPrecision(Value *Val) {
891 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
892 Value *Op = Cast->getOperand(0);
893 if (Op->getType()->isFloatTy())
894 return Op;
895 }
896 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
897 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000898 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000899 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000900 &losesInfo);
901 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000902 return ConstantFP::get(Const->getContext(), F);
903 }
904 return nullptr;
905}
906
Sanjay Patel4e971da2016-01-21 18:01:57 +0000907/// Shrink double -> float for unary functions like 'floor'.
908static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
909 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000910 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000911 // We know this libcall has a valid prototype, but we don't know which.
912 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000913 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000914
Chris Bienemanad070d02014-09-17 20:55:46 +0000915 if (CheckRetType) {
916 // Check if all the uses for function like 'sin' are converted to float.
917 for (User *U : CI->users()) {
918 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
919 if (!Cast || !Cast->getType()->isFloatTy())
920 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000921 }
Meador Inge193e0352012-11-13 04:16:17 +0000922 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000923
924 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000925 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
926 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000927 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000928
Andrew Ng1606fc02017-04-25 12:36:14 +0000929 // If call isn't an intrinsic, check that it isn't within a function with the
930 // same name as the float version of this call.
931 //
932 // e.g. inline float expf(float val) { return (float) exp((double) val); }
933 //
934 // A similar such definition exists in the MinGW-w64 math.h header file which
935 // when compiled with -O2 -ffast-math causes the generation of infinite loops
936 // where expf is called.
937 if (!Callee->isIntrinsic()) {
938 const Function *F = CI->getFunction();
939 StringRef FName = F->getName();
940 StringRef CalleeName = Callee->getName();
941 if ((FName.size() == (CalleeName.size() + 1)) &&
942 (FName.back() == 'f') &&
943 FName.startswith(CalleeName))
944 return nullptr;
945 }
946
Sanjay Patelaa231142015-12-31 21:52:31 +0000947 // Propagate fast-math flags from the existing call to the new call.
948 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000949 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000950
951 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000952 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000953 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000954 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000955 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
956 V = B.CreateCall(F, V);
957 } else {
958 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000959 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000960 }
961
Chris Bienemanad070d02014-09-17 20:55:46 +0000962 return B.CreateFPExt(V, B.getDoubleTy());
963}
Meador Inge193e0352012-11-13 04:16:17 +0000964
Matt Arsenault954a6242017-01-23 23:55:08 +0000965// Replace a libcall \p CI with a call to intrinsic \p IID
966static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
967 // Propagate fast-math flags from the existing call to the new call.
968 IRBuilder<>::FastMathFlagGuard Guard(B);
969 B.setFastMathFlags(CI->getFastMathFlags());
970
971 Module *M = CI->getModule();
972 Value *V = CI->getArgOperand(0);
973 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
974 CallInst *NewCall = B.CreateCall(F, V);
975 NewCall->takeName(CI);
976 return NewCall;
977}
978
Sanjay Patel4e971da2016-01-21 18:01:57 +0000979/// Shrink double -> float for binary functions like 'fmin/fmax'.
980static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000981 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000982 // We know this libcall has a valid prototype, but we don't know which.
983 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000984 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000985
Chris Bienemanad070d02014-09-17 20:55:46 +0000986 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000987 // or fmin(1.0, (double)floatval), then we convert it to fminf.
988 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
989 if (V1 == nullptr)
990 return nullptr;
991 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
992 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000993 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000994
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000995 // Propagate fast-math flags from the existing call to the new call.
996 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000997 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000998
Chris Bienemanad070d02014-09-17 20:55:46 +0000999 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001000 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001001 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001002 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001003 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001004 return B.CreateFPExt(V, B.getDoubleTy());
1005}
1006
1007Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1008 Function *Callee = CI->getCalledFunction();
1009 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001010 StringRef Name = Callee->getName();
1011 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001012 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001013
Chris Bienemanad070d02014-09-17 20:55:46 +00001014 // cos(-x) -> cos(x)
1015 Value *Op1 = CI->getArgOperand(0);
1016 if (BinaryOperator::isFNeg(Op1)) {
1017 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1018 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1019 }
1020 return Ret;
1021}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001022
Weiming Zhao82130722015-12-04 22:00:47 +00001023static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1024 // Multiplications calculated using Addition Chains.
1025 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1026
1027 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1028
1029 if (InnerChain[Exp])
1030 return InnerChain[Exp];
1031
1032 static const unsigned AddChain[33][2] = {
1033 {0, 0}, // Unused.
1034 {0, 0}, // Unused (base case = pow1).
1035 {1, 1}, // Unused (pre-computed).
1036 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1037 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1038 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1039 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1040 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1041 };
1042
1043 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1044 getPow(InnerChain, AddChain[Exp][1], B));
1045 return InnerChain[Exp];
1046}
1047
Chris Bienemanad070d02014-09-17 20:55:46 +00001048Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1049 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001050 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001051 StringRef Name = Callee->getName();
1052 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001053 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001054
Chris Bienemanad070d02014-09-17 20:55:46 +00001055 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001056
1057 // pow(1.0, x) -> 1.0
1058 if (match(Op1, m_SpecificFP(1.0)))
1059 return Op1;
1060 // pow(2.0, x) -> llvm.exp2(x)
1061 if (match(Op1, m_SpecificFP(2.0))) {
1062 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1063 CI->getType());
1064 return B.CreateCall(Exp2, Op2, "exp2");
1065 }
1066
1067 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1068 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001069 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001070 // pow(10.0, x) -> exp10(x)
1071 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001072 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1073 LibFunc_exp10l))
1074 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001075 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001076 }
1077
Sanjay Patel6002e782016-01-12 17:30:37 +00001078 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001079 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001080 // We enable these only with fast-math. Besides rounding differences, the
1081 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001082 // Example: x = 1000, y = 0.001.
1083 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001084 auto *OpC = dyn_cast<CallInst>(Op1);
1085 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001086 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001087 Function *OpCCallee = OpC->getCalledFunction();
1088 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001089 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001090 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001091 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001092 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001093 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001094 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001095 }
1096 }
1097
Chris Bienemanad070d02014-09-17 20:55:46 +00001098 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1099 if (!Op2C)
1100 return Ret;
1101
1102 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1103 return ConstantFP::get(CI->getType(), 1.0);
1104
Davide Italiano472684e2017-01-09 21:55:23 +00001105 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001106 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1107 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001108 // If -ffast-math:
1109 // pow(x, -0.5) -> 1.0 / sqrt(x)
1110 if (CI->hasUnsafeAlgebra()) {
1111 IRBuilder<>::FastMathFlagGuard Guard(B);
1112 B.setFastMathFlags(CI->getFastMathFlags());
1113
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001114 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1115 // intrinsic, so we match errno semantics. We also should check that the
1116 // target can in fact lower the sqrt intrinsic -- we currently have no way
1117 // to ask this question other than asking whether the target has a sqrt
1118 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001119 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001120 Callee->getAttributes());
1121
1122 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1123 }
1124 }
1125
Chris Bienemanad070d02014-09-17 20:55:46 +00001126 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001127 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1128 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001129
1130 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001131 if (CI->hasUnsafeAlgebra()) {
1132 IRBuilder<>::FastMathFlagGuard Guard(B);
1133 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001134
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001135 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1136 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001137 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001138 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001139 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001140
Chris Bienemanad070d02014-09-17 20:55:46 +00001141 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1142 // This is faster than calling pow, and still handles negative zero
1143 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001144 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1145 Value *Inf = ConstantFP::getInfinity(CI->getType());
1146 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001147
1148 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1149 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001150 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001151
1152 Module *M = Callee->getParent();
1153 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1154 CI->getType());
1155 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1156
Chris Bienemanad070d02014-09-17 20:55:46 +00001157 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1158 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1159 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001160 }
1161
Chris Bienemanad070d02014-09-17 20:55:46 +00001162 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1163 return Op1;
1164 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1165 return B.CreateFMul(Op1, Op1, "pow2");
1166 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1167 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001168
1169 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001170 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001171 APFloat V = abs(Op2C->getValueAPF());
1172 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1173 // This transformation applies to integer exponents only.
1174 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1175 !V.isInteger())
1176 return nullptr;
1177
Davide Italianof8711f02017-01-10 18:02:05 +00001178 // Propagate fast math flags.
1179 IRBuilder<>::FastMathFlagGuard Guard(B);
1180 B.setFastMathFlags(CI->getFastMathFlags());
1181
Weiming Zhao82130722015-12-04 22:00:47 +00001182 // We will memoize intermediate products of the Addition Chain.
1183 Value *InnerChain[33] = {nullptr};
1184 InnerChain[1] = Op1;
1185 InnerChain[2] = B.CreateFMul(Op1, Op1);
1186
1187 // We cannot readily convert a non-double type (like float) to a double.
1188 // So we first convert V to something which could be converted to double.
1189 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001190 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001191
Weiming Zhao82130722015-12-04 22:00:47 +00001192 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1193 // For negative exponents simply compute the reciprocal.
1194 if (Op2C->isNegative())
1195 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1196 return FMul;
1197 }
1198
Chris Bienemanad070d02014-09-17 20:55:46 +00001199 return nullptr;
1200}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001201
Chris Bienemanad070d02014-09-17 20:55:46 +00001202Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1203 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001204 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001205 StringRef Name = Callee->getName();
1206 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001207 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001208
Chris Bienemanad070d02014-09-17 20:55:46 +00001209 Value *Op = CI->getArgOperand(0);
1210 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1211 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001212 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001213 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001214 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001215 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001216 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001217
1218 if (TLI->has(LdExp)) {
1219 Value *LdExpArg = nullptr;
1220 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1221 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1222 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1223 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1224 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1225 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1226 }
1227
1228 if (LdExpArg) {
1229 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1230 if (!Op->getType()->isFloatTy())
1231 One = ConstantExpr::getFPExtend(One, Op->getType());
1232
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001233 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001234 Value *NewCallee =
1235 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001236 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001237 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001238 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1239 CI->setCallingConv(F->getCallingConv());
1240
1241 return CI;
1242 }
1243 }
1244 return Ret;
1245}
1246
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001247Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001248 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001249 // If we can shrink the call to a float function rather than a double
1250 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001251 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001252 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1253 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001254 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001255
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001256 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001257 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001258 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001259 // Unsafe algebra sets all fast-math-flags to true.
1260 FMF.setUnsafeAlgebra();
1261 } else {
1262 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001263 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001264 return nullptr;
1265 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1266 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001267 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001268 // might be impractical."
1269 FMF.setNoSignedZeros();
1270 FMF.setNoNaNs();
1271 }
Sanjay Patela2528152016-01-12 18:03:37 +00001272 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001273
1274 // We have a relaxed floating-point environment. We can ignore NaN-handling
1275 // and transform to a compare and select. We do not have to consider errno or
1276 // exceptions, because fmin/fmax do not have those.
1277 Value *Op0 = CI->getArgOperand(0);
1278 Value *Op1 = CI->getArgOperand(1);
1279 Value *Cmp = Callee->getName().startswith("fmin") ?
1280 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1281 return B.CreateSelect(Cmp, Op0, Op1);
1282}
1283
Davide Italianob8b71332015-11-29 20:58:04 +00001284Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1285 Function *Callee = CI->getCalledFunction();
1286 Value *Ret = nullptr;
1287 StringRef Name = Callee->getName();
1288 if (UnsafeFPShrink && hasFloatVersion(Name))
1289 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001290
Sanjay Patele896ede2016-01-11 23:31:48 +00001291 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001292 return Ret;
1293 Value *Op1 = CI->getArgOperand(0);
1294 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001295
1296 // The earlier call must also be unsafe in order to do these transforms.
1297 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001298 return Ret;
1299
1300 // log(pow(x,y)) -> y*log(x)
1301 // This is only applicable to log, log2, log10.
1302 if (Name != "log" && Name != "log2" && Name != "log10")
1303 return Ret;
1304
1305 IRBuilder<>::FastMathFlagGuard Guard(B);
1306 FastMathFlags FMF;
1307 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001308 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001309
David L. Jonesd21529f2017-01-23 23:16:46 +00001310 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001311 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001312 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001313 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001314 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001315 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001316 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001317
1318 // log(exp2(y)) -> y*log(2)
1319 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001320 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001321 return B.CreateFMul(
1322 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001323 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001324 Callee->getName(), B, Callee->getAttributes()),
1325 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001326 return Ret;
1327}
1328
Sanjay Patelc699a612014-10-16 18:48:17 +00001329Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1330 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001331 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001332 // TODO: Once we have a way (other than checking for the existince of the
1333 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1334 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001335 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001336 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001337 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001338
1339 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001340 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001341
Sanjay Patelc2d64612016-01-06 20:52:21 +00001342 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1343 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1344 return Ret;
1345
1346 // We're looking for a repeated factor in a multiplication tree,
1347 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001348 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001349 Value *Op0 = I->getOperand(0);
1350 Value *Op1 = I->getOperand(1);
1351 Value *RepeatOp = nullptr;
1352 Value *OtherOp = nullptr;
1353 if (Op0 == Op1) {
1354 // Simple match: the operands of the multiply are identical.
1355 RepeatOp = Op0;
1356 } else {
1357 // Look for a more complicated pattern: one of the operands is itself
1358 // a multiply, so search for a common factor in that multiply.
1359 // Note: We don't bother looking any deeper than this first level or for
1360 // variations of this pattern because instcombine's visitFMUL and/or the
1361 // reassociation pass should give us this form.
1362 Value *OtherMul0, *OtherMul1;
1363 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1364 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001365 if (OtherMul0 == OtherMul1 &&
1366 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001367 // Matched: sqrt((x * x) * z)
1368 RepeatOp = OtherMul0;
1369 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001370 }
1371 }
1372 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001373 if (!RepeatOp)
1374 return Ret;
1375
1376 // Fast math flags for any created instructions should match the sqrt
1377 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001378 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001379 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001380
Sanjay Patelc2d64612016-01-06 20:52:21 +00001381 // If we found a repeated factor, hoist it out of the square root and
1382 // replace it with the fabs of that factor.
1383 Module *M = Callee->getParent();
1384 Type *ArgType = I->getType();
1385 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1386 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1387 if (OtherOp) {
1388 // If we found a non-repeated factor, we still need to get its square
1389 // root. We then multiply that by the value that was simplified out
1390 // of the square root calculation.
1391 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1392 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1393 return B.CreateFMul(FabsCall, SqrtCall);
1394 }
1395 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001396}
1397
Sanjay Patelcddcd722016-01-06 19:23:35 +00001398// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001399Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1400 Function *Callee = CI->getCalledFunction();
1401 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001402 StringRef Name = Callee->getName();
1403 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001404 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001405
Davide Italiano51507d22015-11-04 23:36:56 +00001406 Value *Op1 = CI->getArgOperand(0);
1407 auto *OpC = dyn_cast<CallInst>(Op1);
1408 if (!OpC)
1409 return Ret;
1410
Sanjay Patelcddcd722016-01-06 19:23:35 +00001411 // Both calls must allow unsafe optimizations in order to remove them.
1412 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1413 return Ret;
1414
Davide Italiano51507d22015-11-04 23:36:56 +00001415 // tan(atan(x)) -> x
1416 // tanf(atanf(x)) -> x
1417 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001418 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001419 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001420 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001421 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1422 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1423 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001424 Ret = OpC->getArgOperand(0);
1425 return Ret;
1426}
1427
Sanjay Patel57747212016-01-21 23:38:43 +00001428static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001429 // We can only hope to do anything useful if we can ignore things like errno
1430 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001431 // We already checked the prototype.
1432 return CI->hasFnAttr(Attribute::NoUnwind) &&
1433 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001434}
1435
Chris Bienemanad070d02014-09-17 20:55:46 +00001436static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1437 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001438 Value *&SinCos) {
1439 Type *ArgTy = Arg->getType();
1440 Type *ResTy;
1441 StringRef Name;
1442
1443 Triple T(OrigCallee->getParent()->getTargetTriple());
1444 if (UseFloat) {
1445 Name = "__sincospif_stret";
1446
1447 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1448 // x86_64 can't use {float, float} since that would be returned in both
1449 // xmm0 and xmm1, which isn't what a real struct would do.
1450 ResTy = T.getArch() == Triple::x86_64
1451 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1452 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1453 } else {
1454 Name = "__sincospi_stret";
1455 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1456 }
1457
1458 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001459 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001460 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001461
1462 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1463 // If the argument is an instruction, it must dominate all uses so put our
1464 // sincos call there.
1465 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1466 } else {
1467 // Otherwise (e.g. for a constant) the beginning of the function is as
1468 // good a place as any.
1469 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1470 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1471 }
1472
1473 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1474
1475 if (SinCos->getType()->isStructTy()) {
1476 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1477 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1478 } else {
1479 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1480 "sinpi");
1481 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1482 "cospi");
1483 }
1484}
Chris Bienemanad070d02014-09-17 20:55:46 +00001485
1486Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001487 // Make sure the prototype is as expected, otherwise the rest of the
1488 // function is probably invalid and likely to abort.
1489 if (!isTrigLibCall(CI))
1490 return nullptr;
1491
1492 Value *Arg = CI->getArgOperand(0);
1493 SmallVector<CallInst *, 1> SinCalls;
1494 SmallVector<CallInst *, 1> CosCalls;
1495 SmallVector<CallInst *, 1> SinCosCalls;
1496
1497 bool IsFloat = Arg->getType()->isFloatTy();
1498
1499 // Look for all compatible sinpi, cospi and sincospi calls with the same
1500 // argument. If there are enough (in some sense) we can make the
1501 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001502 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001503 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001504 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001505
1506 // It's only worthwhile if both sinpi and cospi are actually used.
1507 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1508 return nullptr;
1509
1510 Value *Sin, *Cos, *SinCos;
1511 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1512
Davide Italianof024a562016-12-16 02:28:38 +00001513 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1514 Value *Res) {
1515 for (CallInst *C : Calls)
1516 replaceAllUsesWith(C, Res);
1517 };
1518
Chris Bienemanad070d02014-09-17 20:55:46 +00001519 replaceTrigInsts(SinCalls, Sin);
1520 replaceTrigInsts(CosCalls, Cos);
1521 replaceTrigInsts(SinCosCalls, SinCos);
1522
1523 return nullptr;
1524}
1525
David Majnemerabae6b52016-03-19 04:53:02 +00001526void LibCallSimplifier::classifyArgUse(
1527 Value *Val, Function *F, bool IsFloat,
1528 SmallVectorImpl<CallInst *> &SinCalls,
1529 SmallVectorImpl<CallInst *> &CosCalls,
1530 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001531 CallInst *CI = dyn_cast<CallInst>(Val);
1532
1533 if (!CI)
1534 return;
1535
David Majnemerabae6b52016-03-19 04:53:02 +00001536 // Don't consider calls in other functions.
1537 if (CI->getFunction() != F)
1538 return;
1539
Chris Bienemanad070d02014-09-17 20:55:46 +00001540 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001541 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001542 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001543 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001544 return;
1545
1546 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001547 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001548 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001549 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001550 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001551 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001552 SinCosCalls.push_back(CI);
1553 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001554 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001556 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001557 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001558 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001559 SinCosCalls.push_back(CI);
1560 }
1561}
1562
Meador Inge7415f842012-11-25 20:45:27 +00001563//===----------------------------------------------------------------------===//
1564// Integer Library Call Optimizations
1565//===----------------------------------------------------------------------===//
1566
Chris Bienemanad070d02014-09-17 20:55:46 +00001567Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001568 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001569 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001570 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001571 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1572 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001573 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001574 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1575 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001576
Chris Bienemanad070d02014-09-17 20:55:46 +00001577 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1578 return B.CreateSelect(Cond, V, B.getInt32(0));
1579}
Meador Ingea0b6d872012-11-26 00:24:07 +00001580
Davide Italiano85ad36b2016-12-15 23:45:11 +00001581Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1582 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1583 Value *Op = CI->getArgOperand(0);
1584 Type *ArgType = Op->getType();
1585 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1586 Intrinsic::ctlz, ArgType);
1587 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1588 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1589 V);
1590 return B.CreateIntCast(V, CI->getType(), false);
1591}
1592
Chris Bienemanad070d02014-09-17 20:55:46 +00001593Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001594 // abs(x) -> x >s -1 ? x : -x
1595 Value *Op = CI->getArgOperand(0);
1596 Value *Pos =
1597 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1598 Value *Neg = B.CreateNeg(Op, "neg");
1599 return B.CreateSelect(Pos, Op, Neg);
1600}
Meador Inge9a59ab62012-11-26 02:31:59 +00001601
Chris Bienemanad070d02014-09-17 20:55:46 +00001602Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001603 // isdigit(c) -> (c-'0') <u 10
1604 Value *Op = CI->getArgOperand(0);
1605 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1606 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1607 return B.CreateZExt(Op, CI->getType());
1608}
Meador Ingea62a39e2012-11-26 03:10:07 +00001609
Chris Bienemanad070d02014-09-17 20:55:46 +00001610Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001611 // isascii(c) -> c <u 128
1612 Value *Op = CI->getArgOperand(0);
1613 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1614 return B.CreateZExt(Op, CI->getType());
1615}
1616
1617Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 // toascii(c) -> c & 0x7f
1619 return B.CreateAnd(CI->getArgOperand(0),
1620 ConstantInt::get(CI->getType(), 0x7F));
1621}
Meador Inge604937d2012-11-26 03:38:52 +00001622
Meador Inge08ca1152012-11-26 20:37:20 +00001623//===----------------------------------------------------------------------===//
1624// Formatting and IO Library Call Optimizations
1625//===----------------------------------------------------------------------===//
1626
Chris Bienemanad070d02014-09-17 20:55:46 +00001627static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001628
Chris Bienemanad070d02014-09-17 20:55:46 +00001629Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1630 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001631 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001632 // Error reporting calls should be cold, mark them as such.
1633 // This applies even to non-builtin calls: it is only a hint and applies to
1634 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 // This heuristic was suggested in:
1637 // Improving Static Branch Prediction in a Compiler
1638 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1639 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001640 if (!CI->hasFnAttr(Attribute::Cold) &&
1641 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001642 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001643 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001644
Chris Bienemanad070d02014-09-17 20:55:46 +00001645 return nullptr;
1646}
1647
1648static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001649 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001650 return false;
1651
1652 if (StreamArg < 0)
1653 return true;
1654
1655 // These functions might be considered cold, but only if their stream
1656 // argument is stderr.
1657
1658 if (StreamArg >= (int)CI->getNumArgOperands())
1659 return false;
1660 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1661 if (!LI)
1662 return false;
1663 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1664 if (!GV || !GV->isDeclaration())
1665 return false;
1666 return GV->getName() == "stderr";
1667}
1668
1669Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1670 // Check for a fixed format string.
1671 StringRef FormatStr;
1672 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001673 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001674
Chris Bienemanad070d02014-09-17 20:55:46 +00001675 // Empty format string -> noop.
1676 if (FormatStr.empty()) // Tolerate printf's declared void.
1677 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001678
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 // Do not do any of the following transformations if the printf return value
1680 // is used, in general the printf return value is not compatible with either
1681 // putchar() or puts().
1682 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001683 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001684
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001685 // printf("x") -> putchar('x'), even for "%" and "%%".
1686 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001687 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001688
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001689 // printf("%s", "a") --> putchar('a')
1690 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1691 StringRef ChrStr;
1692 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1693 return nullptr;
1694 if (ChrStr.size() != 1)
1695 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001696 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001697 }
1698
Chris Bienemanad070d02014-09-17 20:55:46 +00001699 // printf("foo\n") --> puts("foo")
1700 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1701 FormatStr.find('%') == StringRef::npos) { // No format characters.
1702 // Create a string literal with no \n on it. We expect the constant merge
1703 // pass to be run after this pass, to merge duplicate strings.
1704 FormatStr = FormatStr.drop_back();
1705 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001706 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001707 }
Meador Inge08ca1152012-11-26 20:37:20 +00001708
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 // Optimize specific format strings.
1710 // printf("%c", chr) --> putchar(chr)
1711 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001712 CI->getArgOperand(1)->getType()->isIntegerTy())
1713 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001714
1715 // printf("%s\n", str) --> puts(str)
1716 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001717 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001718 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001719 return nullptr;
1720}
1721
1722Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1723
1724 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001725 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001726 if (Value *V = optimizePrintFString(CI, B)) {
1727 return V;
1728 }
1729
1730 // printf(format, ...) -> iprintf(format, ...) if no floating point
1731 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001732 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001733 Module *M = B.GetInsertBlock()->getParent()->getParent();
1734 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001735 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 CallInst *New = cast<CallInst>(CI->clone());
1737 New->setCalledFunction(IPrintFFn);
1738 B.Insert(New);
1739 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001740 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001741 return nullptr;
1742}
Meador Inge08ca1152012-11-26 20:37:20 +00001743
Chris Bienemanad070d02014-09-17 20:55:46 +00001744Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1745 // Check for a fixed format string.
1746 StringRef FormatStr;
1747 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001748 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001749
Chris Bienemanad070d02014-09-17 20:55:46 +00001750 // If we just have a format string (nothing else crazy) transform it.
1751 if (CI->getNumArgOperands() == 2) {
1752 // Make sure there's no % in the constant array. We could try to handle
1753 // %% -> % in the future if we cared.
1754 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1755 if (FormatStr[i] == '%')
1756 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001757
Chris Bienemanad070d02014-09-17 20:55:46 +00001758 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001759 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1760 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1761 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001762 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001763 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001764 }
Meador Ingef8e72502012-11-29 15:45:43 +00001765
Chris Bienemanad070d02014-09-17 20:55:46 +00001766 // The remaining optimizations require the format string to be "%s" or "%c"
1767 // and have an extra operand.
1768 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1769 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001770 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001771
Chris Bienemanad070d02014-09-17 20:55:46 +00001772 // Decode the second character of the format string.
1773 if (FormatStr[1] == 'c') {
1774 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1775 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1776 return nullptr;
1777 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001778 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001779 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001780 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001781 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001782
Chris Bienemanad070d02014-09-17 20:55:46 +00001783 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001784 }
1785
Chris Bienemanad070d02014-09-17 20:55:46 +00001786 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001787 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1788 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1789 return nullptr;
1790
Sanjay Pateld3112a52016-01-19 19:46:10 +00001791 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001792 if (!Len)
1793 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001794 Value *IncLen =
1795 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1796 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001797
1798 // The sprintf result is the unincremented number of bytes in the string.
1799 return B.CreateIntCast(Len, CI->getType(), false);
1800 }
1801 return nullptr;
1802}
1803
1804Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1805 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001806 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001807 if (Value *V = optimizeSPrintFString(CI, B)) {
1808 return V;
1809 }
1810
1811 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1812 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001813 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 Module *M = B.GetInsertBlock()->getParent()->getParent();
1815 Constant *SIPrintFFn =
1816 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1817 CallInst *New = cast<CallInst>(CI->clone());
1818 New->setCalledFunction(SIPrintFFn);
1819 B.Insert(New);
1820 return New;
1821 }
1822 return nullptr;
1823}
1824
1825Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1826 optimizeErrorReporting(CI, B, 0);
1827
1828 // All the optimizations depend on the format string.
1829 StringRef FormatStr;
1830 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1831 return nullptr;
1832
1833 // Do not do any of the following transformations if the fprintf return
1834 // value is used, in general the fprintf return value is not compatible
1835 // with fwrite(), fputc() or fputs().
1836 if (!CI->use_empty())
1837 return nullptr;
1838
1839 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1840 if (CI->getNumArgOperands() == 2) {
1841 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1842 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1843 return nullptr; // We found a format specifier.
1844
Sanjay Pateld3112a52016-01-19 19:46:10 +00001845 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001846 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001847 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001848 CI->getArgOperand(0), B, DL, TLI);
1849 }
1850
1851 // The remaining optimizations require the format string to be "%s" or "%c"
1852 // and have an extra operand.
1853 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1854 CI->getNumArgOperands() < 3)
1855 return nullptr;
1856
1857 // Decode the second character of the format string.
1858 if (FormatStr[1] == 'c') {
1859 // fprintf(F, "%c", chr) --> fputc(chr, F)
1860 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1861 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001862 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001863 }
1864
1865 if (FormatStr[1] == 's') {
1866 // fprintf(F, "%s", str) --> fputs(str, F)
1867 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1868 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001869 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001870 }
1871 return nullptr;
1872}
1873
1874Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1875 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001876 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001877 if (Value *V = optimizeFPrintFString(CI, B)) {
1878 return V;
1879 }
1880
1881 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1882 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001883 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 Module *M = B.GetInsertBlock()->getParent()->getParent();
1885 Constant *FIPrintFFn =
1886 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1887 CallInst *New = cast<CallInst>(CI->clone());
1888 New->setCalledFunction(FIPrintFFn);
1889 B.Insert(New);
1890 return New;
1891 }
1892 return nullptr;
1893}
1894
1895Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1896 optimizeErrorReporting(CI, B, 3);
1897
Chris Bienemanad070d02014-09-17 20:55:46 +00001898 // Get the element size and count.
1899 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1900 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1901 if (!SizeC || !CountC)
1902 return nullptr;
1903 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1904
1905 // If this is writing zero records, remove the call (it's a noop).
1906 if (Bytes == 0)
1907 return ConstantInt::get(CI->getType(), 0);
1908
1909 // If this is writing one byte, turn it into fputc.
1910 // This optimisation is only valid, if the return value is unused.
1911 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001912 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1913 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001914 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1915 }
1916
1917 return nullptr;
1918}
1919
1920Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1921 optimizeErrorReporting(CI, B, 1);
1922
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001923 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1924 // requires more arguments and thus extra MOVs are required.
1925 if (CI->getParent()->getParent()->optForSize())
1926 return nullptr;
1927
Ahmed Bougachad765a822016-04-27 19:04:35 +00001928 // We can't optimize if return value is used.
1929 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001930 return nullptr;
1931
1932 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1933 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1934 if (!Len)
1935 return nullptr;
1936
1937 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001938 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001939 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001940 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001941 CI->getArgOperand(1), B, DL, TLI);
1942}
1943
1944Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001945 // Check for a constant string.
1946 StringRef Str;
1947 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1948 return nullptr;
1949
1950 if (Str.empty() && CI->use_empty()) {
1951 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001952 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001953 if (CI->use_empty() || !Res)
1954 return Res;
1955 return B.CreateIntCast(Res, CI->getType(), true);
1956 }
1957
1958 return nullptr;
1959}
1960
1961bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001962 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001963 SmallString<20> FloatFuncName = FuncName;
1964 FloatFuncName += 'f';
1965 if (TLI->getLibFunc(FloatFuncName, Func))
1966 return TLI->has(Func);
1967 return false;
1968}
Meador Inge7fb2f732012-10-13 16:45:32 +00001969
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001970Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1971 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001972 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001973 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001974 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001975 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001976 // Make sure we never change the calling convention.
1977 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001978 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001979 "Optimizing string/memory libcall would change the calling convention");
1980 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001981 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001982 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001983 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001984 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001985 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001986 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001987 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001988 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001989 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001990 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001991 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001992 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001993 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001994 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001995 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001996 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001997 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002001 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002003 case LibFunc_strtol:
2004 case LibFunc_strtod:
2005 case LibFunc_strtof:
2006 case LibFunc_strtoul:
2007 case LibFunc_strtoll:
2008 case LibFunc_strtold:
2009 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002010 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002011 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002012 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002013 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002014 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002015 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002016 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002017 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002018 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002019 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002020 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002021 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002022 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002024 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002025 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002026 return optimizeMemSet(CI, Builder);
2027 default:
2028 break;
2029 }
2030 }
2031 return nullptr;
2032}
2033
Chris Bienemanad070d02014-09-17 20:55:46 +00002034Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2035 if (CI->isNoBuiltin())
2036 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002037
David L. Jonesd21529f2017-01-23 23:16:46 +00002038 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002039 Function *Callee = CI->getCalledFunction();
2040 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002041
2042 SmallVector<OperandBundleDef, 2> OpBundles;
2043 CI->getOperandBundlesAsDefs(OpBundles);
2044 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002045 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002046
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002047 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002048 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2049 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002050 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002051 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002052
Sanjay Patel848309d2014-10-23 21:52:45 +00002053 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002054 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002055 if (!isCallingConvC)
2056 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002057 switch (II->getIntrinsicID()) {
2058 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002059 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002060 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002061 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002062 case Intrinsic::log:
2063 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002064 case Intrinsic::sqrt:
2065 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002066 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002067 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002068 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002069 }
2070 }
2071
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002072 // Also try to simplify calls to fortified library functions.
2073 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2074 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002075 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002076 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2077 // Use an IR Builder from SimplifiedCI if available instead of CI
2078 // to guarantee we reach all uses we might replace later on.
2079 IRBuilder<> TmpBuilder(SimplifiedCI);
2080 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002081 // If we were able to further simplify, remove the now redundant call.
2082 SimplifiedCI->replaceAllUsesWith(V);
2083 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002084 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002085 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002086 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002087 return SimplifiedFortifiedCI;
2088 }
2089
Meador Inge20255ef2013-03-12 00:08:29 +00002090 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002091 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002092 // We never change the calling convention.
2093 if (!ignoreCallingConv(Func) && !isCallingConvC)
2094 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002095 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2096 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002097 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002098 case LibFunc_cosf:
2099 case LibFunc_cos:
2100 case LibFunc_cosl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002101 return optimizeCos(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002102 case LibFunc_sinpif:
2103 case LibFunc_sinpi:
2104 case LibFunc_cospif:
2105 case LibFunc_cospi:
Chris Bienemanad070d02014-09-17 20:55:46 +00002106 return optimizeSinCosPi(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002107 case LibFunc_powf:
2108 case LibFunc_pow:
2109 case LibFunc_powl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002110 return optimizePow(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002111 case LibFunc_exp2l:
2112 case LibFunc_exp2:
2113 case LibFunc_exp2f:
Chris Bienemanad070d02014-09-17 20:55:46 +00002114 return optimizeExp2(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002115 case LibFunc_fabsf:
2116 case LibFunc_fabs:
2117 case LibFunc_fabsl:
Matt Arsenault954a6242017-01-23 23:55:08 +00002118 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
David L. Jonesd21529f2017-01-23 23:16:46 +00002119 case LibFunc_sqrtf:
2120 case LibFunc_sqrt:
2121 case LibFunc_sqrtl:
Sanjay Patelc699a612014-10-16 18:48:17 +00002122 return optimizeSqrt(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002123 case LibFunc_ffs:
2124 case LibFunc_ffsl:
2125 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002126 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002127 case LibFunc_fls:
2128 case LibFunc_flsl:
2129 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002130 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002131 case LibFunc_abs:
2132 case LibFunc_labs:
2133 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002134 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002135 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002136 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002137 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002138 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002139 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002140 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002141 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002142 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002143 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002144 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002145 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002146 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002147 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002148 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002149 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002150 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002151 case LibFunc_log:
2152 case LibFunc_log10:
2153 case LibFunc_log1p:
2154 case LibFunc_log2:
2155 case LibFunc_logb:
Davide Italianob8b71332015-11-29 20:58:04 +00002156 return optimizeLog(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002157 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002158 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002159 case LibFunc_tan:
2160 case LibFunc_tanf:
2161 case LibFunc_tanl:
Davide Italiano51507d22015-11-04 23:36:56 +00002162 return optimizeTan(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002163 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002164 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002165 case LibFunc_vfprintf:
2166 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002167 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002168 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002169 return optimizeErrorReporting(CI, Builder, 1);
David L. Jonesd21529f2017-01-23 23:16:46 +00002170 case LibFunc_ceil:
Matt Arsenault954a6242017-01-23 23:55:08 +00002171 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
David L. Jonesd21529f2017-01-23 23:16:46 +00002172 case LibFunc_floor:
Matt Arsenault954a6242017-01-23 23:55:08 +00002173 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
David L. Jonesd21529f2017-01-23 23:16:46 +00002174 case LibFunc_round:
Matt Arsenault954a6242017-01-23 23:55:08 +00002175 return replaceUnaryCall(CI, Builder, Intrinsic::round);
David L. Jonesd21529f2017-01-23 23:16:46 +00002176 case LibFunc_nearbyint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002177 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002178 case LibFunc_rint:
2179 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
David L. Jonesd21529f2017-01-23 23:16:46 +00002180 case LibFunc_trunc:
Matt Arsenault954a6242017-01-23 23:55:08 +00002181 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
David L. Jonesd21529f2017-01-23 23:16:46 +00002182 case LibFunc_acos:
2183 case LibFunc_acosh:
2184 case LibFunc_asin:
2185 case LibFunc_asinh:
2186 case LibFunc_atan:
2187 case LibFunc_atanh:
2188 case LibFunc_cbrt:
2189 case LibFunc_cosh:
2190 case LibFunc_exp:
2191 case LibFunc_exp10:
2192 case LibFunc_expm1:
2193 case LibFunc_sin:
2194 case LibFunc_sinh:
2195 case LibFunc_tanh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002196 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2197 return optimizeUnaryDoubleFP(CI, Builder, true);
2198 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002199 case LibFunc_copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002200 if (hasFloatVersion(FuncName))
2201 return optimizeBinaryDoubleFP(CI, Builder);
2202 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002203 case LibFunc_fminf:
2204 case LibFunc_fmin:
2205 case LibFunc_fminl:
2206 case LibFunc_fmaxf:
2207 case LibFunc_fmax:
2208 case LibFunc_fmaxl:
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002209 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002210 default:
2211 return nullptr;
2212 }
Meador Inge20255ef2013-03-12 00:08:29 +00002213 }
Craig Topperf40110f2014-04-25 05:29:35 +00002214 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002215}
2216
Chandler Carruth92803822015-01-21 02:11:59 +00002217LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002218 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002219 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002220 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002221 Replacer(Replacer) {}
2222
2223void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2224 // Indirect through the replacer used in this instance.
2225 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002226}
2227
Meador Ingedfb08a22013-06-20 19:48:07 +00002228// TODO:
2229// Additional cases that we need to add to this file:
2230//
2231// cbrt:
2232// * cbrt(expN(X)) -> expN(x/3)
2233// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002234// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002235//
2236// exp, expf, expl:
2237// * exp(log(x)) -> x
2238//
2239// log, logf, logl:
2240// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002241// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002242// * log(exp10(y)) -> y*log(10)
2243// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002244//
Meador Ingedfb08a22013-06-20 19:48:07 +00002245// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002246// * pow(sqrt(x),y) -> pow(x,y*0.5)
2247// * pow(pow(x,y),z)-> pow(x,y*z)
2248//
Meador Ingedfb08a22013-06-20 19:48:07 +00002249// signbit:
2250// * signbit(cnst) -> cnst'
2251// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2252//
2253// sqrt, sqrtf, sqrtl:
2254// * sqrt(expN(x)) -> expN(x*0.5)
2255// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2256// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2257//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002258
2259//===----------------------------------------------------------------------===//
2260// Fortified Library Call Optimizations
2261//===----------------------------------------------------------------------===//
2262
2263bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2264 unsigned ObjSizeOp,
2265 unsigned SizeOp,
2266 bool isString) {
2267 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2268 return true;
2269 if (ConstantInt *ObjSizeCI =
2270 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2271 if (ObjSizeCI->isAllOnesValue())
2272 return true;
2273 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2274 if (OnlyLowerUnknownSize)
2275 return false;
2276 if (isString) {
2277 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2278 // If the length is 0 we don't know how long it is and so we can't
2279 // remove the check.
2280 if (Len == 0)
2281 return false;
2282 return ObjSizeCI->getZExtValue() >= Len;
2283 }
2284 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2285 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2286 }
2287 return false;
2288}
2289
Sanjay Pateld707db92015-12-31 16:10:49 +00002290Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2291 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002292 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2293 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002294 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002295 return CI->getArgOperand(0);
2296 }
2297 return nullptr;
2298}
2299
Sanjay Pateld707db92015-12-31 16:10:49 +00002300Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2301 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002302 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2303 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002304 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002305 return CI->getArgOperand(0);
2306 }
2307 return nullptr;
2308}
2309
Sanjay Pateld707db92015-12-31 16:10:49 +00002310Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2311 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002312 // TODO: Try foldMallocMemset() here.
2313
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002314 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2315 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2316 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2317 return CI->getArgOperand(0);
2318 }
2319 return nullptr;
2320}
2321
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002322Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2323 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002324 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002325 Function *Callee = CI->getCalledFunction();
2326 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002327 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002328 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2329 *ObjSize = CI->getArgOperand(2);
2330
2331 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002332 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002333 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002334 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002335 }
2336
2337 // If a) we don't have any length information, or b) we know this will
2338 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2339 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2340 // TODO: It might be nice to get a maximum length out of the possible
2341 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002342 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002343 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002344
David Blaikie65fab6d2015-04-03 21:32:06 +00002345 if (OnlyLowerUnknownSize)
2346 return nullptr;
2347
2348 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2349 uint64_t Len = GetStringLength(Src);
2350 if (Len == 0)
2351 return nullptr;
2352
2353 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2354 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002355 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002356 // If the function was an __stpcpy_chk, and we were able to fold it into
2357 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002358 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002359 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2360 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002361}
2362
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002363Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2364 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002365 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002366 Function *Callee = CI->getCalledFunction();
2367 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002368 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002369 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002370 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002371 return Ret;
2372 }
2373 return nullptr;
2374}
2375
2376Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002377 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2378 // Some clang users checked for _chk libcall availability using:
2379 // __has_builtin(__builtin___memcpy_chk)
2380 // When compiling with -fno-builtin, this is always true.
2381 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2382 // end up with fortified libcalls, which isn't acceptable in a freestanding
2383 // environment which only provides their non-fortified counterparts.
2384 //
2385 // Until we change clang and/or teach external users to check for availability
2386 // differently, disregard the "nobuiltin" attribute and TLI::has.
2387 //
2388 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002389
David L. Jonesd21529f2017-01-23 23:16:46 +00002390 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002391 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002392
2393 SmallVector<OperandBundleDef, 2> OpBundles;
2394 CI->getOperandBundlesAsDefs(OpBundles);
2395 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002396 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002397
Ahmed Bougachad765a822016-04-27 19:04:35 +00002398 // First, check that this is a known library functions and that the prototype
2399 // is correct.
2400 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002401 return nullptr;
2402
2403 // We never change the calling convention.
2404 if (!ignoreCallingConv(Func) && !isCallingConvC)
2405 return nullptr;
2406
2407 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002408 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002409 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002410 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002411 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002412 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002413 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002414 case LibFunc_stpcpy_chk:
2415 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002416 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002417 case LibFunc_stpncpy_chk:
2418 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002419 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002420 default:
2421 break;
2422 }
2423 return nullptr;
2424}
2425
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002426FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2427 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2428 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}