blob: 7dfaac886b76ee6177f59d3120f081a07734a7bc [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000021#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000022#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000028#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000032#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000034#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000036#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000037
38using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000039using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000040
Hal Finkel66cd3f12013-11-17 02:06:35 +000041static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000042 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46
47
Meador Ingedf796f82012-10-13 16:45:24 +000048//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000049// Helper Functions
50//===----------------------------------------------------------------------===//
51
David L. Jonesd21529f2017-01-23 23:16:46 +000052static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000055}
56
Sam Parker214f7bf2016-09-13 12:10:14 +000057static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
59 default:
60 return false;
61 case llvm::CallingConv::C:
62 return true;
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
66
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
70 return false;
71
72 auto *FuncTy = CI->getFunctionType();
73
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
77 return false;
78
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
81 return false;
82 }
83 return true;
84 }
85 }
86 return false;
87}
88
Sanjay Pateld707db92015-12-31 16:10:49 +000089/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000090static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000093 if (IC->isEquality() && IC->getOperand(1) == With)
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Meador Inge08ca1152012-11-26 20:37:20 +0000101static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000102 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000103 return OI->getType()->isFloatingPointTy();
104 });
Meador Inge08ca1152012-11-26 20:37:20 +0000105}
106
Meador Inged589ac62012-10-31 03:33:06 +0000107//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000108// String and Memory Library Call Optimizations
109//===----------------------------------------------------------------------===//
110
Chris Bienemanad070d02014-09-17 20:55:46 +0000111Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000112 // Extract some information from the instruction
113 Value *Dst = CI->getArgOperand(0);
114 Value *Src = CI->getArgOperand(1);
115
116 // See if we can get the length of the input string.
117 uint64_t Len = GetStringLength(Src);
118 if (Len == 0)
119 return nullptr;
120 --Len; // Unbias length.
121
122 // Handle the simple, do-nothing case: strcat(x, "") -> x
123 if (Len == 0)
124 return Dst;
125
Chris Bienemanad070d02014-09-17 20:55:46 +0000126 return emitStrLenMemCpy(Src, Dst, Len, B);
127}
128
129Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
130 IRBuilder<> &B) {
131 // We need to find the end of the destination string. That's where the
132 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000133 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000134 if (!DstLen)
135 return nullptr;
136
137 // Now that we have the destination's length, we must index into the
138 // destination's pointer to get the actual memcpy destination (end of
139 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000140 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000141
142 // We have enough information to now generate the memcpy call to do the
143 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000144 B.CreateMemCpy(CpyDst, 1, Src, 1,
145 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000146 return Dst;
147}
148
149Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000150 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000151 Value *Dst = CI->getArgOperand(0);
152 Value *Src = CI->getArgOperand(1);
153 uint64_t Len;
154
Sanjay Pateld707db92015-12-31 16:10:49 +0000155 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000156 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
157 Len = LengthArg->getZExtValue();
158 else
159 return nullptr;
160
161 // See if we can get the length of the input string.
162 uint64_t SrcLen = GetStringLength(Src);
163 if (SrcLen == 0)
164 return nullptr;
165 --SrcLen; // Unbias length.
166
167 // Handle the simple, do-nothing cases:
168 // strncat(x, "", c) -> x
169 // strncat(x, c, 0) -> x
170 if (SrcLen == 0 || Len == 0)
171 return Dst;
172
Sanjay Pateld707db92015-12-31 16:10:49 +0000173 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000174 if (Len < SrcLen)
175 return nullptr;
176
177 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000178 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000179 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
180}
181
182Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
183 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000184 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000185 Value *SrcStr = CI->getArgOperand(0);
186
187 // If the second operand is non-constant, see if we can compute the length
188 // of the input string and turn this into memchr.
189 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
190 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000191 uint64_t Len = GetStringLength(SrcStr);
192 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
193 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000194
Sanjay Pateld3112a52016-01-19 19:46:10 +0000195 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000196 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
197 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000198 }
199
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 // Otherwise, the character is a constant, see if the first argument is
201 // a string literal. If so, we can constant fold.
202 StringRef Str;
203 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000204 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000205 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000206 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 return nullptr;
208 }
209
210 // Compute the offset, make sure to handle the case when we're searching for
211 // zero (a weird way to spell strlen).
212 size_t I = (0xFF & CharC->getSExtValue()) == 0
213 ? Str.size()
214 : Str.find(CharC->getSExtValue());
215 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
216 return Constant::getNullValue(CI->getType());
217
218 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000219 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000220}
221
222Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000223 Value *SrcStr = CI->getArgOperand(0);
224 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
225
226 // Cannot fold anything if we're not looking for a constant.
227 if (!CharC)
228 return nullptr;
229
230 StringRef Str;
231 if (!getConstantStringInfo(SrcStr, Str)) {
232 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000234 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000235 return nullptr;
236 }
237
238 // Compute the offset.
239 size_t I = (0xFF & CharC->getSExtValue()) == 0
240 ? Str.size()
241 : Str.rfind(CharC->getSExtValue());
242 if (I == StringRef::npos) // Didn't find the char. Return null.
243 return Constant::getNullValue(CI->getType());
244
245 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000246 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000247}
248
249Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000250 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
251 if (Str1P == Str2P) // strcmp(x,x) -> 0
252 return ConstantInt::get(CI->getType(), 0);
253
254 StringRef Str1, Str2;
255 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
256 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
257
258 // strcmp(x, y) -> cnst (if both x and y are constant strings)
259 if (HasStr1 && HasStr2)
260 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
261
262 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
263 return B.CreateNeg(
264 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
265
266 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
267 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
268
269 // strcmp(P, "x") -> memcmp(P, "x", 2)
270 uint64_t Len1 = GetStringLength(Str1P);
271 uint64_t Len2 = GetStringLength(Str2P);
272 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000273 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000274 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000275 std::min(Len1, Len2)),
276 B, DL, TLI);
277 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000278
Chris Bienemanad070d02014-09-17 20:55:46 +0000279 return nullptr;
280}
281
282Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000283 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
284 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
285 return ConstantInt::get(CI->getType(), 0);
286
287 // Get the length argument if it is constant.
288 uint64_t Length;
289 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
290 Length = LengthArg->getZExtValue();
291 else
292 return nullptr;
293
294 if (Length == 0) // strncmp(x,y,0) -> 0
295 return ConstantInt::get(CI->getType(), 0);
296
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000298 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000299
300 StringRef Str1, Str2;
301 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
302 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
303
304 // strncmp(x, y) -> cnst (if both x and y are constant strings)
305 if (HasStr1 && HasStr2) {
306 StringRef SubStr1 = Str1.substr(0, Length);
307 StringRef SubStr2 = Str2.substr(0, Length);
308 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
309 }
310
311 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
312 return B.CreateNeg(
313 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
314
315 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
316 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
317
318 return nullptr;
319}
320
321Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000322 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
323 if (Dst == Src) // strcpy(x,x) -> x
324 return Src;
325
Chris Bienemanad070d02014-09-17 20:55:46 +0000326 // See if we can get the length of the input string.
327 uint64_t Len = GetStringLength(Src);
328 if (Len == 0)
329 return nullptr;
330
331 // We have enough information to now generate the memcpy call to do the
332 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000333 B.CreateMemCpy(Dst, 1, Src, 1,
334 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000335 return Dst;
336}
337
338Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
339 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000340 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
341 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000342 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000343 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000344 }
345
346 // See if we can get the length of the input string.
347 uint64_t Len = GetStringLength(Src);
348 if (Len == 0)
349 return nullptr;
350
Davide Italianob7487e62015-11-02 23:07:14 +0000351 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000353 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
354 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000355
356 // We have enough information to now generate the memcpy call to do the
357 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000358 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000359 return DstEnd;
360}
361
362Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
363 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000364 Value *Dst = CI->getArgOperand(0);
365 Value *Src = CI->getArgOperand(1);
366 Value *LenOp = CI->getArgOperand(2);
367
368 // See if we can get the length of the input string.
369 uint64_t SrcLen = GetStringLength(Src);
370 if (SrcLen == 0)
371 return nullptr;
372 --SrcLen;
373
374 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000375 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000376 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000377 return Dst;
378 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000379
Chris Bienemanad070d02014-09-17 20:55:46 +0000380 uint64_t Len;
381 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
382 Len = LengthArg->getZExtValue();
383 else
384 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000385
Chris Bienemanad070d02014-09-17 20:55:46 +0000386 if (Len == 0)
387 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000388
Chris Bienemanad070d02014-09-17 20:55:46 +0000389 // Let strncpy handle the zero padding
390 if (Len > SrcLen + 1)
391 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000392
Davide Italianob7487e62015-11-02 23:07:14 +0000393 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000394 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
395 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000396
Chris Bienemanad070d02014-09-17 20:55:46 +0000397 return Dst;
398}
Meador Inge7fb2f732012-10-13 16:45:32 +0000399
Matthias Braun50ec0b52017-05-19 22:37:09 +0000400Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
401 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000402 Value *Src = CI->getArgOperand(0);
403
404 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000405 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000406 return ConstantInt::get(CI->getType(), Len - 1);
407
David L Kreitzer752c1442016-04-13 14:31:06 +0000408 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000409 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000410 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000411 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000412 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000413 // subtraction. This will make the optimization more complex, and it's not
414 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000415 // very uncommon.
416 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000417 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000418 return nullptr;
419
Matthias Braun50ec0b52017-05-19 22:37:09 +0000420 ConstantDataArraySlice Slice;
421 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
422 uint64_t NullTermIdx;
423 if (Slice.Array == nullptr) {
424 NullTermIdx = 0;
425 } else {
426 NullTermIdx = ~((uint64_t)0);
427 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
428 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
429 NullTermIdx = I;
430 break;
431 }
432 }
433 // If the string does not have '\0', leave it to strlen to compute
434 // its length.
435 if (NullTermIdx == ~((uint64_t)0))
436 return nullptr;
437 }
438
David L Kreitzer752c1442016-04-13 14:31:06 +0000439 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000440 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000441 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000442 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000443 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
444
Matthias Braun50ec0b52017-05-19 22:37:09 +0000445 // KnownZero's bits are flipped, so zeros in KnownZero now represent
446 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000447 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000448 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000449 // unsigned-less-than NullTermIdx.
450 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000451 // If Offset is not provably in the range [0, NullTermIdx], we can still
452 // optimize if we can prove that the program has undefined behavior when
453 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000454 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000455 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000456 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000457 NullTermIdx == ArrSize - 1)) {
458 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
459 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000460 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000461 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 }
463
464 return nullptr;
465 }
466
Chris Bienemanad070d02014-09-17 20:55:46 +0000467 // strlen(x?"foo":"bars") --> x ? 3 : 4
468 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000469 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
470 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000471 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000472 ORE.emit([&]() {
473 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
474 << "folded strlen(select) to select of constants";
475 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000476 return B.CreateSelect(SI->getCondition(),
477 ConstantInt::get(CI->getType(), LenTrue - 1),
478 ConstantInt::get(CI->getType(), LenFalse - 1));
479 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000480 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000481
Chris Bienemanad070d02014-09-17 20:55:46 +0000482 // strlen(x) != 0 --> *x != 0
483 // strlen(x) == 0 --> *x == 0
484 if (isOnlyUsedInZeroEqualityComparison(CI))
485 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000486
Chris Bienemanad070d02014-09-17 20:55:46 +0000487 return nullptr;
488}
Meador Inge17418502012-10-13 16:45:37 +0000489
Matthias Braun50ec0b52017-05-19 22:37:09 +0000490Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
491 return optimizeStringLength(CI, B, 8);
492}
493
494Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
495 Module &M = *CI->getParent()->getParent()->getParent();
496 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000497 // We cannot perform this optimization without wchar_size metadata.
498 if (WCharSize == 0)
499 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000500
501 return optimizeStringLength(CI, B, WCharSize);
502}
503
Chris Bienemanad070d02014-09-17 20:55:46 +0000504Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 StringRef S1, S2;
506 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
507 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000508
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000509 // strpbrk(s, "") -> nullptr
510 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000511 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
512 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000513
Chris Bienemanad070d02014-09-17 20:55:46 +0000514 // Constant folding.
515 if (HasS1 && HasS2) {
516 size_t I = S1.find_first_of(S2);
517 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000518 return Constant::getNullValue(CI->getType());
519
Sanjay Pateld707db92015-12-31 16:10:49 +0000520 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
521 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000522 }
Meador Inge17418502012-10-13 16:45:37 +0000523
Chris Bienemanad070d02014-09-17 20:55:46 +0000524 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000525 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000526 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000527
528 return nullptr;
529}
530
531Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000532 Value *EndPtr = CI->getArgOperand(1);
533 if (isa<ConstantPointerNull>(EndPtr)) {
534 // With a null EndPtr, this function won't capture the main argument.
535 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000536 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000537 }
538
539 return nullptr;
540}
541
542Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000543 StringRef S1, S2;
544 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
545 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
546
547 // strspn(s, "") -> 0
548 // strspn("", s) -> 0
549 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
550 return Constant::getNullValue(CI->getType());
551
552 // Constant folding.
553 if (HasS1 && HasS2) {
554 size_t Pos = S1.find_first_not_of(S2);
555 if (Pos == StringRef::npos)
556 Pos = S1.size();
557 return ConstantInt::get(CI->getType(), Pos);
558 }
559
560 return nullptr;
561}
562
563Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000564 StringRef S1, S2;
565 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
566 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
567
568 // strcspn("", s) -> 0
569 if (HasS1 && S1.empty())
570 return Constant::getNullValue(CI->getType());
571
572 // Constant folding.
573 if (HasS1 && HasS2) {
574 size_t Pos = S1.find_first_of(S2);
575 if (Pos == StringRef::npos)
576 Pos = S1.size();
577 return ConstantInt::get(CI->getType(), Pos);
578 }
579
580 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000581 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000582 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000583
584 return nullptr;
585}
586
587Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000588 // fold strstr(x, x) -> x.
589 if (CI->getArgOperand(0) == CI->getArgOperand(1))
590 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
591
592 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000593 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000594 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000595 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000596 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000597 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000598 StrLen, B, DL, TLI);
599 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000600 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000601 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
602 ICmpInst *Old = cast<ICmpInst>(*UI++);
603 Value *Cmp =
604 B.CreateICmp(Old->getPredicate(), StrNCmp,
605 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
606 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000607 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000608 return CI;
609 }
Meador Inge17418502012-10-13 16:45:37 +0000610
Chris Bienemanad070d02014-09-17 20:55:46 +0000611 // See if either input string is a constant string.
612 StringRef SearchStr, ToFindStr;
613 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
614 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
615
616 // fold strstr(x, "") -> x.
617 if (HasStr2 && ToFindStr.empty())
618 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
619
620 // If both strings are known, constant fold it.
621 if (HasStr1 && HasStr2) {
622 size_t Offset = SearchStr.find(ToFindStr);
623
624 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000625 return Constant::getNullValue(CI->getType());
626
Chris Bienemanad070d02014-09-17 20:55:46 +0000627 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000628 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000629 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
630 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000631 }
Meador Inge17418502012-10-13 16:45:37 +0000632
Chris Bienemanad070d02014-09-17 20:55:46 +0000633 // fold strstr(x, "y") -> strchr(x, 'y').
634 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000635 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000636 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
637 }
638 return nullptr;
639}
Meador Inge40b6fac2012-10-15 03:47:37 +0000640
Benjamin Kramer691363e2015-03-21 15:36:21 +0000641Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000642 Value *SrcStr = CI->getArgOperand(0);
643 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
644 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
645
646 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000647 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000648 return Constant::getNullValue(CI->getType());
649
Benjamin Kramer7857d722015-03-21 21:09:33 +0000650 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000651 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000652 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000653 return nullptr;
654
655 // Truncate the string to LenC. If Str is smaller than LenC we will still only
656 // scan the string, as reading past the end of it is undefined and we can just
657 // return null if we don't find the char.
658 Str = Str.substr(0, LenC->getZExtValue());
659
Benjamin Kramer7857d722015-03-21 21:09:33 +0000660 // If the char is variable but the input str and length are not we can turn
661 // this memchr call into a simple bit field test. Of course this only works
662 // when the return value is only checked against null.
663 //
664 // It would be really nice to reuse switch lowering here but we can't change
665 // the CFG at this point.
666 //
667 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
668 // after bounds check.
669 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000670 unsigned char Max =
671 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
672 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000673
674 // Make sure the bit field we're about to create fits in a register on the
675 // target.
676 // FIXME: On a 64 bit architecture this prevents us from using the
677 // interesting range of alpha ascii chars. We could do better by emitting
678 // two bitfields or shifting the range by 64 if no lower chars are used.
679 if (!DL.fitsInLegalInteger(Max + 1))
680 return nullptr;
681
682 // For the bit field use a power-of-2 type with at least 8 bits to avoid
683 // creating unnecessary illegal types.
684 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
685
686 // Now build the bit field.
687 APInt Bitfield(Width, 0);
688 for (char C : Str)
689 Bitfield.setBit((unsigned char)C);
690 Value *BitfieldC = B.getInt(Bitfield);
691
692 // First check that the bit field access is within bounds.
693 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
694 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
695 "memchr.bounds");
696
697 // Create code that checks if the given bit is set in the field.
698 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
699 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
700
701 // Finally merge both checks and cast to pointer type. The inttoptr
702 // implicitly zexts the i1 to intptr type.
703 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
704 }
705
706 // Check if all arguments are constants. If so, we can constant fold.
707 if (!CharC)
708 return nullptr;
709
Benjamin Kramer691363e2015-03-21 15:36:21 +0000710 // Compute the offset.
711 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
712 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
713 return Constant::getNullValue(CI->getType());
714
715 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000716 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000717}
718
Chris Bienemanad070d02014-09-17 20:55:46 +0000719Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000721
Chris Bienemanad070d02014-09-17 20:55:46 +0000722 if (LHS == RHS) // memcmp(s,s,x) -> 0
723 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000724
Chris Bienemanad070d02014-09-17 20:55:46 +0000725 // Make sure we have a constant length.
726 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
727 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000728 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000729
Sanjay Patel70db4242017-06-09 14:22:03 +0000730 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000731 if (Len == 0) // memcmp(s1,s2,0) -> 0
732 return Constant::getNullValue(CI->getType());
733
734 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
735 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000736 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000737 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000738 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000739 CI->getType(), "rhsv");
740 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000741 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000742
Chad Rosierdc655322015-08-28 18:30:18 +0000743 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000744 // TODO: The case where both inputs are constants does not need to be limited
745 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000746 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000747 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
748 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
749
Sanjay Patel82ec8722017-08-21 19:13:14 +0000750 // First, see if we can fold either argument to a constant.
751 Value *LHSV = nullptr;
752 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
753 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
754 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
755 }
756 Value *RHSV = nullptr;
757 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
758 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
759 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
760 }
Chad Rosierdc655322015-08-28 18:30:18 +0000761
Sanjay Patel82ec8722017-08-21 19:13:14 +0000762 // Don't generate unaligned loads. If either source is constant data,
763 // alignment doesn't matter for that source because there is no load.
764 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
765 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
766 if (!LHSV) {
767 Type *LHSPtrTy =
768 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
769 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
770 }
771 if (!RHSV) {
772 Type *RHSPtrTy =
773 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
774 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
775 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000776 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000777 }
Chad Rosierdc655322015-08-28 18:30:18 +0000778 }
779
Sanjay Patel82ec8722017-08-21 19:13:14 +0000780 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
781 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000782 StringRef LHSStr, RHSStr;
783 if (getConstantStringInfo(LHS, LHSStr) &&
784 getConstantStringInfo(RHS, RHSStr)) {
785 // Make sure we're not reading out-of-bounds memory.
786 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000787 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000788 // Fold the memcmp and normalize the result. This way we get consistent
789 // results across multiple platforms.
790 uint64_t Ret = 0;
791 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
792 if (Cmp < 0)
793 Ret = -1;
794 else if (Cmp > 0)
795 Ret = 1;
796 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000797 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000798
Chris Bienemanad070d02014-09-17 20:55:46 +0000799 return nullptr;
800}
Meador Inge9a6a1902012-10-31 00:20:56 +0000801
Chris Bienemanad070d02014-09-17 20:55:46 +0000802Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000803 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
804 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
805 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000806 return CI->getArgOperand(0);
807}
Meador Inge05a625a2012-10-31 14:58:26 +0000808
Chris Bienemanad070d02014-09-17 20:55:46 +0000809Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000810 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
811 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
812 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000813 return CI->getArgOperand(0);
814}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000815
Sanjay Patel980b2802016-01-26 16:17:24 +0000816// TODO: Does this belong in BuildLibCalls or should all of those similar
817// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000818static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000819 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000820 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000821 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
822 return nullptr;
823
824 Module *M = B.GetInsertBlock()->getModule();
825 const DataLayout &DL = M->getDataLayout();
826 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
827 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000828 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000829 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
830
831 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
832 CI->setCallingConv(F->getCallingConv());
833
834 return CI;
835}
836
837/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
838static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
839 const TargetLibraryInfo &TLI) {
840 // This has to be a memset of zeros (bzero).
841 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
842 if (!FillValue || FillValue->getZExtValue() != 0)
843 return nullptr;
844
845 // TODO: We should handle the case where the malloc has more than one use.
846 // This is necessary to optimize common patterns such as when the result of
847 // the malloc is checked against null or when a memset intrinsic is used in
848 // place of a memset library call.
849 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
850 if (!Malloc || !Malloc->hasOneUse())
851 return nullptr;
852
853 // Is the inner call really malloc()?
854 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000855 if (!InnerCallee)
856 return nullptr;
857
David L. Jonesd21529f2017-01-23 23:16:46 +0000858 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000859 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000860 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000861 return nullptr;
862
Sanjay Patel980b2802016-01-26 16:17:24 +0000863 // The memset must cover the same number of bytes that are malloc'd.
864 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
865 return nullptr;
866
867 // Replace the malloc with a calloc. We need the data layout to know what the
868 // actual size of a 'size_t' parameter is.
869 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
870 const DataLayout &DL = Malloc->getModule()->getDataLayout();
871 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
872 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
873 Malloc->getArgOperand(0), Malloc->getAttributes(),
874 B, TLI);
875 if (!Calloc)
876 return nullptr;
877
878 Malloc->replaceAllUsesWith(Calloc);
879 Malloc->eraseFromParent();
880
881 return Calloc;
882}
883
Chris Bienemanad070d02014-09-17 20:55:46 +0000884Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000885 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
886 return Calloc;
887
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000888 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000889 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
890 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
891 return CI->getArgOperand(0);
892}
Meador Inged4825782012-11-11 06:49:03 +0000893
Meador Inge193e0352012-11-13 04:16:17 +0000894//===----------------------------------------------------------------------===//
895// Math Library Optimizations
896//===----------------------------------------------------------------------===//
897
Matthias Braund34e4d22014-12-03 21:46:33 +0000898/// Return a variant of Val with float type.
899/// Currently this works in two cases: If Val is an FPExtension of a float
900/// value to something bigger, simply return the operand.
901/// If Val is a ConstantFP but can be converted to a float ConstantFP without
902/// loss of precision do so.
903static Value *valueHasFloatPrecision(Value *Val) {
904 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
905 Value *Op = Cast->getOperand(0);
906 if (Op->getType()->isFloatTy())
907 return Op;
908 }
909 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
910 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000911 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000912 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000913 &losesInfo);
914 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000915 return ConstantFP::get(Const->getContext(), F);
916 }
917 return nullptr;
918}
919
Sanjay Patel4e971da2016-01-21 18:01:57 +0000920/// Shrink double -> float for unary functions like 'floor'.
921static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
922 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000923 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000924 // We know this libcall has a valid prototype, but we don't know which.
925 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000926 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000927
Chris Bienemanad070d02014-09-17 20:55:46 +0000928 if (CheckRetType) {
929 // Check if all the uses for function like 'sin' are converted to float.
930 for (User *U : CI->users()) {
931 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
932 if (!Cast || !Cast->getType()->isFloatTy())
933 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000934 }
Meador Inge193e0352012-11-13 04:16:17 +0000935 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000936
937 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000938 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
939 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000940 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000941
Andrew Ng1606fc02017-04-25 12:36:14 +0000942 // If call isn't an intrinsic, check that it isn't within a function with the
943 // same name as the float version of this call.
944 //
945 // e.g. inline float expf(float val) { return (float) exp((double) val); }
946 //
947 // A similar such definition exists in the MinGW-w64 math.h header file which
948 // when compiled with -O2 -ffast-math causes the generation of infinite loops
949 // where expf is called.
950 if (!Callee->isIntrinsic()) {
951 const Function *F = CI->getFunction();
952 StringRef FName = F->getName();
953 StringRef CalleeName = Callee->getName();
954 if ((FName.size() == (CalleeName.size() + 1)) &&
955 (FName.back() == 'f') &&
956 FName.startswith(CalleeName))
957 return nullptr;
958 }
959
Sanjay Patelaa231142015-12-31 21:52:31 +0000960 // Propagate fast-math flags from the existing call to the new call.
961 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000962 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000963
964 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000965 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000966 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000967 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000968 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
969 V = B.CreateCall(F, V);
970 } else {
971 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000972 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000973 }
974
Chris Bienemanad070d02014-09-17 20:55:46 +0000975 return B.CreateFPExt(V, B.getDoubleTy());
976}
Meador Inge193e0352012-11-13 04:16:17 +0000977
Matt Arsenault954a6242017-01-23 23:55:08 +0000978// Replace a libcall \p CI with a call to intrinsic \p IID
979static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
980 // Propagate fast-math flags from the existing call to the new call.
981 IRBuilder<>::FastMathFlagGuard Guard(B);
982 B.setFastMathFlags(CI->getFastMathFlags());
983
984 Module *M = CI->getModule();
985 Value *V = CI->getArgOperand(0);
986 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
987 CallInst *NewCall = B.CreateCall(F, V);
988 NewCall->takeName(CI);
989 return NewCall;
990}
991
Sanjay Patel4e971da2016-01-21 18:01:57 +0000992/// Shrink double -> float for binary functions like 'fmin/fmax'.
993static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000994 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000995 // We know this libcall has a valid prototype, but we don't know which.
996 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000997 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000998
Chris Bienemanad070d02014-09-17 20:55:46 +0000999 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001000 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1001 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1002 if (V1 == nullptr)
1003 return nullptr;
1004 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1005 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001006 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001007
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001008 // Propagate fast-math flags from the existing call to the new call.
1009 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001010 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001011
Chris Bienemanad070d02014-09-17 20:55:46 +00001012 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001013 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001014 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001015 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001016 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001017 return B.CreateFPExt(V, B.getDoubleTy());
1018}
1019
Hal Finkel2ff24732017-12-16 01:26:25 +00001020// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1021Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1022 if (!CI->isFast())
1023 return nullptr;
1024
1025 // Propagate fast-math flags from the existing call to new instructions.
1026 IRBuilder<>::FastMathFlagGuard Guard(B);
1027 B.setFastMathFlags(CI->getFastMathFlags());
1028
1029 Value *Real, *Imag;
1030 if (CI->getNumArgOperands() == 1) {
1031 Value *Op = CI->getArgOperand(0);
1032 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1033 Real = B.CreateExtractValue(Op, 0, "real");
1034 Imag = B.CreateExtractValue(Op, 1, "imag");
1035 } else {
1036 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1037 Real = CI->getArgOperand(0);
1038 Imag = CI->getArgOperand(1);
1039 }
1040
1041 Value *RealReal = B.CreateFMul(Real, Real);
1042 Value *ImagImag = B.CreateFMul(Imag, Imag);
1043
1044 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1045 CI->getType());
1046 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1047}
1048
Chris Bienemanad070d02014-09-17 20:55:46 +00001049Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1050 Function *Callee = CI->getCalledFunction();
1051 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001052 StringRef Name = Callee->getName();
1053 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001054 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001055
Chris Bienemanad070d02014-09-17 20:55:46 +00001056 // cos(-x) -> cos(x)
1057 Value *Op1 = CI->getArgOperand(0);
1058 if (BinaryOperator::isFNeg(Op1)) {
1059 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1060 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1061 }
1062 return Ret;
1063}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001064
Weiming Zhao82130722015-12-04 22:00:47 +00001065static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1066 // Multiplications calculated using Addition Chains.
1067 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1068
1069 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1070
1071 if (InnerChain[Exp])
1072 return InnerChain[Exp];
1073
1074 static const unsigned AddChain[33][2] = {
1075 {0, 0}, // Unused.
1076 {0, 0}, // Unused (base case = pow1).
1077 {1, 1}, // Unused (pre-computed).
1078 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1079 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1080 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1081 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1082 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1083 };
1084
1085 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1086 getPow(InnerChain, AddChain[Exp][1], B));
1087 return InnerChain[Exp];
1088}
1089
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001090/// Use square root in place of pow(x, +/-0.5).
1091Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1092 // TODO: There is some subset of 'fast' under which these transforms should
1093 // be allowed.
1094 if (!Pow->isFast())
1095 return nullptr;
1096
Sanjay Patel9771a962017-11-19 16:42:27 +00001097 const APFloat *Arg1C;
1098 if (!match(Pow->getArgOperand(1), m_APFloat(Arg1C)))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001099 return nullptr;
Sanjay Patel9771a962017-11-19 16:42:27 +00001100 if (!Arg1C->isExactlyValue(0.5) && !Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001101 return nullptr;
1102
1103 // Fast-math flags from the pow() are propagated to all replacement ops.
1104 IRBuilder<>::FastMathFlagGuard Guard(B);
1105 B.setFastMathFlags(Pow->getFastMathFlags());
1106 Type *Ty = Pow->getType();
1107 Value *Sqrt;
1108 if (Pow->hasFnAttr(Attribute::ReadNone)) {
1109 // We know that errno is never set, so replace with an intrinsic:
1110 // pow(x, 0.5) --> llvm.sqrt(x)
1111 // llvm.pow(x, 0.5) --> llvm.sqrt(x)
1112 auto *F = Intrinsic::getDeclaration(Pow->getModule(), Intrinsic::sqrt, Ty);
1113 Sqrt = B.CreateCall(F, Pow->getArgOperand(0));
1114 } else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf,
1115 LibFunc_sqrtl)) {
1116 // Errno could be set, so we must use a sqrt libcall.
1117 // TODO: We also should check that the target can in fact lower the sqrt
1118 // libcall. We currently have no way to ask this question, so we ask
1119 // whether the target has a sqrt libcall which is not exactly the same.
1120 Sqrt = emitUnaryFloatFnCall(Pow->getArgOperand(0),
1121 TLI->getName(LibFunc_sqrt), B,
1122 Pow->getCalledFunction()->getAttributes());
1123 } else {
1124 // We can't replace with an intrinsic or a libcall.
1125 return nullptr;
1126 }
1127
1128 // If this is pow(x, -0.5), get the reciprocal.
Sanjay Patel9771a962017-11-19 16:42:27 +00001129 if (Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001130 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt);
1131
1132 return Sqrt;
1133}
1134
Chris Bienemanad070d02014-09-17 20:55:46 +00001135Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1136 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001137 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001138 StringRef Name = Callee->getName();
1139 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001140 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001141
Chris Bienemanad070d02014-09-17 20:55:46 +00001142 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001143
1144 // pow(1.0, x) -> 1.0
1145 if (match(Op1, m_SpecificFP(1.0)))
1146 return Op1;
1147 // pow(2.0, x) -> llvm.exp2(x)
1148 if (match(Op1, m_SpecificFP(2.0))) {
1149 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1150 CI->getType());
1151 return B.CreateCall(Exp2, Op2, "exp2");
1152 }
1153
1154 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1155 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001156 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001157 // pow(10.0, x) -> exp10(x)
1158 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001159 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1160 LibFunc_exp10l))
1161 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001162 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001163 }
1164
Sanjay Patel6002e782016-01-12 17:30:37 +00001165 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001166 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001167 // We enable these only with fast-math. Besides rounding differences, the
1168 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001169 // Example: x = 1000, y = 0.001.
1170 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001171 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patel629c4112017-11-06 16:27:15 +00001172 if (OpC && OpC->isFast() && CI->isFast()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001173 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001174 Function *OpCCallee = OpC->getCalledFunction();
1175 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001176 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001177 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001178 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001179 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001180 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001181 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001182 }
1183 }
1184
Sanjay Patel9771a962017-11-19 16:42:27 +00001185 if (Value *Sqrt = replacePowWithSqrt(CI, B))
1186 return Sqrt;
1187
Chris Bienemanad070d02014-09-17 20:55:46 +00001188 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1189 if (!Op2C)
1190 return Ret;
1191
1192 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1193 return ConstantFP::get(CI->getType(), 1.0);
1194
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001195 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
Chris Bienemanad070d02014-09-17 20:55:46 +00001196 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001197 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1198 LibFunc_sqrtl)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001199 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1200 // This is faster than calling pow, and still handles negative zero
1201 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001202 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1203 Value *Inf = ConstantFP::getInfinity(CI->getType());
1204 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001205
1206 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1207 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001208 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001209
1210 Module *M = Callee->getParent();
1211 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1212 CI->getType());
1213 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1214
Chris Bienemanad070d02014-09-17 20:55:46 +00001215 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1216 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1217 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001218 }
1219
Sanjay Patelb23e1482017-12-10 17:25:54 +00001220 // Propagate fast-math-flags from the call to any created instructions.
1221 IRBuilder<>::FastMathFlagGuard Guard(B);
1222 B.setFastMathFlags(CI->getFastMathFlags());
1223 // pow(x, 1.0) --> x
1224 if (Op2C->isExactlyValue(1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001225 return Op1;
Sanjay Patelb23e1482017-12-10 17:25:54 +00001226 // pow(x, 2.0) --> x * x
1227 if (Op2C->isExactlyValue(2.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001228 return B.CreateFMul(Op1, Op1, "pow2");
Sanjay Patelb23e1482017-12-10 17:25:54 +00001229 // pow(x, -1.0) --> 1.0 / x
1230 if (Op2C->isExactlyValue(-1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001231 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001232
1233 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel629c4112017-11-06 16:27:15 +00001234 if (CI->isFast()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001235 APFloat V = abs(Op2C->getValueAPF());
1236 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1237 // This transformation applies to integer exponents only.
1238 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1239 !V.isInteger())
1240 return nullptr;
1241
1242 // We will memoize intermediate products of the Addition Chain.
1243 Value *InnerChain[33] = {nullptr};
1244 InnerChain[1] = Op1;
1245 InnerChain[2] = B.CreateFMul(Op1, Op1);
1246
1247 // We cannot readily convert a non-double type (like float) to a double.
1248 // So we first convert V to something which could be converted to double.
Sanjay Patelb23e1482017-12-10 17:25:54 +00001249 bool Ignored;
1250 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001251
Weiming Zhao82130722015-12-04 22:00:47 +00001252 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1253 // For negative exponents simply compute the reciprocal.
1254 if (Op2C->isNegative())
1255 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1256 return FMul;
1257 }
1258
Chris Bienemanad070d02014-09-17 20:55:46 +00001259 return nullptr;
1260}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001261
Chris Bienemanad070d02014-09-17 20:55:46 +00001262Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1263 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001264 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001265 StringRef Name = Callee->getName();
1266 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001267 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001268
Chris Bienemanad070d02014-09-17 20:55:46 +00001269 Value *Op = CI->getArgOperand(0);
1270 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1271 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001272 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001273 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001274 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001275 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001276 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001277
1278 if (TLI->has(LdExp)) {
1279 Value *LdExpArg = nullptr;
1280 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1281 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1282 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1283 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1284 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1285 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1286 }
1287
1288 if (LdExpArg) {
1289 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1290 if (!Op->getType()->isFloatTy())
1291 One = ConstantExpr::getFPExtend(One, Op->getType());
1292
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001293 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001294 Value *NewCallee =
1295 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001296 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001297 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001298 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1299 CI->setCallingConv(F->getCallingConv());
1300
1301 return CI;
1302 }
1303 }
1304 return Ret;
1305}
1306
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001307Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001308 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001309 // If we can shrink the call to a float function rather than a double
1310 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001311 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001312 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1313 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001314 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001315
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001316 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001317 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001318 if (CI->isFast()) {
1319 // If the call is 'fast', then anything we create here will also be 'fast'.
1320 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001321 } else {
1322 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001323 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001324 return nullptr;
1325 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1326 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001327 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001328 // might be impractical."
1329 FMF.setNoSignedZeros();
1330 FMF.setNoNaNs();
1331 }
Sanjay Patela2528152016-01-12 18:03:37 +00001332 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001333
1334 // We have a relaxed floating-point environment. We can ignore NaN-handling
1335 // and transform to a compare and select. We do not have to consider errno or
1336 // exceptions, because fmin/fmax do not have those.
1337 Value *Op0 = CI->getArgOperand(0);
1338 Value *Op1 = CI->getArgOperand(1);
1339 Value *Cmp = Callee->getName().startswith("fmin") ?
1340 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1341 return B.CreateSelect(Cmp, Op0, Op1);
1342}
1343
Davide Italianob8b71332015-11-29 20:58:04 +00001344Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1345 Function *Callee = CI->getCalledFunction();
1346 Value *Ret = nullptr;
1347 StringRef Name = Callee->getName();
1348 if (UnsafeFPShrink && hasFloatVersion(Name))
1349 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001350
Sanjay Patel629c4112017-11-06 16:27:15 +00001351 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001352 return Ret;
1353 Value *Op1 = CI->getArgOperand(0);
1354 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001355
Sanjay Patel629c4112017-11-06 16:27:15 +00001356 // The earlier call must also be 'fast' in order to do these transforms.
1357 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001358 return Ret;
1359
1360 // log(pow(x,y)) -> y*log(x)
1361 // This is only applicable to log, log2, log10.
1362 if (Name != "log" && Name != "log2" && Name != "log10")
1363 return Ret;
1364
1365 IRBuilder<>::FastMathFlagGuard Guard(B);
1366 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001367 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001368 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001369
David L. Jonesd21529f2017-01-23 23:16:46 +00001370 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001371 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001372 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001373 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001374 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001375 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001376 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001377
1378 // log(exp2(y)) -> y*log(2)
1379 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001380 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001381 return B.CreateFMul(
1382 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001383 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001384 Callee->getName(), B, Callee->getAttributes()),
1385 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001386 return Ret;
1387}
1388
Sanjay Patelc699a612014-10-16 18:48:17 +00001389Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1390 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001391 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001392 // TODO: Once we have a way (other than checking for the existince of the
1393 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1394 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001395 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001396 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001397 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001398
Sanjay Patel629c4112017-11-06 16:27:15 +00001399 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001400 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001401
Sanjay Patelc2d64612016-01-06 20:52:21 +00001402 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001403 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001404 return Ret;
1405
1406 // We're looking for a repeated factor in a multiplication tree,
1407 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001408 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001409 Value *Op0 = I->getOperand(0);
1410 Value *Op1 = I->getOperand(1);
1411 Value *RepeatOp = nullptr;
1412 Value *OtherOp = nullptr;
1413 if (Op0 == Op1) {
1414 // Simple match: the operands of the multiply are identical.
1415 RepeatOp = Op0;
1416 } else {
1417 // Look for a more complicated pattern: one of the operands is itself
1418 // a multiply, so search for a common factor in that multiply.
1419 // Note: We don't bother looking any deeper than this first level or for
1420 // variations of this pattern because instcombine's visitFMUL and/or the
1421 // reassociation pass should give us this form.
1422 Value *OtherMul0, *OtherMul1;
1423 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1424 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001425 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001426 // Matched: sqrt((x * x) * z)
1427 RepeatOp = OtherMul0;
1428 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001429 }
1430 }
1431 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001432 if (!RepeatOp)
1433 return Ret;
1434
1435 // Fast math flags for any created instructions should match the sqrt
1436 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001437 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001438 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001439
Sanjay Patelc2d64612016-01-06 20:52:21 +00001440 // If we found a repeated factor, hoist it out of the square root and
1441 // replace it with the fabs of that factor.
1442 Module *M = Callee->getParent();
1443 Type *ArgType = I->getType();
1444 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1445 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1446 if (OtherOp) {
1447 // If we found a non-repeated factor, we still need to get its square
1448 // root. We then multiply that by the value that was simplified out
1449 // of the square root calculation.
1450 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1451 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1452 return B.CreateFMul(FabsCall, SqrtCall);
1453 }
1454 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001455}
1456
Sanjay Patelcddcd722016-01-06 19:23:35 +00001457// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001458Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1459 Function *Callee = CI->getCalledFunction();
1460 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001461 StringRef Name = Callee->getName();
1462 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001463 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001464
Davide Italiano51507d22015-11-04 23:36:56 +00001465 Value *Op1 = CI->getArgOperand(0);
1466 auto *OpC = dyn_cast<CallInst>(Op1);
1467 if (!OpC)
1468 return Ret;
1469
Sanjay Patel629c4112017-11-06 16:27:15 +00001470 // Both calls must be 'fast' in order to remove them.
1471 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001472 return Ret;
1473
Davide Italiano51507d22015-11-04 23:36:56 +00001474 // tan(atan(x)) -> x
1475 // tanf(atanf(x)) -> x
1476 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001477 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001478 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001479 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001480 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1481 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1482 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001483 Ret = OpC->getArgOperand(0);
1484 return Ret;
1485}
1486
Sanjay Patel57747212016-01-21 23:38:43 +00001487static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001488 // We can only hope to do anything useful if we can ignore things like errno
1489 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001490 // We already checked the prototype.
1491 return CI->hasFnAttr(Attribute::NoUnwind) &&
1492 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001493}
1494
Chris Bienemanad070d02014-09-17 20:55:46 +00001495static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1496 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001497 Value *&SinCos) {
1498 Type *ArgTy = Arg->getType();
1499 Type *ResTy;
1500 StringRef Name;
1501
1502 Triple T(OrigCallee->getParent()->getTargetTriple());
1503 if (UseFloat) {
1504 Name = "__sincospif_stret";
1505
1506 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1507 // x86_64 can't use {float, float} since that would be returned in both
1508 // xmm0 and xmm1, which isn't what a real struct would do.
1509 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001510 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1511 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001512 } else {
1513 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001514 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001515 }
1516
1517 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001518 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001519 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001520
1521 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1522 // If the argument is an instruction, it must dominate all uses so put our
1523 // sincos call there.
1524 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1525 } else {
1526 // Otherwise (e.g. for a constant) the beginning of the function is as
1527 // good a place as any.
1528 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1529 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1530 }
1531
1532 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1533
1534 if (SinCos->getType()->isStructTy()) {
1535 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1536 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1537 } else {
1538 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1539 "sinpi");
1540 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1541 "cospi");
1542 }
1543}
Chris Bienemanad070d02014-09-17 20:55:46 +00001544
1545Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001546 // Make sure the prototype is as expected, otherwise the rest of the
1547 // function is probably invalid and likely to abort.
1548 if (!isTrigLibCall(CI))
1549 return nullptr;
1550
1551 Value *Arg = CI->getArgOperand(0);
1552 SmallVector<CallInst *, 1> SinCalls;
1553 SmallVector<CallInst *, 1> CosCalls;
1554 SmallVector<CallInst *, 1> SinCosCalls;
1555
1556 bool IsFloat = Arg->getType()->isFloatTy();
1557
1558 // Look for all compatible sinpi, cospi and sincospi calls with the same
1559 // argument. If there are enough (in some sense) we can make the
1560 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001561 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001562 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001563 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001564
1565 // It's only worthwhile if both sinpi and cospi are actually used.
1566 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1567 return nullptr;
1568
1569 Value *Sin, *Cos, *SinCos;
1570 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1571
Davide Italianof024a562016-12-16 02:28:38 +00001572 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1573 Value *Res) {
1574 for (CallInst *C : Calls)
1575 replaceAllUsesWith(C, Res);
1576 };
1577
Chris Bienemanad070d02014-09-17 20:55:46 +00001578 replaceTrigInsts(SinCalls, Sin);
1579 replaceTrigInsts(CosCalls, Cos);
1580 replaceTrigInsts(SinCosCalls, SinCos);
1581
1582 return nullptr;
1583}
1584
David Majnemerabae6b52016-03-19 04:53:02 +00001585void LibCallSimplifier::classifyArgUse(
1586 Value *Val, Function *F, bool IsFloat,
1587 SmallVectorImpl<CallInst *> &SinCalls,
1588 SmallVectorImpl<CallInst *> &CosCalls,
1589 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001590 CallInst *CI = dyn_cast<CallInst>(Val);
1591
1592 if (!CI)
1593 return;
1594
David Majnemerabae6b52016-03-19 04:53:02 +00001595 // Don't consider calls in other functions.
1596 if (CI->getFunction() != F)
1597 return;
1598
Chris Bienemanad070d02014-09-17 20:55:46 +00001599 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001600 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001601 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001602 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001603 return;
1604
1605 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001606 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001607 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001608 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001609 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001610 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001611 SinCosCalls.push_back(CI);
1612 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001613 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001614 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001615 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001616 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001617 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 SinCosCalls.push_back(CI);
1619 }
1620}
1621
Meador Inge7415f842012-11-25 20:45:27 +00001622//===----------------------------------------------------------------------===//
1623// Integer Library Call Optimizations
1624//===----------------------------------------------------------------------===//
1625
Chris Bienemanad070d02014-09-17 20:55:46 +00001626Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001627 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001628 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001629 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001630 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1631 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001632 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1634 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1637 return B.CreateSelect(Cond, V, B.getInt32(0));
1638}
Meador Ingea0b6d872012-11-26 00:24:07 +00001639
Davide Italiano85ad36b2016-12-15 23:45:11 +00001640Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1641 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1642 Value *Op = CI->getArgOperand(0);
1643 Type *ArgType = Op->getType();
1644 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1645 Intrinsic::ctlz, ArgType);
1646 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1647 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1648 V);
1649 return B.CreateIntCast(V, CI->getType(), false);
1650}
1651
Chris Bienemanad070d02014-09-17 20:55:46 +00001652Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001653 // abs(x) -> x >s -1 ? x : -x
1654 Value *Op = CI->getArgOperand(0);
1655 Value *Pos =
1656 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1657 Value *Neg = B.CreateNeg(Op, "neg");
1658 return B.CreateSelect(Pos, Op, Neg);
1659}
Meador Inge9a59ab62012-11-26 02:31:59 +00001660
Chris Bienemanad070d02014-09-17 20:55:46 +00001661Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001662 // isdigit(c) -> (c-'0') <u 10
1663 Value *Op = CI->getArgOperand(0);
1664 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1665 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1666 return B.CreateZExt(Op, CI->getType());
1667}
Meador Ingea62a39e2012-11-26 03:10:07 +00001668
Chris Bienemanad070d02014-09-17 20:55:46 +00001669Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001670 // isascii(c) -> c <u 128
1671 Value *Op = CI->getArgOperand(0);
1672 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1673 return B.CreateZExt(Op, CI->getType());
1674}
1675
1676Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001677 // toascii(c) -> c & 0x7f
1678 return B.CreateAnd(CI->getArgOperand(0),
1679 ConstantInt::get(CI->getType(), 0x7F));
1680}
Meador Inge604937d2012-11-26 03:38:52 +00001681
Meador Inge08ca1152012-11-26 20:37:20 +00001682//===----------------------------------------------------------------------===//
1683// Formatting and IO Library Call Optimizations
1684//===----------------------------------------------------------------------===//
1685
Chris Bienemanad070d02014-09-17 20:55:46 +00001686static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001687
Chris Bienemanad070d02014-09-17 20:55:46 +00001688Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1689 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001690 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001691 // Error reporting calls should be cold, mark them as such.
1692 // This applies even to non-builtin calls: it is only a hint and applies to
1693 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001694
Chris Bienemanad070d02014-09-17 20:55:46 +00001695 // This heuristic was suggested in:
1696 // Improving Static Branch Prediction in a Compiler
1697 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1698 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001699 if (!CI->hasFnAttr(Attribute::Cold) &&
1700 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001701 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001703
Chris Bienemanad070d02014-09-17 20:55:46 +00001704 return nullptr;
1705}
1706
1707static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001708 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 return false;
1710
1711 if (StreamArg < 0)
1712 return true;
1713
1714 // These functions might be considered cold, but only if their stream
1715 // argument is stderr.
1716
1717 if (StreamArg >= (int)CI->getNumArgOperands())
1718 return false;
1719 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1720 if (!LI)
1721 return false;
1722 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1723 if (!GV || !GV->isDeclaration())
1724 return false;
1725 return GV->getName() == "stderr";
1726}
1727
1728Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1729 // Check for a fixed format string.
1730 StringRef FormatStr;
1731 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001732 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001733
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 // Empty format string -> noop.
1735 if (FormatStr.empty()) // Tolerate printf's declared void.
1736 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001737
Chris Bienemanad070d02014-09-17 20:55:46 +00001738 // Do not do any of the following transformations if the printf return value
1739 // is used, in general the printf return value is not compatible with either
1740 // putchar() or puts().
1741 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001742 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001743
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001744 // printf("x") -> putchar('x'), even for "%" and "%%".
1745 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001746 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001747
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001748 // printf("%s", "a") --> putchar('a')
1749 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1750 StringRef ChrStr;
1751 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1752 return nullptr;
1753 if (ChrStr.size() != 1)
1754 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001755 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001756 }
1757
Chris Bienemanad070d02014-09-17 20:55:46 +00001758 // printf("foo\n") --> puts("foo")
1759 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1760 FormatStr.find('%') == StringRef::npos) { // No format characters.
1761 // Create a string literal with no \n on it. We expect the constant merge
1762 // pass to be run after this pass, to merge duplicate strings.
1763 FormatStr = FormatStr.drop_back();
1764 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001765 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001766 }
Meador Inge08ca1152012-11-26 20:37:20 +00001767
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 // Optimize specific format strings.
1769 // printf("%c", chr) --> putchar(chr)
1770 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001771 CI->getArgOperand(1)->getType()->isIntegerTy())
1772 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001773
1774 // printf("%s\n", str) --> puts(str)
1775 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001776 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001777 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001778 return nullptr;
1779}
1780
1781Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1782
1783 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001784 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001785 if (Value *V = optimizePrintFString(CI, B)) {
1786 return V;
1787 }
1788
1789 // printf(format, ...) -> iprintf(format, ...) if no floating point
1790 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001791 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001792 Module *M = B.GetInsertBlock()->getParent()->getParent();
1793 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001794 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001795 CallInst *New = cast<CallInst>(CI->clone());
1796 New->setCalledFunction(IPrintFFn);
1797 B.Insert(New);
1798 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001799 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 return nullptr;
1801}
Meador Inge08ca1152012-11-26 20:37:20 +00001802
Chris Bienemanad070d02014-09-17 20:55:46 +00001803Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1804 // Check for a fixed format string.
1805 StringRef FormatStr;
1806 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001807 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001808
Chris Bienemanad070d02014-09-17 20:55:46 +00001809 // If we just have a format string (nothing else crazy) transform it.
1810 if (CI->getNumArgOperands() == 2) {
1811 // Make sure there's no % in the constant array. We could try to handle
1812 // %% -> % in the future if we cared.
1813 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1814 if (FormatStr[i] == '%')
1815 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001816
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001817 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1818 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001819 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001820 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001822 }
Meador Ingef8e72502012-11-29 15:45:43 +00001823
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 // The remaining optimizations require the format string to be "%s" or "%c"
1825 // and have an extra operand.
1826 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1827 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001828 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001829
Chris Bienemanad070d02014-09-17 20:55:46 +00001830 // Decode the second character of the format string.
1831 if (FormatStr[1] == 'c') {
1832 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1833 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1834 return nullptr;
1835 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001836 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001837 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001838 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001840
Chris Bienemanad070d02014-09-17 20:55:46 +00001841 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001842 }
1843
Chris Bienemanad070d02014-09-17 20:55:46 +00001844 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001845 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1846 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1847 return nullptr;
1848
Sanjay Pateld3112a52016-01-19 19:46:10 +00001849 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 if (!Len)
1851 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001852 Value *IncLen =
1853 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001854 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00001855
1856 // The sprintf result is the unincremented number of bytes in the string.
1857 return B.CreateIntCast(Len, CI->getType(), false);
1858 }
1859 return nullptr;
1860}
1861
1862Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1863 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001864 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001865 if (Value *V = optimizeSPrintFString(CI, B)) {
1866 return V;
1867 }
1868
1869 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1870 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001871 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001872 Module *M = B.GetInsertBlock()->getParent()->getParent();
1873 Constant *SIPrintFFn =
1874 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1875 CallInst *New = cast<CallInst>(CI->clone());
1876 New->setCalledFunction(SIPrintFFn);
1877 B.Insert(New);
1878 return New;
1879 }
1880 return nullptr;
1881}
1882
1883Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1884 optimizeErrorReporting(CI, B, 0);
1885
1886 // All the optimizations depend on the format string.
1887 StringRef FormatStr;
1888 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1889 return nullptr;
1890
1891 // Do not do any of the following transformations if the fprintf return
1892 // value is used, in general the fprintf return value is not compatible
1893 // with fwrite(), fputc() or fputs().
1894 if (!CI->use_empty())
1895 return nullptr;
1896
1897 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1898 if (CI->getNumArgOperands() == 2) {
1899 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1900 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1901 return nullptr; // We found a format specifier.
1902
Sanjay Pateld3112a52016-01-19 19:46:10 +00001903 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001904 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001905 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001906 CI->getArgOperand(0), B, DL, TLI);
1907 }
1908
1909 // The remaining optimizations require the format string to be "%s" or "%c"
1910 // and have an extra operand.
1911 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1912 CI->getNumArgOperands() < 3)
1913 return nullptr;
1914
1915 // Decode the second character of the format string.
1916 if (FormatStr[1] == 'c') {
1917 // fprintf(F, "%c", chr) --> fputc(chr, F)
1918 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1919 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001920 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001921 }
1922
1923 if (FormatStr[1] == 's') {
1924 // fprintf(F, "%s", str) --> fputs(str, F)
1925 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1926 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001927 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001928 }
1929 return nullptr;
1930}
1931
1932Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1933 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001934 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001935 if (Value *V = optimizeFPrintFString(CI, B)) {
1936 return V;
1937 }
1938
1939 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1940 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001941 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001942 Module *M = B.GetInsertBlock()->getParent()->getParent();
1943 Constant *FIPrintFFn =
1944 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1945 CallInst *New = cast<CallInst>(CI->clone());
1946 New->setCalledFunction(FIPrintFFn);
1947 B.Insert(New);
1948 return New;
1949 }
1950 return nullptr;
1951}
1952
1953Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1954 optimizeErrorReporting(CI, B, 3);
1955
Chris Bienemanad070d02014-09-17 20:55:46 +00001956 // Get the element size and count.
1957 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1958 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1959 if (!SizeC || !CountC)
1960 return nullptr;
1961 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1962
1963 // If this is writing zero records, remove the call (it's a noop).
1964 if (Bytes == 0)
1965 return ConstantInt::get(CI->getType(), 0);
1966
1967 // If this is writing one byte, turn it into fputc.
1968 // This optimisation is only valid, if the return value is unused.
1969 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001970 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1971 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001972 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1973 }
1974
1975 return nullptr;
1976}
1977
1978Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1979 optimizeErrorReporting(CI, B, 1);
1980
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001981 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1982 // requires more arguments and thus extra MOVs are required.
1983 if (CI->getParent()->getParent()->optForSize())
1984 return nullptr;
1985
Ahmed Bougachad765a822016-04-27 19:04:35 +00001986 // We can't optimize if return value is used.
1987 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001988 return nullptr;
1989
1990 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1991 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1992 if (!Len)
1993 return nullptr;
1994
1995 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001996 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001997 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001998 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001999 CI->getArgOperand(1), B, DL, TLI);
2000}
2001
2002Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002003 // Check for a constant string.
2004 StringRef Str;
2005 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2006 return nullptr;
2007
2008 if (Str.empty() && CI->use_empty()) {
2009 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002010 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002011 if (CI->use_empty() || !Res)
2012 return Res;
2013 return B.CreateIntCast(Res, CI->getType(), true);
2014 }
2015
2016 return nullptr;
2017}
2018
2019bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002020 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002021 SmallString<20> FloatFuncName = FuncName;
2022 FloatFuncName += 'f';
2023 if (TLI->getLibFunc(FloatFuncName, Func))
2024 return TLI->has(Func);
2025 return false;
2026}
Meador Inge7fb2f732012-10-13 16:45:32 +00002027
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002028Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2029 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002030 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002031 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002032 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002033 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002034 // Make sure we never change the calling convention.
2035 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002036 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002037 "Optimizing string/memory libcall would change the calling convention");
2038 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002039 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002040 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002041 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002042 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002043 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002044 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002045 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002046 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002047 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002048 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002049 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002050 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002051 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002052 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002053 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002054 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002055 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002056 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002057 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002058 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002059 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002060 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002061 case LibFunc_strtol:
2062 case LibFunc_strtod:
2063 case LibFunc_strtof:
2064 case LibFunc_strtoul:
2065 case LibFunc_strtoll:
2066 case LibFunc_strtold:
2067 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002068 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002069 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002070 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002071 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002072 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002073 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002074 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002075 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002076 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002077 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002078 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002079 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002080 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002081 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002082 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002083 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002084 return optimizeMemSet(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002085 case LibFunc_wcslen:
2086 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002087 default:
2088 break;
2089 }
2090 }
2091 return nullptr;
2092}
2093
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002094Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2095 LibFunc Func,
2096 IRBuilder<> &Builder) {
2097 // Don't optimize calls that require strict floating point semantics.
2098 if (CI->isStrictFP())
2099 return nullptr;
2100
2101 switch (Func) {
2102 case LibFunc_cosf:
2103 case LibFunc_cos:
2104 case LibFunc_cosl:
2105 return optimizeCos(CI, Builder);
2106 case LibFunc_sinpif:
2107 case LibFunc_sinpi:
2108 case LibFunc_cospif:
2109 case LibFunc_cospi:
2110 return optimizeSinCosPi(CI, Builder);
2111 case LibFunc_powf:
2112 case LibFunc_pow:
2113 case LibFunc_powl:
2114 return optimizePow(CI, Builder);
2115 case LibFunc_exp2l:
2116 case LibFunc_exp2:
2117 case LibFunc_exp2f:
2118 return optimizeExp2(CI, Builder);
2119 case LibFunc_fabsf:
2120 case LibFunc_fabs:
2121 case LibFunc_fabsl:
2122 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2123 case LibFunc_sqrtf:
2124 case LibFunc_sqrt:
2125 case LibFunc_sqrtl:
2126 return optimizeSqrt(CI, Builder);
2127 case LibFunc_log:
2128 case LibFunc_log10:
2129 case LibFunc_log1p:
2130 case LibFunc_log2:
2131 case LibFunc_logb:
2132 return optimizeLog(CI, Builder);
2133 case LibFunc_tan:
2134 case LibFunc_tanf:
2135 case LibFunc_tanl:
2136 return optimizeTan(CI, Builder);
2137 case LibFunc_ceil:
2138 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2139 case LibFunc_floor:
2140 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2141 case LibFunc_round:
2142 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2143 case LibFunc_nearbyint:
2144 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2145 case LibFunc_rint:
2146 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2147 case LibFunc_trunc:
2148 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2149 case LibFunc_acos:
2150 case LibFunc_acosh:
2151 case LibFunc_asin:
2152 case LibFunc_asinh:
2153 case LibFunc_atan:
2154 case LibFunc_atanh:
2155 case LibFunc_cbrt:
2156 case LibFunc_cosh:
2157 case LibFunc_exp:
2158 case LibFunc_exp10:
2159 case LibFunc_expm1:
2160 case LibFunc_sin:
2161 case LibFunc_sinh:
2162 case LibFunc_tanh:
2163 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2164 return optimizeUnaryDoubleFP(CI, Builder, true);
2165 return nullptr;
2166 case LibFunc_copysign:
2167 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2168 return optimizeBinaryDoubleFP(CI, Builder);
2169 return nullptr;
2170 case LibFunc_fminf:
2171 case LibFunc_fmin:
2172 case LibFunc_fminl:
2173 case LibFunc_fmaxf:
2174 case LibFunc_fmax:
2175 case LibFunc_fmaxl:
2176 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002177 case LibFunc_cabs:
2178 case LibFunc_cabsf:
2179 case LibFunc_cabsl:
2180 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002181 default:
2182 return nullptr;
2183 }
2184}
2185
Chris Bienemanad070d02014-09-17 20:55:46 +00002186Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002187 // TODO: Split out the code below that operates on FP calls so that
2188 // we can all non-FP calls with the StrictFP attribute to be
2189 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002190 if (CI->isNoBuiltin())
2191 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002192
David L. Jonesd21529f2017-01-23 23:16:46 +00002193 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002194 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002195
2196 SmallVector<OperandBundleDef, 2> OpBundles;
2197 CI->getOperandBundlesAsDefs(OpBundles);
2198 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002199 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002200
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002201 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002202 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002203 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002204 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2205 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002206 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002207 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002208
Sanjay Patel848309d2014-10-23 21:52:45 +00002209 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002210 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002211 if (!isCallingConvC)
2212 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002213 // The FP intrinsics have corresponding constrained versions so we don't
2214 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002215 switch (II->getIntrinsicID()) {
2216 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002217 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002218 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002219 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002220 case Intrinsic::log:
2221 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002222 case Intrinsic::sqrt:
2223 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002224 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002225 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002226 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002227 }
2228 }
2229
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002230 // Also try to simplify calls to fortified library functions.
2231 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2232 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002233 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002234 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2235 // Use an IR Builder from SimplifiedCI if available instead of CI
2236 // to guarantee we reach all uses we might replace later on.
2237 IRBuilder<> TmpBuilder(SimplifiedCI);
2238 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002239 // If we were able to further simplify, remove the now redundant call.
2240 SimplifiedCI->replaceAllUsesWith(V);
2241 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002242 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002243 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002244 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002245 return SimplifiedFortifiedCI;
2246 }
2247
Meador Inge20255ef2013-03-12 00:08:29 +00002248 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002249 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002250 // We never change the calling convention.
2251 if (!ignoreCallingConv(Func) && !isCallingConvC)
2252 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002253 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2254 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002255 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2256 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002257 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002258 case LibFunc_ffs:
2259 case LibFunc_ffsl:
2260 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002261 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002262 case LibFunc_fls:
2263 case LibFunc_flsl:
2264 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002265 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002266 case LibFunc_abs:
2267 case LibFunc_labs:
2268 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002269 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002270 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002271 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002272 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002273 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002274 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002275 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002276 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002277 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002278 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002279 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002280 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002281 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002282 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002283 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002284 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002285 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002286 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002287 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002288 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002289 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002290 case LibFunc_vfprintf:
2291 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002292 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002293 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002294 return optimizeErrorReporting(CI, Builder, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002295 default:
2296 return nullptr;
2297 }
Meador Inge20255ef2013-03-12 00:08:29 +00002298 }
Craig Topperf40110f2014-04-25 05:29:35 +00002299 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002300}
2301
Chandler Carruth92803822015-01-21 02:11:59 +00002302LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002303 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002304 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002305 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002306 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2307 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002308
2309void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2310 // Indirect through the replacer used in this instance.
2311 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002312}
2313
Meador Ingedfb08a22013-06-20 19:48:07 +00002314// TODO:
2315// Additional cases that we need to add to this file:
2316//
2317// cbrt:
2318// * cbrt(expN(X)) -> expN(x/3)
2319// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002320// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002321//
2322// exp, expf, expl:
2323// * exp(log(x)) -> x
2324//
2325// log, logf, logl:
2326// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002327// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002328// * log(exp10(y)) -> y*log(10)
2329// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002330//
Meador Ingedfb08a22013-06-20 19:48:07 +00002331// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002332// * pow(sqrt(x),y) -> pow(x,y*0.5)
2333// * pow(pow(x,y),z)-> pow(x,y*z)
2334//
Meador Ingedfb08a22013-06-20 19:48:07 +00002335// signbit:
2336// * signbit(cnst) -> cnst'
2337// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2338//
2339// sqrt, sqrtf, sqrtl:
2340// * sqrt(expN(x)) -> expN(x*0.5)
2341// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2342// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2343//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002344
2345//===----------------------------------------------------------------------===//
2346// Fortified Library Call Optimizations
2347//===----------------------------------------------------------------------===//
2348
2349bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2350 unsigned ObjSizeOp,
2351 unsigned SizeOp,
2352 bool isString) {
2353 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2354 return true;
2355 if (ConstantInt *ObjSizeCI =
2356 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002357 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002358 return true;
2359 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2360 if (OnlyLowerUnknownSize)
2361 return false;
2362 if (isString) {
2363 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2364 // If the length is 0 we don't know how long it is and so we can't
2365 // remove the check.
2366 if (Len == 0)
2367 return false;
2368 return ObjSizeCI->getZExtValue() >= Len;
2369 }
2370 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2371 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2372 }
2373 return false;
2374}
2375
Sanjay Pateld707db92015-12-31 16:10:49 +00002376Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2377 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002378 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002379 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2380 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002381 return CI->getArgOperand(0);
2382 }
2383 return nullptr;
2384}
2385
Sanjay Pateld707db92015-12-31 16:10:49 +00002386Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2387 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002388 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002389 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2390 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002391 return CI->getArgOperand(0);
2392 }
2393 return nullptr;
2394}
2395
Sanjay Pateld707db92015-12-31 16:10:49 +00002396Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2397 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002398 // TODO: Try foldMallocMemset() here.
2399
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2401 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2402 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2403 return CI->getArgOperand(0);
2404 }
2405 return nullptr;
2406}
2407
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002408Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2409 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002410 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002411 Function *Callee = CI->getCalledFunction();
2412 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002413 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2415 *ObjSize = CI->getArgOperand(2);
2416
2417 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002418 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002419 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002420 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002421 }
2422
2423 // If a) we don't have any length information, or b) we know this will
2424 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2425 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2426 // TODO: It might be nice to get a maximum length out of the possible
2427 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002428 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002429 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002430
David Blaikie65fab6d2015-04-03 21:32:06 +00002431 if (OnlyLowerUnknownSize)
2432 return nullptr;
2433
2434 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2435 uint64_t Len = GetStringLength(Src);
2436 if (Len == 0)
2437 return nullptr;
2438
2439 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2440 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002441 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002442 // If the function was an __stpcpy_chk, and we were able to fold it into
2443 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002444 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002445 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2446 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002447}
2448
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002449Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2450 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002451 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002452 Function *Callee = CI->getCalledFunction();
2453 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002454 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002455 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002456 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002457 return Ret;
2458 }
2459 return nullptr;
2460}
2461
2462Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002463 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2464 // Some clang users checked for _chk libcall availability using:
2465 // __has_builtin(__builtin___memcpy_chk)
2466 // When compiling with -fno-builtin, this is always true.
2467 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2468 // end up with fortified libcalls, which isn't acceptable in a freestanding
2469 // environment which only provides their non-fortified counterparts.
2470 //
2471 // Until we change clang and/or teach external users to check for availability
2472 // differently, disregard the "nobuiltin" attribute and TLI::has.
2473 //
2474 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002475
David L. Jonesd21529f2017-01-23 23:16:46 +00002476 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002477 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002478
2479 SmallVector<OperandBundleDef, 2> OpBundles;
2480 CI->getOperandBundlesAsDefs(OpBundles);
2481 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002482 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002483
Ahmed Bougachad765a822016-04-27 19:04:35 +00002484 // First, check that this is a known library functions and that the prototype
2485 // is correct.
2486 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002487 return nullptr;
2488
2489 // We never change the calling convention.
2490 if (!ignoreCallingConv(Func) && !isCallingConvC)
2491 return nullptr;
2492
2493 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002494 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002495 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002496 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002497 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002498 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002499 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002500 case LibFunc_stpcpy_chk:
2501 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002502 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002503 case LibFunc_stpncpy_chk:
2504 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002505 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002506 default:
2507 break;
2508 }
2509 return nullptr;
2510}
2511
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002512FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2513 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2514 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}