blob: e65ecc55c839a3be6964c12ba3c9f49afdb76a49 [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//
Craig Topper2915bc02018-03-01 20:05:09 +000010// This file implements the library calls simplifier. It does not implement
11// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000016#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000017#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000018#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000019#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000020#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000022#include "llvm/Analysis/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
25#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"
Craig Topperb45eabc2017-04-26 16:39:58 +000033#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
35
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
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 is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000088static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000089 for (User *U : V->users()) {
90 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000091 if (IC->isEquality() && IC->getOperand(1) == With)
92 continue;
93 // Unknown instruction.
94 return false;
95 }
96 return true;
97}
98
Meador Inge08ca1152012-11-26 20:37:20 +000099static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000100 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000101 return OI->getType()->isFloatingPointTy();
102 });
Meador Inge08ca1152012-11-26 20:37:20 +0000103}
104
Meador Inged589ac62012-10-31 03:33:06 +0000105//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000106// String and Memory Library Call Optimizations
107//===----------------------------------------------------------------------===//
108
Chris Bienemanad070d02014-09-17 20:55:46 +0000109Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000110 // Extract some information from the instruction
111 Value *Dst = CI->getArgOperand(0);
112 Value *Src = CI->getArgOperand(1);
113
114 // See if we can get the length of the input string.
115 uint64_t Len = GetStringLength(Src);
116 if (Len == 0)
117 return nullptr;
118 --Len; // Unbias length.
119
120 // Handle the simple, do-nothing case: strcat(x, "") -> x
121 if (Len == 0)
122 return Dst;
123
Chris Bienemanad070d02014-09-17 20:55:46 +0000124 return emitStrLenMemCpy(Src, Dst, Len, B);
125}
126
127Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
128 IRBuilder<> &B) {
129 // We need to find the end of the destination string. That's where the
130 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000131 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000132 if (!DstLen)
133 return nullptr;
134
135 // Now that we have the destination's length, we must index into the
136 // destination's pointer to get the actual memcpy destination (end of
137 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000138 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000139
140 // We have enough information to now generate the memcpy call to do the
141 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000142 B.CreateMemCpy(CpyDst, 1, Src, 1,
143 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000144 return Dst;
145}
146
147Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000148 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000149 Value *Dst = CI->getArgOperand(0);
150 Value *Src = CI->getArgOperand(1);
151 uint64_t Len;
152
Sanjay Pateld707db92015-12-31 16:10:49 +0000153 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000154 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
155 Len = LengthArg->getZExtValue();
156 else
157 return nullptr;
158
159 // See if we can get the length of the input string.
160 uint64_t SrcLen = GetStringLength(Src);
161 if (SrcLen == 0)
162 return nullptr;
163 --SrcLen; // Unbias length.
164
165 // Handle the simple, do-nothing cases:
166 // strncat(x, "", c) -> x
167 // strncat(x, c, 0) -> x
168 if (SrcLen == 0 || Len == 0)
169 return Dst;
170
Sanjay Pateld707db92015-12-31 16:10:49 +0000171 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000172 if (Len < SrcLen)
173 return nullptr;
174
175 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000176 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000177 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
178}
179
180Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
181 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000182 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000183 Value *SrcStr = CI->getArgOperand(0);
184
185 // If the second operand is non-constant, see if we can compute the length
186 // of the input string and turn this into memchr.
187 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
188 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000189 uint64_t Len = GetStringLength(SrcStr);
190 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
191 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000192
Sanjay Pateld3112a52016-01-19 19:46:10 +0000193 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000194 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
195 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000196 }
197
Chris Bienemanad070d02014-09-17 20:55:46 +0000198 // Otherwise, the character is a constant, see if the first argument is
199 // a string literal. If so, we can constant fold.
200 StringRef Str;
201 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000202 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000203 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000204 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000205 return nullptr;
206 }
207
208 // Compute the offset, make sure to handle the case when we're searching for
209 // zero (a weird way to spell strlen).
210 size_t I = (0xFF & CharC->getSExtValue()) == 0
211 ? Str.size()
212 : Str.find(CharC->getSExtValue());
213 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
214 return Constant::getNullValue(CI->getType());
215
216 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000217 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000218}
219
220Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000221 Value *SrcStr = CI->getArgOperand(0);
222 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
223
224 // Cannot fold anything if we're not looking for a constant.
225 if (!CharC)
226 return nullptr;
227
228 StringRef Str;
229 if (!getConstantStringInfo(SrcStr, Str)) {
230 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000231 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000232 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000233 return nullptr;
234 }
235
236 // Compute the offset.
237 size_t I = (0xFF & CharC->getSExtValue()) == 0
238 ? Str.size()
239 : Str.rfind(CharC->getSExtValue());
240 if (I == StringRef::npos) // Didn't find the char. Return null.
241 return Constant::getNullValue(CI->getType());
242
243 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000244 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000245}
246
247Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000248 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
249 if (Str1P == Str2P) // strcmp(x,x) -> 0
250 return ConstantInt::get(CI->getType(), 0);
251
252 StringRef Str1, Str2;
253 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
254 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
255
256 // strcmp(x, y) -> cnst (if both x and y are constant strings)
257 if (HasStr1 && HasStr2)
258 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
259
260 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
261 return B.CreateNeg(
262 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
263
264 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
265 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
266
267 // strcmp(P, "x") -> memcmp(P, "x", 2)
268 uint64_t Len1 = GetStringLength(Str1P);
269 uint64_t Len2 = GetStringLength(Str2P);
270 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000271 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000272 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000273 std::min(Len1, Len2)),
274 B, DL, TLI);
275 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000276
Chris Bienemanad070d02014-09-17 20:55:46 +0000277 return nullptr;
278}
279
280Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000281 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
282 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
283 return ConstantInt::get(CI->getType(), 0);
284
285 // Get the length argument if it is constant.
286 uint64_t Length;
287 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
288 Length = LengthArg->getZExtValue();
289 else
290 return nullptr;
291
292 if (Length == 0) // strncmp(x,y,0) -> 0
293 return ConstantInt::get(CI->getType(), 0);
294
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000296 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000297
298 StringRef Str1, Str2;
299 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
300 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
301
302 // strncmp(x, y) -> cnst (if both x and y are constant strings)
303 if (HasStr1 && HasStr2) {
304 StringRef SubStr1 = Str1.substr(0, Length);
305 StringRef SubStr2 = Str2.substr(0, Length);
306 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
307 }
308
309 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
310 return B.CreateNeg(
311 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
312
313 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
314 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
315
316 return nullptr;
317}
318
319Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000320 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
321 if (Dst == Src) // strcpy(x,x) -> x
322 return Src;
323
Chris Bienemanad070d02014-09-17 20:55:46 +0000324 // See if we can get the length of the input string.
325 uint64_t Len = GetStringLength(Src);
326 if (Len == 0)
327 return nullptr;
328
329 // We have enough information to now generate the memcpy call to do the
330 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000331 B.CreateMemCpy(Dst, 1, Src, 1,
332 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000333 return Dst;
334}
335
336Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
337 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000338 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
339 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000340 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000341 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000342 }
343
344 // See if we can get the length of the input string.
345 uint64_t Len = GetStringLength(Src);
346 if (Len == 0)
347 return nullptr;
348
Davide Italianob7487e62015-11-02 23:07:14 +0000349 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000350 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000351 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
352 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000353
354 // We have enough information to now generate the memcpy call to do the
355 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000356 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000357 return DstEnd;
358}
359
360Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
361 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000362 Value *Dst = CI->getArgOperand(0);
363 Value *Src = CI->getArgOperand(1);
364 Value *LenOp = CI->getArgOperand(2);
365
366 // See if we can get the length of the input string.
367 uint64_t SrcLen = GetStringLength(Src);
368 if (SrcLen == 0)
369 return nullptr;
370 --SrcLen;
371
372 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000373 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000374 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000375 return Dst;
376 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000377
Chris Bienemanad070d02014-09-17 20:55:46 +0000378 uint64_t Len;
379 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
380 Len = LengthArg->getZExtValue();
381 else
382 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000383
Chris Bienemanad070d02014-09-17 20:55:46 +0000384 if (Len == 0)
385 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000386
Chris Bienemanad070d02014-09-17 20:55:46 +0000387 // Let strncpy handle the zero padding
388 if (Len > SrcLen + 1)
389 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000390
Davide Italianob7487e62015-11-02 23:07:14 +0000391 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000392 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
393 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000394
Chris Bienemanad070d02014-09-17 20:55:46 +0000395 return Dst;
396}
Meador Inge7fb2f732012-10-13 16:45:32 +0000397
Matthias Braun50ec0b52017-05-19 22:37:09 +0000398Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
399 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000400 Value *Src = CI->getArgOperand(0);
401
402 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000403 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000404 return ConstantInt::get(CI->getType(), Len - 1);
405
David L Kreitzer752c1442016-04-13 14:31:06 +0000406 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000407 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000408 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000409 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000410 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000411 // subtraction. This will make the optimization more complex, and it's not
412 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000413 // very uncommon.
414 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000415 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000416 return nullptr;
417
Matthias Braun50ec0b52017-05-19 22:37:09 +0000418 ConstantDataArraySlice Slice;
419 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
420 uint64_t NullTermIdx;
421 if (Slice.Array == nullptr) {
422 NullTermIdx = 0;
423 } else {
424 NullTermIdx = ~((uint64_t)0);
425 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
426 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
427 NullTermIdx = I;
428 break;
429 }
430 }
431 // If the string does not have '\0', leave it to strlen to compute
432 // its length.
433 if (NullTermIdx == ~((uint64_t)0))
434 return nullptr;
435 }
436
David L Kreitzer752c1442016-04-13 14:31:06 +0000437 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000438 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000439 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000440 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000441 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
442
Matthias Braun50ec0b52017-05-19 22:37:09 +0000443 // KnownZero's bits are flipped, so zeros in KnownZero now represent
444 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000445 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000446 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000447 // unsigned-less-than NullTermIdx.
448 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000449 // If Offset is not provably in the range [0, NullTermIdx], we can still
450 // optimize if we can prove that the program has undefined behavior when
451 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000452 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000453 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000454 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000455 NullTermIdx == ArrSize - 1)) {
456 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
457 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000458 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000459 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000460 }
461
462 return nullptr;
463 }
464
Chris Bienemanad070d02014-09-17 20:55:46 +0000465 // strlen(x?"foo":"bars") --> x ? 3 : 4
466 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000467 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
468 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000469 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000470 ORE.emit([&]() {
471 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
472 << "folded strlen(select) to select of constants";
473 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000474 return B.CreateSelect(SI->getCondition(),
475 ConstantInt::get(CI->getType(), LenTrue - 1),
476 ConstantInt::get(CI->getType(), LenFalse - 1));
477 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000478 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000479
Chris Bienemanad070d02014-09-17 20:55:46 +0000480 // strlen(x) != 0 --> *x != 0
481 // strlen(x) == 0 --> *x == 0
482 if (isOnlyUsedInZeroEqualityComparison(CI))
483 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000484
Chris Bienemanad070d02014-09-17 20:55:46 +0000485 return nullptr;
486}
Meador Inge17418502012-10-13 16:45:37 +0000487
Matthias Braun50ec0b52017-05-19 22:37:09 +0000488Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
489 return optimizeStringLength(CI, B, 8);
490}
491
492Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
493 Module &M = *CI->getParent()->getParent()->getParent();
494 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000495 // We cannot perform this optimization without wchar_size metadata.
496 if (WCharSize == 0)
497 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000498
499 return optimizeStringLength(CI, B, WCharSize);
500}
501
Chris Bienemanad070d02014-09-17 20:55:46 +0000502Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000503 StringRef S1, S2;
504 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
505 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000506
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000507 // strpbrk(s, "") -> nullptr
508 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000509 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
510 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000511
Chris Bienemanad070d02014-09-17 20:55:46 +0000512 // Constant folding.
513 if (HasS1 && HasS2) {
514 size_t I = S1.find_first_of(S2);
515 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000516 return Constant::getNullValue(CI->getType());
517
Sanjay Pateld707db92015-12-31 16:10:49 +0000518 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
519 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000520 }
Meador Inge17418502012-10-13 16:45:37 +0000521
Chris Bienemanad070d02014-09-17 20:55:46 +0000522 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000523 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000524 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000525
526 return nullptr;
527}
528
529Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000530 Value *EndPtr = CI->getArgOperand(1);
531 if (isa<ConstantPointerNull>(EndPtr)) {
532 // With a null EndPtr, this function won't capture the main argument.
533 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000534 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000535 }
536
537 return nullptr;
538}
539
540Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 StringRef S1, S2;
542 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
543 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
544
545 // strspn(s, "") -> 0
546 // strspn("", s) -> 0
547 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
548 return Constant::getNullValue(CI->getType());
549
550 // Constant folding.
551 if (HasS1 && HasS2) {
552 size_t Pos = S1.find_first_not_of(S2);
553 if (Pos == StringRef::npos)
554 Pos = S1.size();
555 return ConstantInt::get(CI->getType(), Pos);
556 }
557
558 return nullptr;
559}
560
561Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000562 StringRef S1, S2;
563 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
564 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
565
566 // strcspn("", s) -> 0
567 if (HasS1 && S1.empty())
568 return Constant::getNullValue(CI->getType());
569
570 // Constant folding.
571 if (HasS1 && HasS2) {
572 size_t Pos = S1.find_first_of(S2);
573 if (Pos == StringRef::npos)
574 Pos = S1.size();
575 return ConstantInt::get(CI->getType(), Pos);
576 }
577
578 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000579 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000580 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000581
582 return nullptr;
583}
584
585Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000586 // fold strstr(x, x) -> x.
587 if (CI->getArgOperand(0) == CI->getArgOperand(1))
588 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
589
590 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000591 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000592 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000593 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000594 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000595 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000596 StrLen, B, DL, TLI);
597 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000598 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000599 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
600 ICmpInst *Old = cast<ICmpInst>(*UI++);
601 Value *Cmp =
602 B.CreateICmp(Old->getPredicate(), StrNCmp,
603 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
604 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000605 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 return CI;
607 }
Meador Inge17418502012-10-13 16:45:37 +0000608
Chris Bienemanad070d02014-09-17 20:55:46 +0000609 // See if either input string is a constant string.
610 StringRef SearchStr, ToFindStr;
611 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
612 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
613
614 // fold strstr(x, "") -> x.
615 if (HasStr2 && ToFindStr.empty())
616 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
617
618 // If both strings are known, constant fold it.
619 if (HasStr1 && HasStr2) {
620 size_t Offset = SearchStr.find(ToFindStr);
621
622 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000623 return Constant::getNullValue(CI->getType());
624
Chris Bienemanad070d02014-09-17 20:55:46 +0000625 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000626 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000627 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
628 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000629 }
Meador Inge17418502012-10-13 16:45:37 +0000630
Chris Bienemanad070d02014-09-17 20:55:46 +0000631 // fold strstr(x, "y") -> strchr(x, 'y').
632 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000633 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
635 }
636 return nullptr;
637}
Meador Inge40b6fac2012-10-15 03:47:37 +0000638
Benjamin Kramer691363e2015-03-21 15:36:21 +0000639Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000640 Value *SrcStr = CI->getArgOperand(0);
641 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
642 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
643
644 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000645 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000646 return Constant::getNullValue(CI->getType());
647
Benjamin Kramer7857d722015-03-21 21:09:33 +0000648 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000649 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000650 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000651 return nullptr;
652
653 // Truncate the string to LenC. If Str is smaller than LenC we will still only
654 // scan the string, as reading past the end of it is undefined and we can just
655 // return null if we don't find the char.
656 Str = Str.substr(0, LenC->getZExtValue());
657
Benjamin Kramer7857d722015-03-21 21:09:33 +0000658 // If the char is variable but the input str and length are not we can turn
659 // this memchr call into a simple bit field test. Of course this only works
660 // when the return value is only checked against null.
661 //
662 // It would be really nice to reuse switch lowering here but we can't change
663 // the CFG at this point.
664 //
665 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
666 // after bounds check.
667 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000668 unsigned char Max =
669 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
670 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000671
672 // Make sure the bit field we're about to create fits in a register on the
673 // target.
674 // FIXME: On a 64 bit architecture this prevents us from using the
675 // interesting range of alpha ascii chars. We could do better by emitting
676 // two bitfields or shifting the range by 64 if no lower chars are used.
677 if (!DL.fitsInLegalInteger(Max + 1))
678 return nullptr;
679
680 // For the bit field use a power-of-2 type with at least 8 bits to avoid
681 // creating unnecessary illegal types.
682 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
683
684 // Now build the bit field.
685 APInt Bitfield(Width, 0);
686 for (char C : Str)
687 Bitfield.setBit((unsigned char)C);
688 Value *BitfieldC = B.getInt(Bitfield);
689
690 // First check that the bit field access is within bounds.
691 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
692 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
693 "memchr.bounds");
694
695 // Create code that checks if the given bit is set in the field.
696 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
697 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
698
699 // Finally merge both checks and cast to pointer type. The inttoptr
700 // implicitly zexts the i1 to intptr type.
701 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
702 }
703
704 // Check if all arguments are constants. If so, we can constant fold.
705 if (!CharC)
706 return nullptr;
707
Benjamin Kramer691363e2015-03-21 15:36:21 +0000708 // Compute the offset.
709 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
710 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
711 return Constant::getNullValue(CI->getType());
712
713 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000714 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000715}
716
Chris Bienemanad070d02014-09-17 20:55:46 +0000717Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000718 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000719
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 if (LHS == RHS) // memcmp(s,s,x) -> 0
721 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000722
Chris Bienemanad070d02014-09-17 20:55:46 +0000723 // Make sure we have a constant length.
724 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
725 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000726 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000727
Sanjay Patel70db4242017-06-09 14:22:03 +0000728 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000729 if (Len == 0) // memcmp(s1,s2,0) -> 0
730 return Constant::getNullValue(CI->getType());
731
732 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
733 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000734 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000735 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000736 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000737 CI->getType(), "rhsv");
738 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000739 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000740
Chad Rosierdc655322015-08-28 18:30:18 +0000741 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000742 // TODO: The case where both inputs are constants does not need to be limited
743 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000744 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000745 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
746 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
747
Sanjay Patel82ec8722017-08-21 19:13:14 +0000748 // First, see if we can fold either argument to a constant.
749 Value *LHSV = nullptr;
750 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
751 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
752 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
753 }
754 Value *RHSV = nullptr;
755 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
756 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
757 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
758 }
Chad Rosierdc655322015-08-28 18:30:18 +0000759
Sanjay Patel82ec8722017-08-21 19:13:14 +0000760 // Don't generate unaligned loads. If either source is constant data,
761 // alignment doesn't matter for that source because there is no load.
762 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
763 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
764 if (!LHSV) {
765 Type *LHSPtrTy =
766 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
767 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
768 }
769 if (!RHSV) {
770 Type *RHSPtrTy =
771 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
772 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
773 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000774 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000775 }
Chad Rosierdc655322015-08-28 18:30:18 +0000776 }
777
Sanjay Patel82ec8722017-08-21 19:13:14 +0000778 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
779 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000780 StringRef LHSStr, RHSStr;
781 if (getConstantStringInfo(LHS, LHSStr) &&
782 getConstantStringInfo(RHS, RHSStr)) {
783 // Make sure we're not reading out-of-bounds memory.
784 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000786 // Fold the memcmp and normalize the result. This way we get consistent
787 // results across multiple platforms.
788 uint64_t Ret = 0;
789 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
790 if (Cmp < 0)
791 Ret = -1;
792 else if (Cmp > 0)
793 Ret = 1;
794 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000795 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000796
Chris Bienemanad070d02014-09-17 20:55:46 +0000797 return nullptr;
798}
Meador Inge9a6a1902012-10-31 00:20:56 +0000799
Chris Bienemanad070d02014-09-17 20:55:46 +0000800Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000801 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
802 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
803 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000804 return CI->getArgOperand(0);
805}
Meador Inge05a625a2012-10-31 14:58:26 +0000806
Chris Bienemanad070d02014-09-17 20:55:46 +0000807Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000808 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
809 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
810 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000811 return CI->getArgOperand(0);
812}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000813
Sanjay Patel980b2802016-01-26 16:17:24 +0000814/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
815static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
816 const TargetLibraryInfo &TLI) {
817 // This has to be a memset of zeros (bzero).
818 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
819 if (!FillValue || FillValue->getZExtValue() != 0)
820 return nullptr;
821
822 // TODO: We should handle the case where the malloc has more than one use.
823 // This is necessary to optimize common patterns such as when the result of
824 // the malloc is checked against null or when a memset intrinsic is used in
825 // place of a memset library call.
826 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
827 if (!Malloc || !Malloc->hasOneUse())
828 return nullptr;
829
830 // Is the inner call really malloc()?
831 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000832 if (!InnerCallee)
833 return nullptr;
834
David L. Jonesd21529f2017-01-23 23:16:46 +0000835 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000836 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000837 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000838 return nullptr;
839
Sanjay Patel980b2802016-01-26 16:17:24 +0000840 // The memset must cover the same number of bytes that are malloc'd.
841 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
842 return nullptr;
843
844 // Replace the malloc with a calloc. We need the data layout to know what the
845 // actual size of a 'size_t' parameter is.
846 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
847 const DataLayout &DL = Malloc->getModule()->getDataLayout();
848 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
849 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
850 Malloc->getArgOperand(0), Malloc->getAttributes(),
851 B, TLI);
852 if (!Calloc)
853 return nullptr;
854
855 Malloc->replaceAllUsesWith(Calloc);
856 Malloc->eraseFromParent();
857
858 return Calloc;
859}
860
Chris Bienemanad070d02014-09-17 20:55:46 +0000861Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000862 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
863 return Calloc;
864
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000865 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000866 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
867 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
868 return CI->getArgOperand(0);
869}
Meador Inged4825782012-11-11 06:49:03 +0000870
Sanjay Patelb2ab3f22018-04-18 14:21:31 +0000871Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
872 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
873 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
874
875 return nullptr;
876}
877
Meador Inge193e0352012-11-13 04:16:17 +0000878//===----------------------------------------------------------------------===//
879// Math Library Optimizations
880//===----------------------------------------------------------------------===//
881
Matthias Braund34e4d22014-12-03 21:46:33 +0000882/// Return a variant of Val with float type.
883/// Currently this works in two cases: If Val is an FPExtension of a float
884/// value to something bigger, simply return the operand.
885/// If Val is a ConstantFP but can be converted to a float ConstantFP without
886/// loss of precision do so.
887static Value *valueHasFloatPrecision(Value *Val) {
888 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
889 Value *Op = Cast->getOperand(0);
890 if (Op->getType()->isFloatTy())
891 return Op;
892 }
893 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
894 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000895 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000896 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000897 &losesInfo);
898 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000899 return ConstantFP::get(Const->getContext(), F);
900 }
901 return nullptr;
902}
903
Sanjay Patel4e971da2016-01-21 18:01:57 +0000904/// Shrink double -> float for unary functions like 'floor'.
905static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
906 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000907 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000908 // We know this libcall has a valid prototype, but we don't know which.
909 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000910 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000911
Chris Bienemanad070d02014-09-17 20:55:46 +0000912 if (CheckRetType) {
913 // Check if all the uses for function like 'sin' are converted to float.
914 for (User *U : CI->users()) {
915 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
916 if (!Cast || !Cast->getType()->isFloatTy())
917 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000918 }
Meador Inge193e0352012-11-13 04:16:17 +0000919 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000920
921 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000922 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
923 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000924 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000925
Andrew Ng1606fc02017-04-25 12:36:14 +0000926 // If call isn't an intrinsic, check that it isn't within a function with the
927 // same name as the float version of this call.
928 //
929 // e.g. inline float expf(float val) { return (float) exp((double) val); }
930 //
931 // A similar such definition exists in the MinGW-w64 math.h header file which
932 // when compiled with -O2 -ffast-math causes the generation of infinite loops
933 // where expf is called.
934 if (!Callee->isIntrinsic()) {
935 const Function *F = CI->getFunction();
936 StringRef FName = F->getName();
937 StringRef CalleeName = Callee->getName();
938 if ((FName.size() == (CalleeName.size() + 1)) &&
939 (FName.back() == 'f') &&
940 FName.startswith(CalleeName))
941 return nullptr;
942 }
943
Sanjay Patelaa231142015-12-31 21:52:31 +0000944 // Propagate fast-math flags from the existing call to the new call.
945 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000946 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000947
948 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000949 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000950 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000951 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000952 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
953 V = B.CreateCall(F, V);
954 } else {
955 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000956 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000957 }
958
Chris Bienemanad070d02014-09-17 20:55:46 +0000959 return B.CreateFPExt(V, B.getDoubleTy());
960}
Meador Inge193e0352012-11-13 04:16:17 +0000961
Matt Arsenault954a6242017-01-23 23:55:08 +0000962// Replace a libcall \p CI with a call to intrinsic \p IID
963static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
964 // Propagate fast-math flags from the existing call to the new call.
965 IRBuilder<>::FastMathFlagGuard Guard(B);
966 B.setFastMathFlags(CI->getFastMathFlags());
967
968 Module *M = CI->getModule();
969 Value *V = CI->getArgOperand(0);
970 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
971 CallInst *NewCall = B.CreateCall(F, V);
972 NewCall->takeName(CI);
973 return NewCall;
974}
975
Sanjay Patel4e971da2016-01-21 18:01:57 +0000976/// Shrink double -> float for binary functions like 'fmin/fmax'.
977static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000978 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000979 // We know this libcall has a valid prototype, but we don't know which.
980 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000981 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000982
Chris Bienemanad070d02014-09-17 20:55:46 +0000983 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000984 // or fmin(1.0, (double)floatval), then we convert it to fminf.
985 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
986 if (V1 == nullptr)
987 return nullptr;
988 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
989 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000990 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000991
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000992 // Propagate fast-math flags from the existing call to the new call.
993 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000994 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000995
Chris Bienemanad070d02014-09-17 20:55:46 +0000996 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +0000997 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +0000998 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +0000999 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001000 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001001 return B.CreateFPExt(V, B.getDoubleTy());
1002}
1003
Hal Finkel2ff24732017-12-16 01:26:25 +00001004// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1005Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1006 if (!CI->isFast())
1007 return nullptr;
1008
1009 // Propagate fast-math flags from the existing call to new instructions.
1010 IRBuilder<>::FastMathFlagGuard Guard(B);
1011 B.setFastMathFlags(CI->getFastMathFlags());
1012
1013 Value *Real, *Imag;
1014 if (CI->getNumArgOperands() == 1) {
1015 Value *Op = CI->getArgOperand(0);
1016 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1017 Real = B.CreateExtractValue(Op, 0, "real");
1018 Imag = B.CreateExtractValue(Op, 1, "imag");
1019 } else {
1020 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1021 Real = CI->getArgOperand(0);
1022 Imag = CI->getArgOperand(1);
1023 }
1024
1025 Value *RealReal = B.CreateFMul(Real, Real);
1026 Value *ImagImag = B.CreateFMul(Imag, Imag);
1027
1028 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1029 CI->getType());
1030 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1031}
1032
Chris Bienemanad070d02014-09-17 20:55:46 +00001033Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1034 Function *Callee = CI->getCalledFunction();
1035 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001036 StringRef Name = Callee->getName();
1037 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001038 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001039
Chris Bienemanad070d02014-09-17 20:55:46 +00001040 // cos(-x) -> cos(x)
1041 Value *Op1 = CI->getArgOperand(0);
1042 if (BinaryOperator::isFNeg(Op1)) {
1043 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1044 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1045 }
1046 return Ret;
1047}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001048
Weiming Zhao82130722015-12-04 22:00:47 +00001049static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1050 // Multiplications calculated using Addition Chains.
1051 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1052
1053 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1054
1055 if (InnerChain[Exp])
1056 return InnerChain[Exp];
1057
1058 static const unsigned AddChain[33][2] = {
1059 {0, 0}, // Unused.
1060 {0, 0}, // Unused (base case = pow1).
1061 {1, 1}, // Unused (pre-computed).
1062 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1063 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1064 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1065 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1066 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1067 };
1068
1069 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1070 getPow(InnerChain, AddChain[Exp][1], B));
1071 return InnerChain[Exp];
1072}
1073
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001074/// Use square root in place of pow(x, +/-0.5).
1075Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1076 // TODO: There is some subset of 'fast' under which these transforms should
1077 // be allowed.
1078 if (!Pow->isFast())
1079 return nullptr;
1080
Sanjay Patel9771a962017-11-19 16:42:27 +00001081 const APFloat *Arg1C;
1082 if (!match(Pow->getArgOperand(1), m_APFloat(Arg1C)))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001083 return nullptr;
Sanjay Patel9771a962017-11-19 16:42:27 +00001084 if (!Arg1C->isExactlyValue(0.5) && !Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001085 return nullptr;
1086
1087 // Fast-math flags from the pow() are propagated to all replacement ops.
1088 IRBuilder<>::FastMathFlagGuard Guard(B);
1089 B.setFastMathFlags(Pow->getFastMathFlags());
1090 Type *Ty = Pow->getType();
1091 Value *Sqrt;
1092 if (Pow->hasFnAttr(Attribute::ReadNone)) {
1093 // We know that errno is never set, so replace with an intrinsic:
1094 // pow(x, 0.5) --> llvm.sqrt(x)
1095 // llvm.pow(x, 0.5) --> llvm.sqrt(x)
1096 auto *F = Intrinsic::getDeclaration(Pow->getModule(), Intrinsic::sqrt, Ty);
1097 Sqrt = B.CreateCall(F, Pow->getArgOperand(0));
1098 } else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf,
1099 LibFunc_sqrtl)) {
1100 // Errno could be set, so we must use a sqrt libcall.
1101 // TODO: We also should check that the target can in fact lower the sqrt
1102 // libcall. We currently have no way to ask this question, so we ask
1103 // whether the target has a sqrt libcall which is not exactly the same.
1104 Sqrt = emitUnaryFloatFnCall(Pow->getArgOperand(0),
1105 TLI->getName(LibFunc_sqrt), B,
1106 Pow->getCalledFunction()->getAttributes());
1107 } else {
1108 // We can't replace with an intrinsic or a libcall.
1109 return nullptr;
1110 }
1111
1112 // If this is pow(x, -0.5), get the reciprocal.
Sanjay Patel9771a962017-11-19 16:42:27 +00001113 if (Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001114 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt);
1115
1116 return Sqrt;
1117}
1118
Chris Bienemanad070d02014-09-17 20:55:46 +00001119Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1120 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001121 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001122 StringRef Name = Callee->getName();
1123 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001124 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001125
Chris Bienemanad070d02014-09-17 20:55:46 +00001126 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001127
1128 // pow(1.0, x) -> 1.0
1129 if (match(Op1, m_SpecificFP(1.0)))
1130 return Op1;
1131 // pow(2.0, x) -> llvm.exp2(x)
1132 if (match(Op1, m_SpecificFP(2.0))) {
1133 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1134 CI->getType());
1135 return B.CreateCall(Exp2, Op2, "exp2");
1136 }
1137
1138 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1139 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001140 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001141 // pow(10.0, x) -> exp10(x)
1142 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001143 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1144 LibFunc_exp10l))
1145 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001146 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001147 }
1148
Sanjay Patel6002e782016-01-12 17:30:37 +00001149 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001150 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001151 // We enable these only with fast-math. Besides rounding differences, the
1152 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001153 // Example: x = 1000, y = 0.001.
1154 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001155 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patel629c4112017-11-06 16:27:15 +00001156 if (OpC && OpC->isFast() && CI->isFast()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001157 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001158 Function *OpCCallee = OpC->getCalledFunction();
1159 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001160 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001161 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001162 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001163 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001164 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001165 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001166 }
1167 }
1168
Sanjay Patel9771a962017-11-19 16:42:27 +00001169 if (Value *Sqrt = replacePowWithSqrt(CI, B))
1170 return Sqrt;
1171
Chris Bienemanad070d02014-09-17 20:55:46 +00001172 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1173 if (!Op2C)
1174 return Ret;
1175
1176 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1177 return ConstantFP::get(CI->getType(), 1.0);
1178
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001179 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
Chris Bienemanad070d02014-09-17 20:55:46 +00001180 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001181 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1182 LibFunc_sqrtl)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001183 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1184 // This is faster than calling pow, and still handles negative zero
1185 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001186 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1187 Value *Inf = ConstantFP::getInfinity(CI->getType());
1188 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001189
1190 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1191 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001192 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001193
1194 Module *M = Callee->getParent();
1195 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1196 CI->getType());
1197 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1198
Chris Bienemanad070d02014-09-17 20:55:46 +00001199 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1200 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1201 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001202 }
1203
Sanjay Patelb23e1482017-12-10 17:25:54 +00001204 // Propagate fast-math-flags from the call to any created instructions.
1205 IRBuilder<>::FastMathFlagGuard Guard(B);
1206 B.setFastMathFlags(CI->getFastMathFlags());
1207 // pow(x, 1.0) --> x
1208 if (Op2C->isExactlyValue(1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001209 return Op1;
Sanjay Patelb23e1482017-12-10 17:25:54 +00001210 // pow(x, 2.0) --> x * x
1211 if (Op2C->isExactlyValue(2.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001212 return B.CreateFMul(Op1, Op1, "pow2");
Sanjay Patelb23e1482017-12-10 17:25:54 +00001213 // pow(x, -1.0) --> 1.0 / x
1214 if (Op2C->isExactlyValue(-1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001215 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001216
1217 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel629c4112017-11-06 16:27:15 +00001218 if (CI->isFast()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001219 APFloat V = abs(Op2C->getValueAPF());
1220 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1221 // This transformation applies to integer exponents only.
1222 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1223 !V.isInteger())
1224 return nullptr;
1225
1226 // We will memoize intermediate products of the Addition Chain.
1227 Value *InnerChain[33] = {nullptr};
1228 InnerChain[1] = Op1;
1229 InnerChain[2] = B.CreateFMul(Op1, Op1);
1230
1231 // We cannot readily convert a non-double type (like float) to a double.
1232 // So we first convert V to something which could be converted to double.
Sanjay Patelb23e1482017-12-10 17:25:54 +00001233 bool Ignored;
1234 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001235
Weiming Zhao82130722015-12-04 22:00:47 +00001236 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1237 // For negative exponents simply compute the reciprocal.
1238 if (Op2C->isNegative())
1239 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1240 return FMul;
1241 }
1242
Chris Bienemanad070d02014-09-17 20:55:46 +00001243 return nullptr;
1244}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001245
Chris Bienemanad070d02014-09-17 20:55:46 +00001246Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1247 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001248 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001249 StringRef Name = Callee->getName();
1250 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001251 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001252
Chris Bienemanad070d02014-09-17 20:55:46 +00001253 Value *Op = CI->getArgOperand(0);
1254 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1255 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001256 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001257 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001258 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001259 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001260 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001261
1262 if (TLI->has(LdExp)) {
1263 Value *LdExpArg = nullptr;
1264 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1265 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1266 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1267 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1268 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1269 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1270 }
1271
1272 if (LdExpArg) {
1273 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1274 if (!Op->getType()->isFloatTy())
1275 One = ConstantExpr::getFPExtend(One, Op->getType());
1276
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001277 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001278 Value *NewCallee =
1279 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001280 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001281 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001282 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1283 CI->setCallingConv(F->getCallingConv());
1284
1285 return CI;
1286 }
1287 }
1288 return Ret;
1289}
1290
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001291Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001292 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001293 // If we can shrink the call to a float function rather than a double
1294 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001295 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001296 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1297 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001298 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001299
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001300 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001301 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001302 if (CI->isFast()) {
1303 // If the call is 'fast', then anything we create here will also be 'fast'.
1304 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001305 } else {
1306 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001307 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001308 return nullptr;
1309 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1310 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001311 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001312 // might be impractical."
1313 FMF.setNoSignedZeros();
1314 FMF.setNoNaNs();
1315 }
Sanjay Patela2528152016-01-12 18:03:37 +00001316 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001317
1318 // We have a relaxed floating-point environment. We can ignore NaN-handling
1319 // and transform to a compare and select. We do not have to consider errno or
1320 // exceptions, because fmin/fmax do not have those.
1321 Value *Op0 = CI->getArgOperand(0);
1322 Value *Op1 = CI->getArgOperand(1);
1323 Value *Cmp = Callee->getName().startswith("fmin") ?
1324 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1325 return B.CreateSelect(Cmp, Op0, Op1);
1326}
1327
Davide Italianob8b71332015-11-29 20:58:04 +00001328Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1329 Function *Callee = CI->getCalledFunction();
1330 Value *Ret = nullptr;
1331 StringRef Name = Callee->getName();
1332 if (UnsafeFPShrink && hasFloatVersion(Name))
1333 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001334
Sanjay Patel629c4112017-11-06 16:27:15 +00001335 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001336 return Ret;
1337 Value *Op1 = CI->getArgOperand(0);
1338 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001339
Sanjay Patel629c4112017-11-06 16:27:15 +00001340 // The earlier call must also be 'fast' in order to do these transforms.
1341 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001342 return Ret;
1343
1344 // log(pow(x,y)) -> y*log(x)
1345 // This is only applicable to log, log2, log10.
1346 if (Name != "log" && Name != "log2" && Name != "log10")
1347 return Ret;
1348
1349 IRBuilder<>::FastMathFlagGuard Guard(B);
1350 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001351 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001352 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001353
David L. Jonesd21529f2017-01-23 23:16:46 +00001354 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001355 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001356 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001357 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001358 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001359 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001360 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001361
1362 // log(exp2(y)) -> y*log(2)
1363 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001364 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001365 return B.CreateFMul(
1366 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001367 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001368 Callee->getName(), B, Callee->getAttributes()),
1369 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001370 return Ret;
1371}
1372
Sanjay Patelc699a612014-10-16 18:48:17 +00001373Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1374 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001375 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001376 // TODO: Once we have a way (other than checking for the existince of the
1377 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1378 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001379 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001380 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001381 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001382
Sanjay Patel629c4112017-11-06 16:27:15 +00001383 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001384 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001385
Sanjay Patelc2d64612016-01-06 20:52:21 +00001386 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001387 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001388 return Ret;
1389
1390 // We're looking for a repeated factor in a multiplication tree,
1391 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001392 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001393 Value *Op0 = I->getOperand(0);
1394 Value *Op1 = I->getOperand(1);
1395 Value *RepeatOp = nullptr;
1396 Value *OtherOp = nullptr;
1397 if (Op0 == Op1) {
1398 // Simple match: the operands of the multiply are identical.
1399 RepeatOp = Op0;
1400 } else {
1401 // Look for a more complicated pattern: one of the operands is itself
1402 // a multiply, so search for a common factor in that multiply.
1403 // Note: We don't bother looking any deeper than this first level or for
1404 // variations of this pattern because instcombine's visitFMUL and/or the
1405 // reassociation pass should give us this form.
1406 Value *OtherMul0, *OtherMul1;
1407 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1408 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001409 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001410 // Matched: sqrt((x * x) * z)
1411 RepeatOp = OtherMul0;
1412 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001413 }
1414 }
1415 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001416 if (!RepeatOp)
1417 return Ret;
1418
1419 // Fast math flags for any created instructions should match the sqrt
1420 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001421 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001422 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001423
Sanjay Patelc2d64612016-01-06 20:52:21 +00001424 // If we found a repeated factor, hoist it out of the square root and
1425 // replace it with the fabs of that factor.
1426 Module *M = Callee->getParent();
1427 Type *ArgType = I->getType();
1428 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1429 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1430 if (OtherOp) {
1431 // If we found a non-repeated factor, we still need to get its square
1432 // root. We then multiply that by the value that was simplified out
1433 // of the square root calculation.
1434 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1435 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1436 return B.CreateFMul(FabsCall, SqrtCall);
1437 }
1438 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001439}
1440
Sanjay Patelcddcd722016-01-06 19:23:35 +00001441// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001442Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1443 Function *Callee = CI->getCalledFunction();
1444 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001445 StringRef Name = Callee->getName();
1446 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001447 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001448
Davide Italiano51507d22015-11-04 23:36:56 +00001449 Value *Op1 = CI->getArgOperand(0);
1450 auto *OpC = dyn_cast<CallInst>(Op1);
1451 if (!OpC)
1452 return Ret;
1453
Sanjay Patel629c4112017-11-06 16:27:15 +00001454 // Both calls must be 'fast' in order to remove them.
1455 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001456 return Ret;
1457
Davide Italiano51507d22015-11-04 23:36:56 +00001458 // tan(atan(x)) -> x
1459 // tanf(atanf(x)) -> x
1460 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001461 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001462 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001463 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001464 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1465 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1466 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001467 Ret = OpC->getArgOperand(0);
1468 return Ret;
1469}
1470
Sanjay Patel57747212016-01-21 23:38:43 +00001471static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001472 // We can only hope to do anything useful if we can ignore things like errno
1473 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001474 // We already checked the prototype.
1475 return CI->hasFnAttr(Attribute::NoUnwind) &&
1476 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001477}
1478
Chris Bienemanad070d02014-09-17 20:55:46 +00001479static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1480 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001481 Value *&SinCos) {
1482 Type *ArgTy = Arg->getType();
1483 Type *ResTy;
1484 StringRef Name;
1485
1486 Triple T(OrigCallee->getParent()->getTargetTriple());
1487 if (UseFloat) {
1488 Name = "__sincospif_stret";
1489
1490 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1491 // x86_64 can't use {float, float} since that would be returned in both
1492 // xmm0 and xmm1, which isn't what a real struct would do.
1493 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001494 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1495 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001496 } else {
1497 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001498 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001499 }
1500
1501 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001502 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001503 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001504
1505 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1506 // If the argument is an instruction, it must dominate all uses so put our
1507 // sincos call there.
1508 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1509 } else {
1510 // Otherwise (e.g. for a constant) the beginning of the function is as
1511 // good a place as any.
1512 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1513 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1514 }
1515
1516 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1517
1518 if (SinCos->getType()->isStructTy()) {
1519 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1520 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1521 } else {
1522 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1523 "sinpi");
1524 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1525 "cospi");
1526 }
1527}
Chris Bienemanad070d02014-09-17 20:55:46 +00001528
1529Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001530 // Make sure the prototype is as expected, otherwise the rest of the
1531 // function is probably invalid and likely to abort.
1532 if (!isTrigLibCall(CI))
1533 return nullptr;
1534
1535 Value *Arg = CI->getArgOperand(0);
1536 SmallVector<CallInst *, 1> SinCalls;
1537 SmallVector<CallInst *, 1> CosCalls;
1538 SmallVector<CallInst *, 1> SinCosCalls;
1539
1540 bool IsFloat = Arg->getType()->isFloatTy();
1541
1542 // Look for all compatible sinpi, cospi and sincospi calls with the same
1543 // argument. If there are enough (in some sense) we can make the
1544 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001545 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001546 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001547 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001548
1549 // It's only worthwhile if both sinpi and cospi are actually used.
1550 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1551 return nullptr;
1552
1553 Value *Sin, *Cos, *SinCos;
1554 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1555
Davide Italianof024a562016-12-16 02:28:38 +00001556 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1557 Value *Res) {
1558 for (CallInst *C : Calls)
1559 replaceAllUsesWith(C, Res);
1560 };
1561
Chris Bienemanad070d02014-09-17 20:55:46 +00001562 replaceTrigInsts(SinCalls, Sin);
1563 replaceTrigInsts(CosCalls, Cos);
1564 replaceTrigInsts(SinCosCalls, SinCos);
1565
1566 return nullptr;
1567}
1568
David Majnemerabae6b52016-03-19 04:53:02 +00001569void LibCallSimplifier::classifyArgUse(
1570 Value *Val, Function *F, bool IsFloat,
1571 SmallVectorImpl<CallInst *> &SinCalls,
1572 SmallVectorImpl<CallInst *> &CosCalls,
1573 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001574 CallInst *CI = dyn_cast<CallInst>(Val);
1575
1576 if (!CI)
1577 return;
1578
David Majnemerabae6b52016-03-19 04:53:02 +00001579 // Don't consider calls in other functions.
1580 if (CI->getFunction() != F)
1581 return;
1582
Chris Bienemanad070d02014-09-17 20:55:46 +00001583 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001584 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001585 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001586 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001587 return;
1588
1589 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001590 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001591 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001592 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001593 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001594 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001595 SinCosCalls.push_back(CI);
1596 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001597 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001599 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001600 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001601 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001602 SinCosCalls.push_back(CI);
1603 }
1604}
1605
Meador Inge7415f842012-11-25 20:45:27 +00001606//===----------------------------------------------------------------------===//
1607// Integer Library Call Optimizations
1608//===----------------------------------------------------------------------===//
1609
Chris Bienemanad070d02014-09-17 20:55:46 +00001610Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001611 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001612 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001613 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001614 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1615 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001616 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001617 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1618 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001619
Chris Bienemanad070d02014-09-17 20:55:46 +00001620 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1621 return B.CreateSelect(Cond, V, B.getInt32(0));
1622}
Meador Ingea0b6d872012-11-26 00:24:07 +00001623
Davide Italiano85ad36b2016-12-15 23:45:11 +00001624Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1625 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1626 Value *Op = CI->getArgOperand(0);
1627 Type *ArgType = Op->getType();
1628 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1629 Intrinsic::ctlz, ArgType);
1630 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1631 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1632 V);
1633 return B.CreateIntCast(V, CI->getType(), false);
1634}
1635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001637 // abs(x) -> x >s -1 ? x : -x
1638 Value *Op = CI->getArgOperand(0);
1639 Value *Pos =
1640 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1641 Value *Neg = B.CreateNeg(Op, "neg");
1642 return B.CreateSelect(Pos, Op, Neg);
1643}
Meador Inge9a59ab62012-11-26 02:31:59 +00001644
Chris Bienemanad070d02014-09-17 20:55:46 +00001645Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001646 // isdigit(c) -> (c-'0') <u 10
1647 Value *Op = CI->getArgOperand(0);
1648 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1649 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1650 return B.CreateZExt(Op, CI->getType());
1651}
Meador Ingea62a39e2012-11-26 03:10:07 +00001652
Chris Bienemanad070d02014-09-17 20:55:46 +00001653Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001654 // isascii(c) -> c <u 128
1655 Value *Op = CI->getArgOperand(0);
1656 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1657 return B.CreateZExt(Op, CI->getType());
1658}
1659
1660Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001661 // toascii(c) -> c & 0x7f
1662 return B.CreateAnd(CI->getArgOperand(0),
1663 ConstantInt::get(CI->getType(), 0x7F));
1664}
Meador Inge604937d2012-11-26 03:38:52 +00001665
Meador Inge08ca1152012-11-26 20:37:20 +00001666//===----------------------------------------------------------------------===//
1667// Formatting and IO Library Call Optimizations
1668//===----------------------------------------------------------------------===//
1669
Chris Bienemanad070d02014-09-17 20:55:46 +00001670static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001671
Chris Bienemanad070d02014-09-17 20:55:46 +00001672Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1673 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001674 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001675 // Error reporting calls should be cold, mark them as such.
1676 // This applies even to non-builtin calls: it is only a hint and applies to
1677 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001678
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 // This heuristic was suggested in:
1680 // Improving Static Branch Prediction in a Compiler
1681 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1682 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001683 if (!CI->hasFnAttr(Attribute::Cold) &&
1684 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001685 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001686 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001687
Chris Bienemanad070d02014-09-17 20:55:46 +00001688 return nullptr;
1689}
1690
1691static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001692 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001693 return false;
1694
1695 if (StreamArg < 0)
1696 return true;
1697
1698 // These functions might be considered cold, but only if their stream
1699 // argument is stderr.
1700
1701 if (StreamArg >= (int)CI->getNumArgOperands())
1702 return false;
1703 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1704 if (!LI)
1705 return false;
1706 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1707 if (!GV || !GV->isDeclaration())
1708 return false;
1709 return GV->getName() == "stderr";
1710}
1711
1712Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1713 // Check for a fixed format string.
1714 StringRef FormatStr;
1715 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001716 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001717
Chris Bienemanad070d02014-09-17 20:55:46 +00001718 // Empty format string -> noop.
1719 if (FormatStr.empty()) // Tolerate printf's declared void.
1720 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001721
Chris Bienemanad070d02014-09-17 20:55:46 +00001722 // Do not do any of the following transformations if the printf return value
1723 // is used, in general the printf return value is not compatible with either
1724 // putchar() or puts().
1725 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001726 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001727
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001728 // printf("x") -> putchar('x'), even for "%" and "%%".
1729 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001730 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001731
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001732 // printf("%s", "a") --> putchar('a')
1733 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1734 StringRef ChrStr;
1735 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1736 return nullptr;
1737 if (ChrStr.size() != 1)
1738 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001739 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001740 }
1741
Chris Bienemanad070d02014-09-17 20:55:46 +00001742 // printf("foo\n") --> puts("foo")
1743 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1744 FormatStr.find('%') == StringRef::npos) { // No format characters.
1745 // Create a string literal with no \n on it. We expect the constant merge
1746 // pass to be run after this pass, to merge duplicate strings.
1747 FormatStr = FormatStr.drop_back();
1748 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001749 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001750 }
Meador Inge08ca1152012-11-26 20:37:20 +00001751
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 // Optimize specific format strings.
1753 // printf("%c", chr) --> putchar(chr)
1754 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001755 CI->getArgOperand(1)->getType()->isIntegerTy())
1756 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001757
1758 // printf("%s\n", str) --> puts(str)
1759 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001760 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001761 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001762 return nullptr;
1763}
1764
1765Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1766
1767 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 if (Value *V = optimizePrintFString(CI, B)) {
1770 return V;
1771 }
1772
1773 // printf(format, ...) -> iprintf(format, ...) if no floating point
1774 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001775 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001776 Module *M = B.GetInsertBlock()->getParent()->getParent();
1777 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001778 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001779 CallInst *New = cast<CallInst>(CI->clone());
1780 New->setCalledFunction(IPrintFFn);
1781 B.Insert(New);
1782 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001783 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001784 return nullptr;
1785}
Meador Inge08ca1152012-11-26 20:37:20 +00001786
Chris Bienemanad070d02014-09-17 20:55:46 +00001787Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1788 // Check for a fixed format string.
1789 StringRef FormatStr;
1790 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001791 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001792
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 // If we just have a format string (nothing else crazy) transform it.
1794 if (CI->getNumArgOperands() == 2) {
1795 // Make sure there's no % in the constant array. We could try to handle
1796 // %% -> % in the future if we cared.
1797 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1798 if (FormatStr[i] == '%')
1799 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001800
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001801 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1802 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001803 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001804 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001805 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001806 }
Meador Ingef8e72502012-11-29 15:45:43 +00001807
Chris Bienemanad070d02014-09-17 20:55:46 +00001808 // The remaining optimizations require the format string to be "%s" or "%c"
1809 // and have an extra operand.
1810 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1811 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001812 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001813
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 // Decode the second character of the format string.
1815 if (FormatStr[1] == 'c') {
1816 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1817 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1818 return nullptr;
1819 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001820 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001822 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001823 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001824
Chris Bienemanad070d02014-09-17 20:55:46 +00001825 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001826 }
1827
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001829 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1830 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1831 return nullptr;
1832
Sanjay Pateld3112a52016-01-19 19:46:10 +00001833 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001834 if (!Len)
1835 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001836 Value *IncLen =
1837 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001838 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00001839
1840 // The sprintf result is the unincremented number of bytes in the string.
1841 return B.CreateIntCast(Len, CI->getType(), false);
1842 }
1843 return nullptr;
1844}
1845
1846Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1847 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001848 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001849 if (Value *V = optimizeSPrintFString(CI, B)) {
1850 return V;
1851 }
1852
1853 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1854 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001855 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001856 Module *M = B.GetInsertBlock()->getParent()->getParent();
1857 Constant *SIPrintFFn =
1858 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1859 CallInst *New = cast<CallInst>(CI->clone());
1860 New->setCalledFunction(SIPrintFFn);
1861 B.Insert(New);
1862 return New;
1863 }
1864 return nullptr;
1865}
1866
1867Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1868 optimizeErrorReporting(CI, B, 0);
1869
1870 // All the optimizations depend on the format string.
1871 StringRef FormatStr;
1872 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1873 return nullptr;
1874
1875 // Do not do any of the following transformations if the fprintf return
1876 // value is used, in general the fprintf return value is not compatible
1877 // with fwrite(), fputc() or fputs().
1878 if (!CI->use_empty())
1879 return nullptr;
1880
1881 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1882 if (CI->getNumArgOperands() == 2) {
1883 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1884 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1885 return nullptr; // We found a format specifier.
1886
Sanjay Pateld3112a52016-01-19 19:46:10 +00001887 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001888 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001889 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001890 CI->getArgOperand(0), B, DL, TLI);
1891 }
1892
1893 // The remaining optimizations require the format string to be "%s" or "%c"
1894 // and have an extra operand.
1895 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1896 CI->getNumArgOperands() < 3)
1897 return nullptr;
1898
1899 // Decode the second character of the format string.
1900 if (FormatStr[1] == 'c') {
1901 // fprintf(F, "%c", chr) --> fputc(chr, F)
1902 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1903 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001904 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001905 }
1906
1907 if (FormatStr[1] == 's') {
1908 // fprintf(F, "%s", str) --> fputs(str, F)
1909 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1910 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001911 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001912 }
1913 return nullptr;
1914}
1915
1916Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1917 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001918 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001919 if (Value *V = optimizeFPrintFString(CI, B)) {
1920 return V;
1921 }
1922
1923 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1924 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001925 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001926 Module *M = B.GetInsertBlock()->getParent()->getParent();
1927 Constant *FIPrintFFn =
1928 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1929 CallInst *New = cast<CallInst>(CI->clone());
1930 New->setCalledFunction(FIPrintFFn);
1931 B.Insert(New);
1932 return New;
1933 }
1934 return nullptr;
1935}
1936
1937Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1938 optimizeErrorReporting(CI, B, 3);
1939
Chris Bienemanad070d02014-09-17 20:55:46 +00001940 // Get the element size and count.
1941 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1942 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1943 if (!SizeC || !CountC)
1944 return nullptr;
1945 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1946
1947 // If this is writing zero records, remove the call (it's a noop).
1948 if (Bytes == 0)
1949 return ConstantInt::get(CI->getType(), 0);
1950
1951 // If this is writing one byte, turn it into fputc.
1952 // This optimisation is only valid, if the return value is unused.
1953 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001954 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1955 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001956 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1957 }
1958
1959 return nullptr;
1960}
1961
1962Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1963 optimizeErrorReporting(CI, B, 1);
1964
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001965 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1966 // requires more arguments and thus extra MOVs are required.
1967 if (CI->getParent()->getParent()->optForSize())
1968 return nullptr;
1969
Ahmed Bougachad765a822016-04-27 19:04:35 +00001970 // We can't optimize if return value is used.
1971 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001972 return nullptr;
1973
1974 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1975 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1976 if (!Len)
1977 return nullptr;
1978
1979 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001980 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001981 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001982 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001983 CI->getArgOperand(1), B, DL, TLI);
1984}
1985
1986Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001987 // Check for a constant string.
1988 StringRef Str;
1989 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1990 return nullptr;
1991
1992 if (Str.empty() && CI->use_empty()) {
1993 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001994 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001995 if (CI->use_empty() || !Res)
1996 return Res;
1997 return B.CreateIntCast(Res, CI->getType(), true);
1998 }
1999
2000 return nullptr;
2001}
2002
2003bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002004 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002005 SmallString<20> FloatFuncName = FuncName;
2006 FloatFuncName += 'f';
2007 if (TLI->getLibFunc(FloatFuncName, Func))
2008 return TLI->has(Func);
2009 return false;
2010}
Meador Inge7fb2f732012-10-13 16:45:32 +00002011
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002012Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2013 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002014 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002015 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002016 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002017 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002018 // Make sure we never change the calling convention.
2019 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002020 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002021 "Optimizing string/memory libcall would change the calling convention");
2022 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002024 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002025 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002026 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002027 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002028 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002029 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002030 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002031 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002032 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002033 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002034 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002035 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002036 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002037 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002038 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002039 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002040 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002041 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002042 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002043 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002044 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002045 case LibFunc_strtol:
2046 case LibFunc_strtod:
2047 case LibFunc_strtof:
2048 case LibFunc_strtoul:
2049 case LibFunc_strtoll:
2050 case LibFunc_strtold:
2051 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002052 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002053 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002054 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002055 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002056 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002057 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002058 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002059 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002060 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002061 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002062 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002063 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002064 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002065 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002066 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002067 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002068 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002069 case LibFunc_realloc:
2070 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002071 case LibFunc_wcslen:
2072 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002073 default:
2074 break;
2075 }
2076 }
2077 return nullptr;
2078}
2079
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002080Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2081 LibFunc Func,
2082 IRBuilder<> &Builder) {
2083 // Don't optimize calls that require strict floating point semantics.
2084 if (CI->isStrictFP())
2085 return nullptr;
2086
2087 switch (Func) {
2088 case LibFunc_cosf:
2089 case LibFunc_cos:
2090 case LibFunc_cosl:
2091 return optimizeCos(CI, Builder);
2092 case LibFunc_sinpif:
2093 case LibFunc_sinpi:
2094 case LibFunc_cospif:
2095 case LibFunc_cospi:
2096 return optimizeSinCosPi(CI, Builder);
2097 case LibFunc_powf:
2098 case LibFunc_pow:
2099 case LibFunc_powl:
2100 return optimizePow(CI, Builder);
2101 case LibFunc_exp2l:
2102 case LibFunc_exp2:
2103 case LibFunc_exp2f:
2104 return optimizeExp2(CI, Builder);
2105 case LibFunc_fabsf:
2106 case LibFunc_fabs:
2107 case LibFunc_fabsl:
2108 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2109 case LibFunc_sqrtf:
2110 case LibFunc_sqrt:
2111 case LibFunc_sqrtl:
2112 return optimizeSqrt(CI, Builder);
2113 case LibFunc_log:
2114 case LibFunc_log10:
2115 case LibFunc_log1p:
2116 case LibFunc_log2:
2117 case LibFunc_logb:
2118 return optimizeLog(CI, Builder);
2119 case LibFunc_tan:
2120 case LibFunc_tanf:
2121 case LibFunc_tanl:
2122 return optimizeTan(CI, Builder);
2123 case LibFunc_ceil:
2124 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2125 case LibFunc_floor:
2126 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2127 case LibFunc_round:
2128 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2129 case LibFunc_nearbyint:
2130 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2131 case LibFunc_rint:
2132 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2133 case LibFunc_trunc:
2134 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2135 case LibFunc_acos:
2136 case LibFunc_acosh:
2137 case LibFunc_asin:
2138 case LibFunc_asinh:
2139 case LibFunc_atan:
2140 case LibFunc_atanh:
2141 case LibFunc_cbrt:
2142 case LibFunc_cosh:
2143 case LibFunc_exp:
2144 case LibFunc_exp10:
2145 case LibFunc_expm1:
2146 case LibFunc_sin:
2147 case LibFunc_sinh:
2148 case LibFunc_tanh:
2149 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2150 return optimizeUnaryDoubleFP(CI, Builder, true);
2151 return nullptr;
2152 case LibFunc_copysign:
2153 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2154 return optimizeBinaryDoubleFP(CI, Builder);
2155 return nullptr;
2156 case LibFunc_fminf:
2157 case LibFunc_fmin:
2158 case LibFunc_fminl:
2159 case LibFunc_fmaxf:
2160 case LibFunc_fmax:
2161 case LibFunc_fmaxl:
2162 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002163 case LibFunc_cabs:
2164 case LibFunc_cabsf:
2165 case LibFunc_cabsl:
2166 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002167 default:
2168 return nullptr;
2169 }
2170}
2171
Chris Bienemanad070d02014-09-17 20:55:46 +00002172Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002173 // TODO: Split out the code below that operates on FP calls so that
2174 // we can all non-FP calls with the StrictFP attribute to be
2175 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002176 if (CI->isNoBuiltin())
2177 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002178
David L. Jonesd21529f2017-01-23 23:16:46 +00002179 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002180 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002181
2182 SmallVector<OperandBundleDef, 2> OpBundles;
2183 CI->getOperandBundlesAsDefs(OpBundles);
2184 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002185 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002186
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002187 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002188 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002189 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002190 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2191 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002192 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002193 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002194
Sanjay Patel848309d2014-10-23 21:52:45 +00002195 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002196 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002197 if (!isCallingConvC)
2198 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002199 // The FP intrinsics have corresponding constrained versions so we don't
2200 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002201 switch (II->getIntrinsicID()) {
2202 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002203 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002204 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002205 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002206 case Intrinsic::log:
2207 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002208 case Intrinsic::sqrt:
2209 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002210 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002211 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002212 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002213 }
2214 }
2215
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002216 // Also try to simplify calls to fortified library functions.
2217 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2218 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002219 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002220 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2221 // Use an IR Builder from SimplifiedCI if available instead of CI
2222 // to guarantee we reach all uses we might replace later on.
2223 IRBuilder<> TmpBuilder(SimplifiedCI);
2224 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002225 // If we were able to further simplify, remove the now redundant call.
2226 SimplifiedCI->replaceAllUsesWith(V);
2227 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002228 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002229 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002230 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002231 return SimplifiedFortifiedCI;
2232 }
2233
Meador Inge20255ef2013-03-12 00:08:29 +00002234 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002235 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002236 // We never change the calling convention.
2237 if (!ignoreCallingConv(Func) && !isCallingConvC)
2238 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002239 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2240 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002241 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2242 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002243 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002244 case LibFunc_ffs:
2245 case LibFunc_ffsl:
2246 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002247 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002248 case LibFunc_fls:
2249 case LibFunc_flsl:
2250 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002251 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002252 case LibFunc_abs:
2253 case LibFunc_labs:
2254 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002255 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002256 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002257 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002258 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002259 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002260 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002261 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002262 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002263 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002264 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002265 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002266 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002267 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002268 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002269 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002270 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002271 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002272 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002273 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002274 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002275 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002276 case LibFunc_vfprintf:
2277 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002278 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002279 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002280 return optimizeErrorReporting(CI, Builder, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002281 default:
2282 return nullptr;
2283 }
Meador Inge20255ef2013-03-12 00:08:29 +00002284 }
Craig Topperf40110f2014-04-25 05:29:35 +00002285 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002286}
2287
Chandler Carruth92803822015-01-21 02:11:59 +00002288LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002289 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002290 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002291 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002292 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2293 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002294
2295void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2296 // Indirect through the replacer used in this instance.
2297 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002298}
2299
Meador Ingedfb08a22013-06-20 19:48:07 +00002300// TODO:
2301// Additional cases that we need to add to this file:
2302//
2303// cbrt:
2304// * cbrt(expN(X)) -> expN(x/3)
2305// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002306// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002307//
2308// exp, expf, expl:
2309// * exp(log(x)) -> x
2310//
2311// log, logf, logl:
2312// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002313// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002314// * log(exp10(y)) -> y*log(10)
2315// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002316//
Meador Ingedfb08a22013-06-20 19:48:07 +00002317// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002318// * pow(sqrt(x),y) -> pow(x,y*0.5)
2319// * pow(pow(x,y),z)-> pow(x,y*z)
2320//
Meador Ingedfb08a22013-06-20 19:48:07 +00002321// signbit:
2322// * signbit(cnst) -> cnst'
2323// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2324//
2325// sqrt, sqrtf, sqrtl:
2326// * sqrt(expN(x)) -> expN(x*0.5)
2327// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2328// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2329//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002330
2331//===----------------------------------------------------------------------===//
2332// Fortified Library Call Optimizations
2333//===----------------------------------------------------------------------===//
2334
2335bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2336 unsigned ObjSizeOp,
2337 unsigned SizeOp,
2338 bool isString) {
2339 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2340 return true;
2341 if (ConstantInt *ObjSizeCI =
2342 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002343 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002344 return true;
2345 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2346 if (OnlyLowerUnknownSize)
2347 return false;
2348 if (isString) {
2349 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2350 // If the length is 0 we don't know how long it is and so we can't
2351 // remove the check.
2352 if (Len == 0)
2353 return false;
2354 return ObjSizeCI->getZExtValue() >= Len;
2355 }
2356 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2357 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2358 }
2359 return false;
2360}
2361
Sanjay Pateld707db92015-12-31 16:10:49 +00002362Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2363 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002364 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002365 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2366 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002367 return CI->getArgOperand(0);
2368 }
2369 return nullptr;
2370}
2371
Sanjay Pateld707db92015-12-31 16:10:49 +00002372Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2373 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002374 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002375 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2376 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002377 return CI->getArgOperand(0);
2378 }
2379 return nullptr;
2380}
2381
Sanjay Pateld707db92015-12-31 16:10:49 +00002382Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2383 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002384 // TODO: Try foldMallocMemset() here.
2385
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002386 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2387 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2388 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2389 return CI->getArgOperand(0);
2390 }
2391 return nullptr;
2392}
2393
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002394Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2395 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002396 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002397 Function *Callee = CI->getCalledFunction();
2398 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002399 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2401 *ObjSize = CI->getArgOperand(2);
2402
2403 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002404 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002405 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002406 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002407 }
2408
2409 // If a) we don't have any length information, or b) we know this will
2410 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2411 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2412 // TODO: It might be nice to get a maximum length out of the possible
2413 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002414 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002415 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416
David Blaikie65fab6d2015-04-03 21:32:06 +00002417 if (OnlyLowerUnknownSize)
2418 return nullptr;
2419
2420 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2421 uint64_t Len = GetStringLength(Src);
2422 if (Len == 0)
2423 return nullptr;
2424
2425 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2426 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002427 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002428 // If the function was an __stpcpy_chk, and we were able to fold it into
2429 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002430 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002431 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2432 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002433}
2434
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002435Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2436 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002437 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002438 Function *Callee = CI->getCalledFunction();
2439 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002440 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002441 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002442 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002443 return Ret;
2444 }
2445 return nullptr;
2446}
2447
2448Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002449 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2450 // Some clang users checked for _chk libcall availability using:
2451 // __has_builtin(__builtin___memcpy_chk)
2452 // When compiling with -fno-builtin, this is always true.
2453 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2454 // end up with fortified libcalls, which isn't acceptable in a freestanding
2455 // environment which only provides their non-fortified counterparts.
2456 //
2457 // Until we change clang and/or teach external users to check for availability
2458 // differently, disregard the "nobuiltin" attribute and TLI::has.
2459 //
2460 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002461
David L. Jonesd21529f2017-01-23 23:16:46 +00002462 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002463 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002464
2465 SmallVector<OperandBundleDef, 2> OpBundles;
2466 CI->getOperandBundlesAsDefs(OpBundles);
2467 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002468 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002469
Ahmed Bougachad765a822016-04-27 19:04:35 +00002470 // First, check that this is a known library functions and that the prototype
2471 // is correct.
2472 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002473 return nullptr;
2474
2475 // We never change the calling convention.
2476 if (!ignoreCallingConv(Func) && !isCallingConvC)
2477 return nullptr;
2478
2479 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002480 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002481 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002482 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002483 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002484 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002485 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002486 case LibFunc_stpcpy_chk:
2487 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002488 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002489 case LibFunc_stpncpy_chk:
2490 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002491 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002492 default:
2493 break;
2494 }
2495 return nullptr;
2496}
2497
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002498FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2499 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2500 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}