blob: a50575b025601c4ecbf8d14bea8a671b06344b3d [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Craig Topper2915bc02018-03-01 20:05:09 +000010// This file implements the library calls simplifier. It does not implement
11// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Evandro Menezes2123ea72018-08-30 19:04:51 +000016#include "llvm/ADT/APSInt.h"
Meador Inge20255ef2013-03-12 00:08:29 +000017#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000018#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000019#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000020#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000021#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000023#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000024#include "llvm/Analysis/ValueTracking.h"
David Bolvanskyca22d422018-05-16 11:39:52 +000025#include "llvm/Analysis/CaptureTracking.h"
David Bolvansky909889b2018-08-10 04:32:54 +000026#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000030#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000034#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000035#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000036#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000037#include "llvm/Transforms/Utils/BuildLibCalls.h"
38
39using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000040using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000041
Hal Finkel66cd3f12013-11-17 02:06:35 +000042static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000043 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
44 cl::init(false),
45 cl::desc("Enable unsafe double to float "
46 "shrinking for math lib calls"));
47
48
Meador Ingedf796f82012-10-13 16:45:24 +000049//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000050// Helper Functions
51//===----------------------------------------------------------------------===//
52
David L. Jonesd21529f2017-01-23 23:16:46 +000053static bool ignoreCallingConv(LibFunc Func) {
54 return Func == LibFunc_abs || Func == LibFunc_labs ||
55 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000056}
57
Sam Parker214f7bf2016-09-13 12:10:14 +000058static bool isCallingConvCCompatible(CallInst *CI) {
59 switch(CI->getCallingConv()) {
60 default:
61 return false;
62 case llvm::CallingConv::C:
63 return true;
64 case llvm::CallingConv::ARM_APCS:
65 case llvm::CallingConv::ARM_AAPCS:
66 case llvm::CallingConv::ARM_AAPCS_VFP: {
67
68 // The iOS ABI diverges from the standard in some cases, so for now don't
69 // try to simplify those calls.
70 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
71 return false;
72
73 auto *FuncTy = CI->getFunctionType();
74
75 if (!FuncTy->getReturnType()->isPointerTy() &&
76 !FuncTy->getReturnType()->isIntegerTy() &&
77 !FuncTy->getReturnType()->isVoidTy())
78 return false;
79
80 for (auto Param : FuncTy->params()) {
81 if (!Param->isPointerTy() && !Param->isIntegerTy())
82 return false;
83 }
84 return true;
85 }
86 }
87 return false;
88}
89
Sanjay Pateld707db92015-12-31 16:10:49 +000090/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000091static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000092 for (User *U : V->users()) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000094 if (IC->isEquality() && IC->getOperand(1) == With)
95 continue;
96 // Unknown instruction.
97 return false;
98 }
99 return true;
100}
101
Meador Inge08ca1152012-11-26 20:37:20 +0000102static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000103 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000104 return OI->getType()->isFloatingPointTy();
105 });
Meador Inge08ca1152012-11-26 20:37:20 +0000106}
107
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000108static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
109 if (Base < 2 || Base > 36)
110 // handle special zero base
111 if (Base != 0)
112 return nullptr;
113
114 char *End;
115 std::string nptr = Str.str();
116 errno = 0;
117 long long int Result = strtoll(nptr.c_str(), &End, Base);
118 if (errno)
119 return nullptr;
120
121 // if we assume all possible target locales are ASCII supersets,
122 // then if strtoll successfully parses a number on the host,
123 // it will also successfully parse the same way on the target
124 if (*End != '\0')
125 return nullptr;
126
127 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
128 return nullptr;
129
130 return ConstantInt::get(CI->getType(), Result);
131}
132
David Bolvanskyca22d422018-05-16 11:39:52 +0000133static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
134 const TargetLibraryInfo *TLI) {
135 CallInst *FOpen = dyn_cast<CallInst>(File);
136 if (!FOpen)
137 return false;
138
139 Function *InnerCallee = FOpen->getCalledFunction();
140 if (!InnerCallee)
141 return false;
142
143 LibFunc Func;
144 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
145 Func != LibFunc_fopen)
146 return false;
147
David Bolvansky7c7760d2018-10-16 21:18:31 +0000148 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
David Bolvanskyca22d422018-05-16 11:39:52 +0000149 if (PointerMayBeCaptured(File, true, true))
150 return false;
151
152 return true;
153}
154
David Bolvansky909889b2018-08-10 04:32:54 +0000155static bool isOnlyUsedInComparisonWithZero(Value *V) {
156 for (User *U : V->users()) {
157 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
158 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
159 if (C->isNullValue())
160 continue;
161 // Unknown instruction.
162 return false;
163 }
164 return true;
165}
166
167static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
168 const DataLayout &DL) {
169 if (!isOnlyUsedInComparisonWithZero(CI))
170 return false;
171
172 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
173 return false;
Matt Morehousee62fc3d2018-09-19 19:37:24 +0000174
175 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
176 return false;
177
David Bolvansky909889b2018-08-10 04:32:54 +0000178 return true;
179}
180
Meador Inged589ac62012-10-31 03:33:06 +0000181//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000182// String and Memory Library Call Optimizations
183//===----------------------------------------------------------------------===//
184
Chris Bienemanad070d02014-09-17 20:55:46 +0000185Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000186 // Extract some information from the instruction
187 Value *Dst = CI->getArgOperand(0);
188 Value *Src = CI->getArgOperand(1);
189
190 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000191 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000192 if (Len == 0)
193 return nullptr;
194 --Len; // Unbias length.
195
196 // Handle the simple, do-nothing case: strcat(x, "") -> x
197 if (Len == 0)
198 return Dst;
199
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 return emitStrLenMemCpy(Src, Dst, Len, B);
201}
202
203Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
204 IRBuilder<> &B) {
205 // We need to find the end of the destination string. That's where the
206 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000207 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000208 if (!DstLen)
209 return nullptr;
210
211 // Now that we have the destination's length, we must index into the
212 // destination's pointer to get the actual memcpy destination (end of
213 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000214 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000215
216 // We have enough information to now generate the memcpy call to do the
217 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000218 B.CreateMemCpy(CpyDst, 1, Src, 1,
219 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000220 return Dst;
221}
222
223Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000224 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000225 Value *Dst = CI->getArgOperand(0);
226 Value *Src = CI->getArgOperand(1);
227 uint64_t Len;
228
Sanjay Pateld707db92015-12-31 16:10:49 +0000229 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000230 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
231 Len = LengthArg->getZExtValue();
232 else
233 return nullptr;
234
235 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000236 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000237 if (SrcLen == 0)
238 return nullptr;
239 --SrcLen; // Unbias length.
240
241 // Handle the simple, do-nothing cases:
242 // strncat(x, "", c) -> x
243 // strncat(x, c, 0) -> x
244 if (SrcLen == 0 || Len == 0)
245 return Dst;
246
Sanjay Pateld707db92015-12-31 16:10:49 +0000247 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000248 if (Len < SrcLen)
249 return nullptr;
250
251 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000252 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000253 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
254}
255
256Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
257 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000258 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000259 Value *SrcStr = CI->getArgOperand(0);
260
261 // If the second operand is non-constant, see if we can compute the length
262 // of the input string and turn this into memchr.
263 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
264 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000265 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000266 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
267 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000268
Sanjay Pateld3112a52016-01-19 19:46:10 +0000269 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000270 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
271 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000272 }
273
Chris Bienemanad070d02014-09-17 20:55:46 +0000274 // Otherwise, the character is a constant, see if the first argument is
275 // a string literal. If so, we can constant fold.
276 StringRef Str;
277 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000278 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000279 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000280 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000281 return nullptr;
282 }
283
284 // Compute the offset, make sure to handle the case when we're searching for
285 // zero (a weird way to spell strlen).
286 size_t I = (0xFF & CharC->getSExtValue()) == 0
287 ? Str.size()
288 : Str.find(CharC->getSExtValue());
289 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
290 return Constant::getNullValue(CI->getType());
291
292 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000293 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000294}
295
296Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000297 Value *SrcStr = CI->getArgOperand(0);
298 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
299
300 // Cannot fold anything if we're not looking for a constant.
301 if (!CharC)
302 return nullptr;
303
304 StringRef Str;
305 if (!getConstantStringInfo(SrcStr, Str)) {
306 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000307 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000308 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000309 return nullptr;
310 }
311
312 // Compute the offset.
313 size_t I = (0xFF & CharC->getSExtValue()) == 0
314 ? Str.size()
315 : Str.rfind(CharC->getSExtValue());
316 if (I == StringRef::npos) // Didn't find the char. Return null.
317 return Constant::getNullValue(CI->getType());
318
319 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000320 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000321}
322
323Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000324 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
325 if (Str1P == Str2P) // strcmp(x,x) -> 0
326 return ConstantInt::get(CI->getType(), 0);
327
328 StringRef Str1, Str2;
329 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
330 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
331
332 // strcmp(x, y) -> cnst (if both x and y are constant strings)
333 if (HasStr1 && HasStr2)
334 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
335
336 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
337 return B.CreateNeg(
338 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
339
340 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
341 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
342
343 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000344 uint64_t Len1 = GetStringLength(Str1P);
345 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000346 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000347 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000349 std::min(Len1, Len2)),
350 B, DL, TLI);
351 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000352
David Bolvansky909889b2018-08-10 04:32:54 +0000353 // strcmp to memcmp
354 if (!HasStr1 && HasStr2) {
355 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
356 return emitMemCmp(
357 Str1P, Str2P,
358 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
359 TLI);
360 } else if (HasStr1 && !HasStr2) {
361 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
362 return emitMemCmp(
363 Str1P, Str2P,
364 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
365 TLI);
366 }
367
Chris Bienemanad070d02014-09-17 20:55:46 +0000368 return nullptr;
369}
370
371Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000372 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
373 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
374 return ConstantInt::get(CI->getType(), 0);
375
376 // Get the length argument if it is constant.
377 uint64_t Length;
378 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
379 Length = LengthArg->getZExtValue();
380 else
381 return nullptr;
382
383 if (Length == 0) // strncmp(x,y,0) -> 0
384 return ConstantInt::get(CI->getType(), 0);
385
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000386 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000387 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000388
389 StringRef Str1, Str2;
390 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
391 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
392
393 // strncmp(x, y) -> cnst (if both x and y are constant strings)
394 if (HasStr1 && HasStr2) {
395 StringRef SubStr1 = Str1.substr(0, Length);
396 StringRef SubStr2 = Str2.substr(0, Length);
397 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
398 }
399
400 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
401 return B.CreateNeg(
402 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
403
404 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
405 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
406
David Bolvansky909889b2018-08-10 04:32:54 +0000407 uint64_t Len1 = GetStringLength(Str1P);
408 uint64_t Len2 = GetStringLength(Str2P);
409
410 // strncmp to memcmp
411 if (!HasStr1 && HasStr2) {
412 Len2 = std::min(Len2, Length);
413 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
414 return emitMemCmp(
415 Str1P, Str2P,
416 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
417 TLI);
418 } else if (HasStr1 && !HasStr2) {
419 Len1 = std::min(Len1, Length);
420 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
421 return emitMemCmp(
422 Str1P, Str2P,
423 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
424 TLI);
425 }
426
Chris Bienemanad070d02014-09-17 20:55:46 +0000427 return nullptr;
428}
429
430Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000431 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
432 if (Dst == Src) // strcpy(x,x) -> x
433 return Src;
434
Chris Bienemanad070d02014-09-17 20:55:46 +0000435 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000436 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000437 if (Len == 0)
438 return nullptr;
439
440 // We have enough information to now generate the memcpy call to do the
441 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000442 B.CreateMemCpy(Dst, 1, Src, 1,
443 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000444 return Dst;
445}
446
447Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
448 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000449 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
450 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000451 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000452 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000453 }
454
455 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000456 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000457 if (Len == 0)
458 return nullptr;
459
Davide Italianob7487e62015-11-02 23:07:14 +0000460 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000461 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000462 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
463 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000464
465 // We have enough information to now generate the memcpy call to do the
466 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000467 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000468 return DstEnd;
469}
470
471Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
472 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000473 Value *Dst = CI->getArgOperand(0);
474 Value *Src = CI->getArgOperand(1);
475 Value *LenOp = CI->getArgOperand(2);
476
477 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000478 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000479 if (SrcLen == 0)
480 return nullptr;
481 --SrcLen;
482
483 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000484 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000485 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000486 return Dst;
487 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000488
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 uint64_t Len;
490 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
491 Len = LengthArg->getZExtValue();
492 else
493 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000494
Chris Bienemanad070d02014-09-17 20:55:46 +0000495 if (Len == 0)
496 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000497
Chris Bienemanad070d02014-09-17 20:55:46 +0000498 // Let strncpy handle the zero padding
499 if (Len > SrcLen + 1)
500 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000501
Davide Italianob7487e62015-11-02 23:07:14 +0000502 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000503 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
504 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000505
Chris Bienemanad070d02014-09-17 20:55:46 +0000506 return Dst;
507}
Meador Inge7fb2f732012-10-13 16:45:32 +0000508
Matthias Braun50ec0b52017-05-19 22:37:09 +0000509Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
510 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000511 Value *Src = CI->getArgOperand(0);
512
513 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000514 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000515 return ConstantInt::get(CI->getType(), Len - 1);
516
David L Kreitzer752c1442016-04-13 14:31:06 +0000517 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000518 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000519 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000520 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000521 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000522 // subtraction. This will make the optimization more complex, and it's not
523 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000524 // very uncommon.
525 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000526 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000527 return nullptr;
528
Matthias Braun50ec0b52017-05-19 22:37:09 +0000529 ConstantDataArraySlice Slice;
530 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
531 uint64_t NullTermIdx;
532 if (Slice.Array == nullptr) {
533 NullTermIdx = 0;
534 } else {
535 NullTermIdx = ~((uint64_t)0);
536 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
537 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
538 NullTermIdx = I;
539 break;
540 }
541 }
542 // If the string does not have '\0', leave it to strlen to compute
543 // its length.
544 if (NullTermIdx == ~((uint64_t)0))
545 return nullptr;
546 }
547
David L Kreitzer752c1442016-04-13 14:31:06 +0000548 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000549 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000550 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000551 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000552 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
553
Matthias Braun50ec0b52017-05-19 22:37:09 +0000554 // KnownZero's bits are flipped, so zeros in KnownZero now represent
555 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000556 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000557 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000558 // unsigned-less-than NullTermIdx.
559 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000560 // If Offset is not provably in the range [0, NullTermIdx], we can still
561 // optimize if we can prove that the program has undefined behavior when
562 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000563 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000564 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000565 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000566 NullTermIdx == ArrSize - 1)) {
567 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
568 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000569 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000570 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000571 }
572
573 return nullptr;
574 }
575
Chris Bienemanad070d02014-09-17 20:55:46 +0000576 // strlen(x?"foo":"bars") --> x ? 3 : 4
577 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000578 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
579 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000580 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000581 ORE.emit([&]() {
582 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
583 << "folded strlen(select) to select of constants";
584 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000585 return B.CreateSelect(SI->getCondition(),
586 ConstantInt::get(CI->getType(), LenTrue - 1),
587 ConstantInt::get(CI->getType(), LenFalse - 1));
588 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000589 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000590
Chris Bienemanad070d02014-09-17 20:55:46 +0000591 // strlen(x) != 0 --> *x != 0
592 // strlen(x) == 0 --> *x == 0
593 if (isOnlyUsedInZeroEqualityComparison(CI))
594 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000595
Chris Bienemanad070d02014-09-17 20:55:46 +0000596 return nullptr;
597}
Meador Inge17418502012-10-13 16:45:37 +0000598
Matthias Braun50ec0b52017-05-19 22:37:09 +0000599Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
600 return optimizeStringLength(CI, B, 8);
601}
602
603Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000604 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000605 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000606 // We cannot perform this optimization without wchar_size metadata.
607 if (WCharSize == 0)
608 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000609
610 return optimizeStringLength(CI, B, WCharSize);
611}
612
Chris Bienemanad070d02014-09-17 20:55:46 +0000613Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000614 StringRef S1, S2;
615 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
616 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000617
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000618 // strpbrk(s, "") -> nullptr
619 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000620 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
621 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000622
Chris Bienemanad070d02014-09-17 20:55:46 +0000623 // Constant folding.
624 if (HasS1 && HasS2) {
625 size_t I = S1.find_first_of(S2);
626 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000627 return Constant::getNullValue(CI->getType());
628
Sanjay Pateld707db92015-12-31 16:10:49 +0000629 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
630 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000631 }
Meador Inge17418502012-10-13 16:45:37 +0000632
Chris Bienemanad070d02014-09-17 20:55:46 +0000633 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000634 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000635 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000636
637 return nullptr;
638}
639
640Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000641 Value *EndPtr = CI->getArgOperand(1);
642 if (isa<ConstantPointerNull>(EndPtr)) {
643 // With a null EndPtr, this function won't capture the main argument.
644 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000645 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000646 }
647
648 return nullptr;
649}
650
651Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000652 StringRef S1, S2;
653 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
654 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
655
656 // strspn(s, "") -> 0
657 // strspn("", s) -> 0
658 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
659 return Constant::getNullValue(CI->getType());
660
661 // Constant folding.
662 if (HasS1 && HasS2) {
663 size_t Pos = S1.find_first_not_of(S2);
664 if (Pos == StringRef::npos)
665 Pos = S1.size();
666 return ConstantInt::get(CI->getType(), Pos);
667 }
668
669 return nullptr;
670}
671
672Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000673 StringRef S1, S2;
674 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
675 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
676
677 // strcspn("", s) -> 0
678 if (HasS1 && S1.empty())
679 return Constant::getNullValue(CI->getType());
680
681 // Constant folding.
682 if (HasS1 && HasS2) {
683 size_t Pos = S1.find_first_of(S2);
684 if (Pos == StringRef::npos)
685 Pos = S1.size();
686 return ConstantInt::get(CI->getType(), Pos);
687 }
688
689 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000690 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000691 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000692
693 return nullptr;
694}
695
696Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000697 // fold strstr(x, x) -> x.
698 if (CI->getArgOperand(0) == CI->getArgOperand(1))
699 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
700
701 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000702 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000703 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000704 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000706 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000707 StrLen, B, DL, TLI);
708 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000709 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000710 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
711 ICmpInst *Old = cast<ICmpInst>(*UI++);
712 Value *Cmp =
713 B.CreateICmp(Old->getPredicate(), StrNCmp,
714 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
715 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000716 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000717 return CI;
718 }
Meador Inge17418502012-10-13 16:45:37 +0000719
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 // See if either input string is a constant string.
721 StringRef SearchStr, ToFindStr;
722 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
723 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
724
725 // fold strstr(x, "") -> x.
726 if (HasStr2 && ToFindStr.empty())
727 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
728
729 // If both strings are known, constant fold it.
730 if (HasStr1 && HasStr2) {
731 size_t Offset = SearchStr.find(ToFindStr);
732
733 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000734 return Constant::getNullValue(CI->getType());
735
Chris Bienemanad070d02014-09-17 20:55:46 +0000736 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000737 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000738 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
739 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000740 }
Meador Inge17418502012-10-13 16:45:37 +0000741
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 // fold strstr(x, "y") -> strchr(x, 'y').
743 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000744 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
746 }
747 return nullptr;
748}
Meador Inge40b6fac2012-10-15 03:47:37 +0000749
Benjamin Kramer691363e2015-03-21 15:36:21 +0000750Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000751 Value *SrcStr = CI->getArgOperand(0);
752 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
753 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
754
755 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000756 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000757 return Constant::getNullValue(CI->getType());
758
Benjamin Kramer7857d722015-03-21 21:09:33 +0000759 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000760 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000761 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000762 return nullptr;
763
764 // Truncate the string to LenC. If Str is smaller than LenC we will still only
765 // scan the string, as reading past the end of it is undefined and we can just
766 // return null if we don't find the char.
767 Str = Str.substr(0, LenC->getZExtValue());
768
Benjamin Kramer7857d722015-03-21 21:09:33 +0000769 // If the char is variable but the input str and length are not we can turn
770 // this memchr call into a simple bit field test. Of course this only works
771 // when the return value is only checked against null.
772 //
773 // It would be really nice to reuse switch lowering here but we can't change
774 // the CFG at this point.
775 //
776 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
777 // after bounds check.
778 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000779 unsigned char Max =
780 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
781 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000782
783 // Make sure the bit field we're about to create fits in a register on the
784 // target.
785 // FIXME: On a 64 bit architecture this prevents us from using the
786 // interesting range of alpha ascii chars. We could do better by emitting
787 // two bitfields or shifting the range by 64 if no lower chars are used.
788 if (!DL.fitsInLegalInteger(Max + 1))
789 return nullptr;
790
791 // For the bit field use a power-of-2 type with at least 8 bits to avoid
792 // creating unnecessary illegal types.
793 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
794
795 // Now build the bit field.
796 APInt Bitfield(Width, 0);
797 for (char C : Str)
798 Bitfield.setBit((unsigned char)C);
799 Value *BitfieldC = B.getInt(Bitfield);
800
801 // First check that the bit field access is within bounds.
802 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
803 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
804 "memchr.bounds");
805
806 // Create code that checks if the given bit is set in the field.
807 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
808 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
809
810 // Finally merge both checks and cast to pointer type. The inttoptr
811 // implicitly zexts the i1 to intptr type.
812 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
813 }
814
815 // Check if all arguments are constants. If so, we can constant fold.
816 if (!CharC)
817 return nullptr;
818
Benjamin Kramer691363e2015-03-21 15:36:21 +0000819 // Compute the offset.
820 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
821 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
822 return Constant::getNullValue(CI->getType());
823
824 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000825 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000826}
827
Chris Bienemanad070d02014-09-17 20:55:46 +0000828Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000829 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000830
Chris Bienemanad070d02014-09-17 20:55:46 +0000831 if (LHS == RHS) // memcmp(s,s,x) -> 0
832 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000833
Chris Bienemanad070d02014-09-17 20:55:46 +0000834 // Make sure we have a constant length.
835 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
836 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000837 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000838
Sanjay Patel70db4242017-06-09 14:22:03 +0000839 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000840 if (Len == 0) // memcmp(s1,s2,0) -> 0
841 return Constant::getNullValue(CI->getType());
842
843 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
844 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000845 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000846 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000847 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000848 CI->getType(), "rhsv");
849 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000850 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000851
Chad Rosierdc655322015-08-28 18:30:18 +0000852 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000853 // TODO: The case where both inputs are constants does not need to be limited
854 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000855 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000856 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
857 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
858
Sanjay Patel82ec8722017-08-21 19:13:14 +0000859 // First, see if we can fold either argument to a constant.
860 Value *LHSV = nullptr;
861 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
862 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
863 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
864 }
865 Value *RHSV = nullptr;
866 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
867 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
868 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
869 }
Chad Rosierdc655322015-08-28 18:30:18 +0000870
Sanjay Patel82ec8722017-08-21 19:13:14 +0000871 // Don't generate unaligned loads. If either source is constant data,
872 // alignment doesn't matter for that source because there is no load.
873 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
874 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
875 if (!LHSV) {
876 Type *LHSPtrTy =
877 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
878 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
879 }
880 if (!RHSV) {
881 Type *RHSPtrTy =
882 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
883 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
884 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000885 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000886 }
Chad Rosierdc655322015-08-28 18:30:18 +0000887 }
888
Sanjay Patel82ec8722017-08-21 19:13:14 +0000889 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
890 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000891 StringRef LHSStr, RHSStr;
892 if (getConstantStringInfo(LHS, LHSStr) &&
893 getConstantStringInfo(RHS, RHSStr)) {
894 // Make sure we're not reading out-of-bounds memory.
895 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000896 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000897 // Fold the memcmp and normalize the result. This way we get consistent
898 // results across multiple platforms.
899 uint64_t Ret = 0;
900 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
901 if (Cmp < 0)
902 Ret = -1;
903 else if (Cmp > 0)
904 Ret = 1;
905 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000906 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000907
Chris Bienemanad070d02014-09-17 20:55:46 +0000908 return nullptr;
909}
Meador Inge9a6a1902012-10-31 00:20:56 +0000910
Chris Bienemanad070d02014-09-17 20:55:46 +0000911Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000912 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
913 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
914 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000915 return CI->getArgOperand(0);
916}
Meador Inge05a625a2012-10-31 14:58:26 +0000917
Chris Bienemanad070d02014-09-17 20:55:46 +0000918Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000919 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
920 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
921 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000922 return CI->getArgOperand(0);
923}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000924
Sanjay Patel980b2802016-01-26 16:17:24 +0000925/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +0000926Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000927 // This has to be a memset of zeros (bzero).
928 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
929 if (!FillValue || FillValue->getZExtValue() != 0)
930 return nullptr;
931
932 // TODO: We should handle the case where the malloc has more than one use.
933 // This is necessary to optimize common patterns such as when the result of
934 // the malloc is checked against null or when a memset intrinsic is used in
935 // place of a memset library call.
936 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
937 if (!Malloc || !Malloc->hasOneUse())
938 return nullptr;
939
940 // Is the inner call really malloc()?
941 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000942 if (!InnerCallee)
943 return nullptr;
944
David L. Jonesd21529f2017-01-23 23:16:46 +0000945 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +0000946 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000947 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000948 return nullptr;
949
Sanjay Patel980b2802016-01-26 16:17:24 +0000950 // The memset must cover the same number of bytes that are malloc'd.
951 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
952 return nullptr;
953
954 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +0000955 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +0000956 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
957 const DataLayout &DL = Malloc->getModule()->getDataLayout();
958 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
959 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
960 Malloc->getArgOperand(0), Malloc->getAttributes(),
Amara Emerson54f60252018-10-11 14:51:11 +0000961 B, *TLI);
Sanjay Patel980b2802016-01-26 16:17:24 +0000962 if (!Calloc)
963 return nullptr;
964
965 Malloc->replaceAllUsesWith(Calloc);
Amara Emerson54f60252018-10-11 14:51:11 +0000966 eraseFromParent(Malloc);
Sanjay Patel980b2802016-01-26 16:17:24 +0000967
968 return Calloc;
969}
970
Chris Bienemanad070d02014-09-17 20:55:46 +0000971Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Amara Emerson54f60252018-10-11 14:51:11 +0000972 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +0000973 return Calloc;
974
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000975 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000976 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
977 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
978 return CI->getArgOperand(0);
979}
Meador Inged4825782012-11-11 06:49:03 +0000980
Sanjay Patelb2ab3f22018-04-18 14:21:31 +0000981Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
982 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
983 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
984
985 return nullptr;
986}
987
Meador Inge193e0352012-11-13 04:16:17 +0000988//===----------------------------------------------------------------------===//
989// Math Library Optimizations
990//===----------------------------------------------------------------------===//
991
Evandro Menezes5aa217a2018-08-03 17:50:16 +0000992// Replace a libcall \p CI with a call to intrinsic \p IID
993static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
994 // Propagate fast-math flags from the existing call to the new call.
995 IRBuilder<>::FastMathFlagGuard Guard(B);
996 B.setFastMathFlags(CI->getFastMathFlags());
997
998 Module *M = CI->getModule();
999 Value *V = CI->getArgOperand(0);
1000 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1001 CallInst *NewCall = B.CreateCall(F, V);
1002 NewCall->takeName(CI);
1003 return NewCall;
1004}
1005
Matthias Braund34e4d22014-12-03 21:46:33 +00001006/// Return a variant of Val with float type.
1007/// Currently this works in two cases: If Val is an FPExtension of a float
1008/// value to something bigger, simply return the operand.
1009/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1010/// loss of precision do so.
1011static Value *valueHasFloatPrecision(Value *Val) {
1012 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1013 Value *Op = Cast->getOperand(0);
1014 if (Op->getType()->isFloatTy())
1015 return Op;
1016 }
1017 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1018 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001019 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001020 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001021 &losesInfo);
1022 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001023 return ConstantFP::get(Const->getContext(), F);
1024 }
1025 return nullptr;
1026}
1027
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001028/// Shrink double -> float functions.
1029static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001030 bool isBinary, bool isPrecise = false) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001031 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00001032 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001033
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001034 // If not all the uses of the function are converted to float, then bail out.
1035 // This matters if the precision of the result is more important than the
1036 // precision of the arguments.
1037 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001038 for (User *U : CI->users()) {
1039 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1040 if (!Cast || !Cast->getType()->isFloatTy())
1041 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001042 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001043
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001044 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1045 Value *V[2];
1046 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1047 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1048 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001049 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001050
Andrew Ng1606fc02017-04-25 12:36:14 +00001051 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001052 // same name as the float version of this call, otherwise the result is an
1053 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001054 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001055 // float expf(float val) { return (float) exp((double) val); }
1056 Function *CalleeFn = CI->getCalledFunction();
1057 StringRef CalleeNm = CalleeFn->getName();
1058 AttributeList CalleeAt = CalleeFn->getAttributes();
1059 if (CalleeFn && !CalleeFn->isIntrinsic()) {
1060 const Function *Fn = CI->getFunction();
1061 StringRef FnName = Fn->getName();
1062 if (FnName.back() == 'f' &&
1063 FnName.size() == (CalleeNm.size() + 1) &&
1064 FnName.startswith(CalleeNm))
Andrew Ng1606fc02017-04-25 12:36:14 +00001065 return nullptr;
1066 }
1067
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001068 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001069 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001070 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001071
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001072 // g((double) float) -> (double) gf(float)
1073 Value *R;
1074 if (CalleeFn->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001075 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001076 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1077 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1078 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Patel848309d2014-10-23 21:52:45 +00001079 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001080 else
1081 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1082 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
Sanjay Patel848309d2014-10-23 21:52:45 +00001083
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001084 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001085}
Meador Inge193e0352012-11-13 04:16:17 +00001086
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001087/// Shrink double -> float for unary functions.
1088static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001089 bool isPrecise = false) {
1090 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001091}
1092
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001093/// Shrink double -> float for binary functions.
1094static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001095 bool isPrecise = false) {
1096 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001097}
1098
Hal Finkel2ff24732017-12-16 01:26:25 +00001099// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1100Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1101 if (!CI->isFast())
1102 return nullptr;
1103
1104 // Propagate fast-math flags from the existing call to new instructions.
1105 IRBuilder<>::FastMathFlagGuard Guard(B);
1106 B.setFastMathFlags(CI->getFastMathFlags());
1107
1108 Value *Real, *Imag;
1109 if (CI->getNumArgOperands() == 1) {
1110 Value *Op = CI->getArgOperand(0);
1111 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1112 Real = B.CreateExtractValue(Op, 0, "real");
1113 Imag = B.CreateExtractValue(Op, 1, "imag");
1114 } else {
1115 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1116 Real = CI->getArgOperand(0);
1117 Imag = CI->getArgOperand(1);
1118 }
1119
1120 Value *RealReal = B.CreateFMul(Real, Real);
1121 Value *ImagImag = B.CreateFMul(Imag, Imag);
1122
1123 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1124 CI->getType());
1125 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1126}
1127
Sanjay Patele45a83d2018-08-13 19:24:41 +00001128static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1129 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001130 if (!isa<FPMathOperator>(Call))
1131 return nullptr;
1132
1133 IRBuilder<>::FastMathFlagGuard Guard(B);
1134 B.setFastMathFlags(Call->getFastMathFlags());
1135
Sanjay Patele45a83d2018-08-13 19:24:41 +00001136 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001137 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001138 switch (Func) {
1139 case LibFunc_sin:
1140 case LibFunc_sinf:
1141 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001142 case LibFunc_tan:
1143 case LibFunc_tanf:
1144 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001145 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001146 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001147 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001148 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001149 break;
1150 case LibFunc_cos:
1151 case LibFunc_cosf:
1152 case LibFunc_cosl:
1153 // cos(-X) --> cos(X)
1154 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1155 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1156 break;
1157 default:
1158 break;
1159 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001160 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001161}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001162
Weiming Zhao82130722015-12-04 22:00:47 +00001163static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1164 // Multiplications calculated using Addition Chains.
1165 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1166
1167 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1168
1169 if (InnerChain[Exp])
1170 return InnerChain[Exp];
1171
1172 static const unsigned AddChain[33][2] = {
1173 {0, 0}, // Unused.
1174 {0, 0}, // Unused (base case = pow1).
1175 {1, 1}, // Unused (pre-computed).
1176 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1177 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1178 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1179 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1180 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1181 };
1182
1183 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1184 getPow(InnerChain, AddChain[Exp][1], B));
1185 return InnerChain[Exp];
1186}
1187
Evandro Menezes4b390102018-08-17 17:59:53 +00001188/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001189/// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001190Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1191 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1192 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1193 Module *Mod = Pow->getModule();
1194 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001195 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001196
1197 // Evaluate special cases related to a nested function as the base.
1198
1199 // pow(exp(x), y) -> exp(x * y)
1200 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001201 // If exp{,2}() is used only once, it is better to fold two transcendental
1202 // math functions into one. If used again, exp{,2}() would still have to be
1203 // called with the original argument, then keep both original transcendental
1204 // functions. However, this transformation is only safe with fully relaxed
1205 // math semantics, since, besides rounding differences, it changes overflow
1206 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001207 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1208 // Whereas:
1209 // exp(1000 * 0.001) = exp(1)
1210 // TODO: Loosen the requirement for fully relaxed math semantics.
1211 // TODO: Handle exp10() when more targets have it available.
1212 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001213 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001214 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001215
Evandro Menezes4b390102018-08-17 17:59:53 +00001216 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001217 if (CalleeFn &&
1218 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1219 StringRef ExpName;
1220 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001221 Value *ExpFn;
Mikael Holmene3605d02018-10-18 06:27:53 +00001222 LibFunc LibFnFloat;
1223 LibFunc LibFnDouble;
1224 LibFunc LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001225
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001226 switch (LibFn) {
1227 default:
1228 return nullptr;
1229 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001230 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001231 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001232 LibFnFloat = LibFunc_expf;
1233 LibFnDouble = LibFunc_exp;
1234 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001235 break;
1236 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001237 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001238 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001239 LibFnFloat = LibFunc_exp2f;
1240 LibFnDouble = LibFunc_exp2;
1241 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001242 break;
1243 }
1244
Evandro Menezes253991c2018-08-27 22:11:15 +00001245 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001246 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001247 ExpFn = BaseFn->doesNotAccessMemory()
1248 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1249 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001250 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1251 LibFnLongDouble, B,
1252 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001253
1254 // Since the new exp{,2}() is different from the original one, dead code
1255 // elimination cannot be trusted to remove it, since it may have side
1256 // effects (e.g., errno). When the only consumer for the original
1257 // exp{,2}() is pow(), then it has to be explicitly erased.
1258 BaseFn->replaceAllUsesWith(ExpFn);
Amara Emerson54f60252018-10-11 14:51:11 +00001259 eraseFromParent(BaseFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001260
1261 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001262 }
1263 }
1264
1265 // Evaluate special cases related to a constant base.
1266
Evandro Menezes2123ea72018-08-30 19:04:51 +00001267 const APFloat *BaseF;
1268 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1269 return nullptr;
1270
1271 // pow(2.0 ** n, x) -> exp2(n * x)
1272 if (hasUnaryFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1273 APFloat BaseR = APFloat(1.0);
1274 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1275 BaseR = BaseR / *BaseF;
1276 bool IsInteger = BaseF->isInteger(),
1277 IsReciprocal = BaseR.isInteger();
1278 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1279 APSInt NI(64, false);
1280 if ((IsInteger || IsReciprocal) &&
1281 !NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) &&
1282 NI > 1 && NI.isPowerOf2()) {
1283 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1284 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1285 if (Pow->doesNotAccessMemory())
1286 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1287 FMul, "exp2");
1288 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001289 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1290 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001291 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001292 }
1293
1294 // pow(10.0, x) -> exp10(x)
1295 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1296 if (match(Base, m_SpecificFP(10.0)) &&
1297 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001298 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1299 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001300
1301 return nullptr;
1302}
1303
Florian Hahncc9dc592018-09-03 17:37:39 +00001304static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1305 Module *M, IRBuilder<> &B,
1306 const TargetLibraryInfo *TLI) {
1307 // If errno is never set, then use the intrinsic for sqrt().
1308 if (NoErrno) {
1309 Function *SqrtFn =
1310 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1311 return B.CreateCall(SqrtFn, V, "sqrt");
1312 }
1313
1314 // Otherwise, use the libcall for sqrt().
1315 if (hasUnaryFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1316 LibFunc_sqrtl))
1317 // TODO: We also should check that the target can in fact lower the sqrt()
1318 // libcall. We currently have no way to ask this question, so we ask if
1319 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001320 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1321 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001322
1323 return nullptr;
1324}
1325
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001326/// Use square root in place of pow(x, +/-0.5).
1327Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001328 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001329 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1330 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001331 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001332
Evandro Menezesa7d48282018-07-30 16:20:04 +00001333 const APFloat *ExpoF;
1334 if (!match(Expo, m_APFloat(ExpoF)) ||
1335 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1336 return nullptr;
1337
Florian Hahncc9dc592018-09-03 17:37:39 +00001338 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1339 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001340 return nullptr;
1341
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001342 // Handle signed zero base by expanding to fabs(sqrt(x)).
1343 if (!Pow->hasNoSignedZeros()) {
1344 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1345 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1346 }
1347
1348 // Handle non finite base by expanding to
1349 // (x == -infinity ? +infinity : sqrt(x)).
1350 if (!Pow->hasNoInfs()) {
1351 Value *PosInf = ConstantFP::getInfinity(Ty),
1352 *NegInf = ConstantFP::getInfinity(Ty, true);
1353 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1354 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1355 }
1356
Evandro Menezes61e4e402018-07-31 22:11:02 +00001357 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001358 if (ExpoF->isNegative())
1359 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001360
1361 return Sqrt;
1362}
1363
Evandro Menezesa7d48282018-07-30 16:20:04 +00001364Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1365 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1366 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001367 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001368 Type *Ty = Pow->getType();
1369 Value *Shrunk = nullptr;
1370 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001371
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001372 // Bail out if simplifying libcalls to pow() is disabled.
1373 if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1374 return nullptr;
1375
Evandro Menezes61e4e402018-07-31 22:11:02 +00001376 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001377 IRBuilder<>::FastMathFlagGuard Guard(B);
1378 B.setFastMathFlags(Pow->getFastMathFlags());
1379
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001380 // Shrink pow() to powf() if the arguments are single precision,
1381 // unless the result is expected to be double precision.
1382 if (UnsafeFPShrink &&
1383 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1384 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1385
Evandro Menezesa7d48282018-07-30 16:20:04 +00001386 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001387
1388 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001389 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001390 return Base;
1391
Evandro Menezes4b390102018-08-17 17:59:53 +00001392 if (Value *Exp = replacePowWithExp(Pow, B))
1393 return Exp;
Davide Italianoc8a79132015-11-03 20:32:23 +00001394
Evandro Menezesa7d48282018-07-30 16:20:04 +00001395 // Evaluate special cases related to the exponent.
1396
Evandro Menezesa7d48282018-07-30 16:20:04 +00001397 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001398 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001399 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1400
1401 // pow(x, 0.0) -> 1.0
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001402 if (match(Expo, m_SpecificFP(0.0)))
1403 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001404
1405 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001406 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001407 return Base;
1408
1409 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001410 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001411 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001412
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001413 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1414 return Sqrt;
1415
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001416 // pow(x, n) -> x * x * x * ...
1417 const APFloat *ExpoF;
1418 if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
1419 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001420 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1421 // additional fmul.
1422 // TODO: This whole transformation should be backend specific (e.g. some
1423 // backends might prefer libcalls or the limit for the exponent might
1424 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001425 APFloat LimF(ExpoF->getSemantics(), 33.0),
1426 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001427 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1428 // This transformation applies to integer or integer+0.5 exponents only.
1429 // For integer+0.5, we create a sqrt(Base) call.
1430 Value *Sqrt = nullptr;
1431 if (!ExpoA.isInteger()) {
1432 APFloat Expo2 = ExpoA;
1433 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1434 // is no floating point exception and the result is an integer, then
1435 // ExpoA == integer + 0.5
1436 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1437 return nullptr;
1438
1439 if (!Expo2.isInteger())
1440 return nullptr;
1441
1442 Sqrt =
1443 getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1444 Pow->doesNotAccessMemory(), Pow->getModule(), B, TLI);
1445 }
1446
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001447 // We will memoize intermediate products of the Addition Chain.
1448 Value *InnerChain[33] = {nullptr};
1449 InnerChain[1] = Base;
1450 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001451
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001452 // We cannot readily convert a non-double type (like float) to a double.
1453 // So we first convert it to something which could be converted to double.
1454 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1455 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001456
Florian Hahncc9dc592018-09-03 17:37:39 +00001457 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1458 if (Sqrt)
1459 FMul = B.CreateFMul(FMul, Sqrt);
1460
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001461 // If the exponent is negative, then get the reciprocal.
1462 if (ExpoF->isNegative())
1463 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001464
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001465 return FMul;
1466 }
Weiming Zhao82130722015-12-04 22:00:47 +00001467 }
1468
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001469 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001470}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001471
Chris Bienemanad070d02014-09-17 20:55:46 +00001472Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1473 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001474 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001475 StringRef Name = Callee->getName();
1476 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001477 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001478
Chris Bienemanad070d02014-09-17 20:55:46 +00001479 Value *Op = CI->getArgOperand(0);
1480 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1481 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001482 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001483 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001484 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001485 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001486 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001487
1488 if (TLI->has(LdExp)) {
1489 Value *LdExpArg = nullptr;
1490 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1491 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1492 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1493 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1494 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1495 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1496 }
1497
1498 if (LdExpArg) {
1499 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1500 if (!Op->getType()->isFloatTy())
1501 One = ConstantExpr::getFPExtend(One, Op->getType());
1502
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001503 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001504 Value *NewCallee =
1505 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001506 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001507 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001508 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1509 CI->setCallingConv(F->getCallingConv());
1510
1511 return CI;
1512 }
1513 }
1514 return Ret;
1515}
1516
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001517Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001518 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001519 // If we can shrink the call to a float function rather than a double
1520 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001521 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001522 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1523 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001524 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001525
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001526 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001527 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001528 if (CI->isFast()) {
1529 // If the call is 'fast', then anything we create here will also be 'fast'.
1530 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001531 } else {
1532 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001533 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001534 return nullptr;
1535 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1536 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001537 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001538 // might be impractical."
1539 FMF.setNoSignedZeros();
1540 FMF.setNoNaNs();
1541 }
Sanjay Patela2528152016-01-12 18:03:37 +00001542 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001543
1544 // We have a relaxed floating-point environment. We can ignore NaN-handling
1545 // and transform to a compare and select. We do not have to consider errno or
1546 // exceptions, because fmin/fmax do not have those.
1547 Value *Op0 = CI->getArgOperand(0);
1548 Value *Op1 = CI->getArgOperand(1);
1549 Value *Cmp = Callee->getName().startswith("fmin") ?
1550 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1551 return B.CreateSelect(Cmp, Op0, Op1);
1552}
1553
Davide Italianob8b71332015-11-29 20:58:04 +00001554Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1555 Function *Callee = CI->getCalledFunction();
1556 Value *Ret = nullptr;
1557 StringRef Name = Callee->getName();
1558 if (UnsafeFPShrink && hasFloatVersion(Name))
1559 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001560
Sanjay Patel629c4112017-11-06 16:27:15 +00001561 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001562 return Ret;
1563 Value *Op1 = CI->getArgOperand(0);
1564 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001565
Sanjay Patel629c4112017-11-06 16:27:15 +00001566 // The earlier call must also be 'fast' in order to do these transforms.
1567 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001568 return Ret;
1569
1570 // log(pow(x,y)) -> y*log(x)
1571 // This is only applicable to log, log2, log10.
1572 if (Name != "log" && Name != "log2" && Name != "log10")
1573 return Ret;
1574
1575 IRBuilder<>::FastMathFlagGuard Guard(B);
1576 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001577 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001578 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001579
David L. Jonesd21529f2017-01-23 23:16:46 +00001580 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001581 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001582 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001583 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001584 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001585 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001586 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001587
1588 // log(exp2(y)) -> y*log(2)
1589 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001590 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001591 return B.CreateFMul(
1592 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001593 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001594 Callee->getName(), B, Callee->getAttributes()),
1595 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001596 return Ret;
1597}
1598
Sanjay Patelc699a612014-10-16 18:48:17 +00001599Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1600 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001601 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001602 // TODO: Once we have a way (other than checking for the existince of the
1603 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1604 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001605 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001606 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001607 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001608
Sanjay Patel629c4112017-11-06 16:27:15 +00001609 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001610 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001611
Sanjay Patelc2d64612016-01-06 20:52:21 +00001612 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001613 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001614 return Ret;
1615
1616 // We're looking for a repeated factor in a multiplication tree,
1617 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001618 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001619 Value *Op0 = I->getOperand(0);
1620 Value *Op1 = I->getOperand(1);
1621 Value *RepeatOp = nullptr;
1622 Value *OtherOp = nullptr;
1623 if (Op0 == Op1) {
1624 // Simple match: the operands of the multiply are identical.
1625 RepeatOp = Op0;
1626 } else {
1627 // Look for a more complicated pattern: one of the operands is itself
1628 // a multiply, so search for a common factor in that multiply.
1629 // Note: We don't bother looking any deeper than this first level or for
1630 // variations of this pattern because instcombine's visitFMUL and/or the
1631 // reassociation pass should give us this form.
1632 Value *OtherMul0, *OtherMul1;
1633 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1634 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001635 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001636 // Matched: sqrt((x * x) * z)
1637 RepeatOp = OtherMul0;
1638 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001639 }
1640 }
1641 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001642 if (!RepeatOp)
1643 return Ret;
1644
1645 // Fast math flags for any created instructions should match the sqrt
1646 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001647 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001648 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001649
Sanjay Patelc2d64612016-01-06 20:52:21 +00001650 // If we found a repeated factor, hoist it out of the square root and
1651 // replace it with the fabs of that factor.
1652 Module *M = Callee->getParent();
1653 Type *ArgType = I->getType();
1654 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1655 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1656 if (OtherOp) {
1657 // If we found a non-repeated factor, we still need to get its square
1658 // root. We then multiply that by the value that was simplified out
1659 // of the square root calculation.
1660 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1661 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1662 return B.CreateFMul(FabsCall, SqrtCall);
1663 }
1664 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001665}
1666
Sanjay Patelcddcd722016-01-06 19:23:35 +00001667// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001668Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1669 Function *Callee = CI->getCalledFunction();
1670 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001671 StringRef Name = Callee->getName();
1672 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001673 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001674
Davide Italiano51507d22015-11-04 23:36:56 +00001675 Value *Op1 = CI->getArgOperand(0);
1676 auto *OpC = dyn_cast<CallInst>(Op1);
1677 if (!OpC)
1678 return Ret;
1679
Sanjay Patel629c4112017-11-06 16:27:15 +00001680 // Both calls must be 'fast' in order to remove them.
1681 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001682 return Ret;
1683
Davide Italiano51507d22015-11-04 23:36:56 +00001684 // tan(atan(x)) -> x
1685 // tanf(atanf(x)) -> x
1686 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001687 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001688 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001689 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001690 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1691 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1692 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001693 Ret = OpC->getArgOperand(0);
1694 return Ret;
1695}
1696
Sanjay Patel57747212016-01-21 23:38:43 +00001697static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001698 // We can only hope to do anything useful if we can ignore things like errno
1699 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001700 // We already checked the prototype.
1701 return CI->hasFnAttr(Attribute::NoUnwind) &&
1702 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001703}
1704
Chris Bienemanad070d02014-09-17 20:55:46 +00001705static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1706 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001707 Value *&SinCos) {
1708 Type *ArgTy = Arg->getType();
1709 Type *ResTy;
1710 StringRef Name;
1711
1712 Triple T(OrigCallee->getParent()->getTargetTriple());
1713 if (UseFloat) {
1714 Name = "__sincospif_stret";
1715
1716 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1717 // x86_64 can't use {float, float} since that would be returned in both
1718 // xmm0 and xmm1, which isn't what a real struct would do.
1719 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001720 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1721 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001722 } else {
1723 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001724 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001725 }
1726
1727 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001728 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001729 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001730
1731 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1732 // If the argument is an instruction, it must dominate all uses so put our
1733 // sincos call there.
1734 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1735 } else {
1736 // Otherwise (e.g. for a constant) the beginning of the function is as
1737 // good a place as any.
1738 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1739 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1740 }
1741
1742 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1743
1744 if (SinCos->getType()->isStructTy()) {
1745 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1746 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1747 } else {
1748 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1749 "sinpi");
1750 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1751 "cospi");
1752 }
1753}
Chris Bienemanad070d02014-09-17 20:55:46 +00001754
1755Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001756 // Make sure the prototype is as expected, otherwise the rest of the
1757 // function is probably invalid and likely to abort.
1758 if (!isTrigLibCall(CI))
1759 return nullptr;
1760
1761 Value *Arg = CI->getArgOperand(0);
1762 SmallVector<CallInst *, 1> SinCalls;
1763 SmallVector<CallInst *, 1> CosCalls;
1764 SmallVector<CallInst *, 1> SinCosCalls;
1765
1766 bool IsFloat = Arg->getType()->isFloatTy();
1767
1768 // Look for all compatible sinpi, cospi and sincospi calls with the same
1769 // argument. If there are enough (in some sense) we can make the
1770 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001771 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001772 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001773 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001774
1775 // It's only worthwhile if both sinpi and cospi are actually used.
1776 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1777 return nullptr;
1778
1779 Value *Sin, *Cos, *SinCos;
1780 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1781
Davide Italianof024a562016-12-16 02:28:38 +00001782 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1783 Value *Res) {
1784 for (CallInst *C : Calls)
1785 replaceAllUsesWith(C, Res);
1786 };
1787
Chris Bienemanad070d02014-09-17 20:55:46 +00001788 replaceTrigInsts(SinCalls, Sin);
1789 replaceTrigInsts(CosCalls, Cos);
1790 replaceTrigInsts(SinCosCalls, SinCos);
1791
1792 return nullptr;
1793}
1794
David Majnemerabae6b52016-03-19 04:53:02 +00001795void LibCallSimplifier::classifyArgUse(
1796 Value *Val, Function *F, bool IsFloat,
1797 SmallVectorImpl<CallInst *> &SinCalls,
1798 SmallVectorImpl<CallInst *> &CosCalls,
1799 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 CallInst *CI = dyn_cast<CallInst>(Val);
1801
1802 if (!CI)
1803 return;
1804
David Majnemerabae6b52016-03-19 04:53:02 +00001805 // Don't consider calls in other functions.
1806 if (CI->getFunction() != F)
1807 return;
1808
Chris Bienemanad070d02014-09-17 20:55:46 +00001809 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001810 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001811 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001812 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001813 return;
1814
1815 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001816 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001817 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001818 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001819 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001820 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 SinCosCalls.push_back(CI);
1822 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001823 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001825 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001826 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001827 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 SinCosCalls.push_back(CI);
1829 }
1830}
1831
Meador Inge7415f842012-11-25 20:45:27 +00001832//===----------------------------------------------------------------------===//
1833// Integer Library Call Optimizations
1834//===----------------------------------------------------------------------===//
1835
Chris Bienemanad070d02014-09-17 20:55:46 +00001836Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001837 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001838 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001840 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1841 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001842 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001843 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1844 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001845
Chris Bienemanad070d02014-09-17 20:55:46 +00001846 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1847 return B.CreateSelect(Cond, V, B.getInt32(0));
1848}
Meador Ingea0b6d872012-11-26 00:24:07 +00001849
Davide Italiano85ad36b2016-12-15 23:45:11 +00001850Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1851 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1852 Value *Op = CI->getArgOperand(0);
1853 Type *ArgType = Op->getType();
1854 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1855 Intrinsic::ctlz, ArgType);
1856 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1857 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1858 V);
1859 return B.CreateIntCast(V, CI->getType(), false);
1860}
1861
Chris Bienemanad070d02014-09-17 20:55:46 +00001862Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001863 // abs(x) -> x <s 0 ? -x : x
1864 // The negation has 'nsw' because abs of INT_MIN is undefined.
1865 Value *X = CI->getArgOperand(0);
1866 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1867 Value *NegX = B.CreateNSWNeg(X, "neg");
1868 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001869}
Meador Inge9a59ab62012-11-26 02:31:59 +00001870
Chris Bienemanad070d02014-09-17 20:55:46 +00001871Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001872 // isdigit(c) -> (c-'0') <u 10
1873 Value *Op = CI->getArgOperand(0);
1874 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1875 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1876 return B.CreateZExt(Op, CI->getType());
1877}
Meador Ingea62a39e2012-11-26 03:10:07 +00001878
Chris Bienemanad070d02014-09-17 20:55:46 +00001879Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001880 // isascii(c) -> c <u 128
1881 Value *Op = CI->getArgOperand(0);
1882 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1883 return B.CreateZExt(Op, CI->getType());
1884}
1885
1886Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001887 // toascii(c) -> c & 0x7f
1888 return B.CreateAnd(CI->getArgOperand(0),
1889 ConstantInt::get(CI->getType(), 0x7F));
1890}
Meador Inge604937d2012-11-26 03:38:52 +00001891
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001892Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1893 StringRef Str;
1894 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1895 return nullptr;
1896
1897 return convertStrToNumber(CI, Str, 10);
1898}
1899
1900Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1901 StringRef Str;
1902 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1903 return nullptr;
1904
1905 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1906 return nullptr;
1907
1908 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1909 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1910 }
1911
1912 return nullptr;
1913}
1914
Meador Inge08ca1152012-11-26 20:37:20 +00001915//===----------------------------------------------------------------------===//
1916// Formatting and IO Library Call Optimizations
1917//===----------------------------------------------------------------------===//
1918
Chris Bienemanad070d02014-09-17 20:55:46 +00001919static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001920
Chris Bienemanad070d02014-09-17 20:55:46 +00001921Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1922 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001923 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001924 // Error reporting calls should be cold, mark them as such.
1925 // This applies even to non-builtin calls: it is only a hint and applies to
1926 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001927
Chris Bienemanad070d02014-09-17 20:55:46 +00001928 // This heuristic was suggested in:
1929 // Improving Static Branch Prediction in a Compiler
1930 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1931 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001932 if (!CI->hasFnAttr(Attribute::Cold) &&
1933 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001934 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001935 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001936
Chris Bienemanad070d02014-09-17 20:55:46 +00001937 return nullptr;
1938}
1939
1940static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001941 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001942 return false;
1943
1944 if (StreamArg < 0)
1945 return true;
1946
1947 // These functions might be considered cold, but only if their stream
1948 // argument is stderr.
1949
1950 if (StreamArg >= (int)CI->getNumArgOperands())
1951 return false;
1952 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1953 if (!LI)
1954 return false;
1955 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1956 if (!GV || !GV->isDeclaration())
1957 return false;
1958 return GV->getName() == "stderr";
1959}
1960
1961Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1962 // Check for a fixed format string.
1963 StringRef FormatStr;
1964 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001965 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001966
Chris Bienemanad070d02014-09-17 20:55:46 +00001967 // Empty format string -> noop.
1968 if (FormatStr.empty()) // Tolerate printf's declared void.
1969 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001970
Chris Bienemanad070d02014-09-17 20:55:46 +00001971 // Do not do any of the following transformations if the printf return value
1972 // is used, in general the printf return value is not compatible with either
1973 // putchar() or puts().
1974 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001975 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001976
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001977 // printf("x") -> putchar('x'), even for "%" and "%%".
1978 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001979 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001980
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001981 // printf("%s", "a") --> putchar('a')
1982 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1983 StringRef ChrStr;
1984 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1985 return nullptr;
1986 if (ChrStr.size() != 1)
1987 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001988 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001989 }
1990
Chris Bienemanad070d02014-09-17 20:55:46 +00001991 // printf("foo\n") --> puts("foo")
1992 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1993 FormatStr.find('%') == StringRef::npos) { // No format characters.
1994 // Create a string literal with no \n on it. We expect the constant merge
1995 // pass to be run after this pass, to merge duplicate strings.
1996 FormatStr = FormatStr.drop_back();
1997 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001998 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001999 }
Meador Inge08ca1152012-11-26 20:37:20 +00002000
Chris Bienemanad070d02014-09-17 20:55:46 +00002001 // Optimize specific format strings.
2002 // printf("%c", chr) --> putchar(chr)
2003 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002004 CI->getArgOperand(1)->getType()->isIntegerTy())
2005 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002006
2007 // printf("%s\n", str) --> puts(str)
2008 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002009 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002010 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002011 return nullptr;
2012}
2013
2014Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2015
2016 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002017 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002018 if (Value *V = optimizePrintFString(CI, B)) {
2019 return V;
2020 }
2021
2022 // printf(format, ...) -> iprintf(format, ...) if no floating point
2023 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002024 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002025 Module *M = B.GetInsertBlock()->getParent()->getParent();
2026 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002027 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002028 CallInst *New = cast<CallInst>(CI->clone());
2029 New->setCalledFunction(IPrintFFn);
2030 B.Insert(New);
2031 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002032 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002033 return nullptr;
2034}
Meador Inge08ca1152012-11-26 20:37:20 +00002035
Chris Bienemanad070d02014-09-17 20:55:46 +00002036Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2037 // Check for a fixed format string.
2038 StringRef FormatStr;
2039 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002040 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002041
Chris Bienemanad070d02014-09-17 20:55:46 +00002042 // If we just have a format string (nothing else crazy) transform it.
2043 if (CI->getNumArgOperands() == 2) {
2044 // Make sure there's no % in the constant array. We could try to handle
2045 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002046 if (FormatStr.find('%') != StringRef::npos)
2047 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002048
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002049 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2050 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002051 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002052 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002053 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002054 }
Meador Ingef8e72502012-11-29 15:45:43 +00002055
Chris Bienemanad070d02014-09-17 20:55:46 +00002056 // The remaining optimizations require the format string to be "%s" or "%c"
2057 // and have an extra operand.
2058 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2059 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002060 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002061
Chris Bienemanad070d02014-09-17 20:55:46 +00002062 // Decode the second character of the format string.
2063 if (FormatStr[1] == 'c') {
2064 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2065 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2066 return nullptr;
2067 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00002068 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002069 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002070 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002071 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002072
Chris Bienemanad070d02014-09-17 20:55:46 +00002073 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002074 }
2075
Chris Bienemanad070d02014-09-17 20:55:46 +00002076 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00002077 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
2078 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2079 return nullptr;
2080
Sanjay Pateld3112a52016-01-19 19:46:10 +00002081 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002082 if (!Len)
2083 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002084 Value *IncLen =
2085 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002086 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002087
2088 // The sprintf result is the unincremented number of bytes in the string.
2089 return B.CreateIntCast(Len, CI->getType(), false);
2090 }
2091 return nullptr;
2092}
2093
2094Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2095 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002096 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002097 if (Value *V = optimizeSPrintFString(CI, B)) {
2098 return V;
2099 }
2100
2101 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2102 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002103 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002104 Module *M = B.GetInsertBlock()->getParent()->getParent();
2105 Constant *SIPrintFFn =
2106 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2107 CallInst *New = cast<CallInst>(CI->clone());
2108 New->setCalledFunction(SIPrintFFn);
2109 B.Insert(New);
2110 return New;
2111 }
2112 return nullptr;
2113}
2114
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002115Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2116 // Check for a fixed format string.
2117 StringRef FormatStr;
2118 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2119 return nullptr;
2120
2121 // Check for size
2122 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2123 if (!Size)
2124 return nullptr;
2125
2126 uint64_t N = Size->getZExtValue();
2127
2128 // If we just have a format string (nothing else crazy) transform it.
2129 if (CI->getNumArgOperands() == 3) {
2130 // Make sure there's no % in the constant array. We could try to handle
2131 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002132 if (FormatStr.find('%') != StringRef::npos)
2133 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002134
2135 if (N == 0)
2136 return ConstantInt::get(CI->getType(), FormatStr.size());
2137 else if (N < FormatStr.size() + 1)
2138 return nullptr;
2139
2140 // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
2141 // strlen(fmt)+1)
2142 B.CreateMemCpy(
2143 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2144 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2145 FormatStr.size() + 1)); // Copy the null byte.
2146 return ConstantInt::get(CI->getType(), FormatStr.size());
2147 }
2148
2149 // The remaining optimizations require the format string to be "%s" or "%c"
2150 // and have an extra operand.
2151 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2152 CI->getNumArgOperands() == 4) {
2153
2154 // Decode the second character of the format string.
2155 if (FormatStr[1] == 'c') {
2156 if (N == 0)
2157 return ConstantInt::get(CI->getType(), 1);
2158 else if (N == 1)
2159 return nullptr;
2160
2161 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2162 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2163 return nullptr;
2164 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2165 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2166 B.CreateStore(V, Ptr);
2167 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2168 B.CreateStore(B.getInt8(0), Ptr);
2169
2170 return ConstantInt::get(CI->getType(), 1);
2171 }
2172
2173 if (FormatStr[1] == 's') {
2174 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2175 StringRef Str;
2176 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2177 return nullptr;
2178
2179 if (N == 0)
2180 return ConstantInt::get(CI->getType(), Str.size());
2181 else if (N < Str.size() + 1)
2182 return nullptr;
2183
2184 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2185 ConstantInt::get(CI->getType(), Str.size() + 1));
2186
2187 // The snprintf result is the unincremented number of bytes in the string.
2188 return ConstantInt::get(CI->getType(), Str.size());
2189 }
2190 }
2191 return nullptr;
2192}
2193
2194Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2195 if (Value *V = optimizeSnPrintFString(CI, B)) {
2196 return V;
2197 }
2198
2199 return nullptr;
2200}
2201
Chris Bienemanad070d02014-09-17 20:55:46 +00002202Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2203 optimizeErrorReporting(CI, B, 0);
2204
2205 // All the optimizations depend on the format string.
2206 StringRef FormatStr;
2207 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2208 return nullptr;
2209
2210 // Do not do any of the following transformations if the fprintf return
2211 // value is used, in general the fprintf return value is not compatible
2212 // with fwrite(), fputc() or fputs().
2213 if (!CI->use_empty())
2214 return nullptr;
2215
2216 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2217 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002218 // Could handle %% -> % if we cared.
2219 if (FormatStr.find('%') != StringRef::npos)
2220 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002221
Sanjay Pateld3112a52016-01-19 19:46:10 +00002222 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002223 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002224 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002225 CI->getArgOperand(0), B, DL, TLI);
2226 }
2227
2228 // The remaining optimizations require the format string to be "%s" or "%c"
2229 // and have an extra operand.
2230 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2231 CI->getNumArgOperands() < 3)
2232 return nullptr;
2233
2234 // Decode the second character of the format string.
2235 if (FormatStr[1] == 'c') {
2236 // fprintf(F, "%c", chr) --> fputc(chr, F)
2237 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2238 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002239 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002240 }
2241
2242 if (FormatStr[1] == 's') {
2243 // fprintf(F, "%s", str) --> fputs(str, F)
2244 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2245 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002246 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002247 }
2248 return nullptr;
2249}
2250
2251Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2252 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002253 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002254 if (Value *V = optimizeFPrintFString(CI, B)) {
2255 return V;
2256 }
2257
2258 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2259 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002260 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002261 Module *M = B.GetInsertBlock()->getParent()->getParent();
2262 Constant *FIPrintFFn =
2263 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2264 CallInst *New = cast<CallInst>(CI->clone());
2265 New->setCalledFunction(FIPrintFFn);
2266 B.Insert(New);
2267 return New;
2268 }
2269 return nullptr;
2270}
2271
2272Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2273 optimizeErrorReporting(CI, B, 3);
2274
Chris Bienemanad070d02014-09-17 20:55:46 +00002275 // Get the element size and count.
2276 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2277 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002278 if (SizeC && CountC) {
2279 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002280
David Bolvanskyca22d422018-05-16 11:39:52 +00002281 // If this is writing zero records, remove the call (it's a noop).
2282 if (Bytes == 0)
2283 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002284
David Bolvanskyca22d422018-05-16 11:39:52 +00002285 // If this is writing one byte, turn it into fputc.
2286 // This optimisation is only valid, if the return value is unused.
2287 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2288 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2289 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2290 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2291 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002292 }
2293
David Bolvanskyca22d422018-05-16 11:39:52 +00002294 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2295 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2296 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2297 TLI);
2298
Chris Bienemanad070d02014-09-17 20:55:46 +00002299 return nullptr;
2300}
2301
2302Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2303 optimizeErrorReporting(CI, B, 1);
2304
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002305 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2306 // requires more arguments and thus extra MOVs are required.
David Bolvansky5430b7372018-05-31 16:39:27 +00002307 if (CI->getFunction()->optForSize())
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002308 return nullptr;
2309
David Bolvanskyca22d422018-05-16 11:39:52 +00002310 // Check if has any use
2311 if (!CI->use_empty()) {
2312 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2313 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2314 TLI);
2315 else
2316 // We can't optimize if return value is used.
2317 return nullptr;
2318 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002319
2320 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002321 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002322 if (!Len)
2323 return nullptr;
2324
2325 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002326 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002327 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002328 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002329 CI->getArgOperand(1), B, DL, TLI);
2330}
2331
David Bolvanskyca22d422018-05-16 11:39:52 +00002332Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2333 optimizeErrorReporting(CI, B, 1);
2334
2335 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2336 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2337 TLI);
2338
2339 return nullptr;
2340}
2341
2342Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2343 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2344 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2345
2346 return nullptr;
2347}
2348
2349Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2350 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2351 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2352 CI->getArgOperand(2), B, TLI);
2353
2354 return nullptr;
2355}
2356
2357Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2358 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2359 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2360 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2361 TLI);
2362
2363 return nullptr;
2364}
2365
Chris Bienemanad070d02014-09-17 20:55:46 +00002366Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002367 // Check for a constant string.
2368 StringRef Str;
2369 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2370 return nullptr;
2371
2372 if (Str.empty() && CI->use_empty()) {
2373 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002374 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002375 if (CI->use_empty() || !Res)
2376 return Res;
2377 return B.CreateIntCast(Res, CI->getType(), true);
2378 }
2379
2380 return nullptr;
2381}
2382
2383bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002384 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002385 SmallString<20> FloatFuncName = FuncName;
2386 FloatFuncName += 'f';
2387 if (TLI->getLibFunc(FloatFuncName, Func))
2388 return TLI->has(Func);
2389 return false;
2390}
Meador Inge7fb2f732012-10-13 16:45:32 +00002391
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002392Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2393 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002394 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002395 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002396 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002397 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002398 // Make sure we never change the calling convention.
2399 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002400 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002401 "Optimizing string/memory libcall would change the calling convention");
2402 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002403 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002404 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002405 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002406 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002407 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002408 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002409 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002410 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002411 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002412 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002413 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002414 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002415 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002416 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002417 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002418 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002419 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002420 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002421 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002422 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002423 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002424 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002425 case LibFunc_strtol:
2426 case LibFunc_strtod:
2427 case LibFunc_strtof:
2428 case LibFunc_strtoul:
2429 case LibFunc_strtoll:
2430 case LibFunc_strtold:
2431 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002432 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002433 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002434 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002435 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002436 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002437 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002438 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002439 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002440 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002441 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002442 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002443 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002444 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002445 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002446 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002447 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002448 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002449 case LibFunc_realloc:
2450 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002451 case LibFunc_wcslen:
2452 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002453 default:
2454 break;
2455 }
2456 }
2457 return nullptr;
2458}
2459
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002460Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2461 LibFunc Func,
2462 IRBuilder<> &Builder) {
2463 // Don't optimize calls that require strict floating point semantics.
2464 if (CI->isStrictFP())
2465 return nullptr;
2466
Sanjay Patele45a83d2018-08-13 19:24:41 +00002467 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2468 return V;
2469
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002470 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002471 case LibFunc_sinpif:
2472 case LibFunc_sinpi:
2473 case LibFunc_cospif:
2474 case LibFunc_cospi:
2475 return optimizeSinCosPi(CI, Builder);
2476 case LibFunc_powf:
2477 case LibFunc_pow:
2478 case LibFunc_powl:
2479 return optimizePow(CI, Builder);
2480 case LibFunc_exp2l:
2481 case LibFunc_exp2:
2482 case LibFunc_exp2f:
2483 return optimizeExp2(CI, Builder);
2484 case LibFunc_fabsf:
2485 case LibFunc_fabs:
2486 case LibFunc_fabsl:
2487 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2488 case LibFunc_sqrtf:
2489 case LibFunc_sqrt:
2490 case LibFunc_sqrtl:
2491 return optimizeSqrt(CI, Builder);
2492 case LibFunc_log:
2493 case LibFunc_log10:
2494 case LibFunc_log1p:
2495 case LibFunc_log2:
2496 case LibFunc_logb:
2497 return optimizeLog(CI, Builder);
2498 case LibFunc_tan:
2499 case LibFunc_tanf:
2500 case LibFunc_tanl:
2501 return optimizeTan(CI, Builder);
2502 case LibFunc_ceil:
2503 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2504 case LibFunc_floor:
2505 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2506 case LibFunc_round:
2507 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2508 case LibFunc_nearbyint:
2509 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2510 case LibFunc_rint:
2511 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2512 case LibFunc_trunc:
2513 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2514 case LibFunc_acos:
2515 case LibFunc_acosh:
2516 case LibFunc_asin:
2517 case LibFunc_asinh:
2518 case LibFunc_atan:
2519 case LibFunc_atanh:
2520 case LibFunc_cbrt:
2521 case LibFunc_cosh:
2522 case LibFunc_exp:
2523 case LibFunc_exp10:
2524 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002525 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002526 case LibFunc_sin:
2527 case LibFunc_sinh:
2528 case LibFunc_tanh:
2529 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2530 return optimizeUnaryDoubleFP(CI, Builder, true);
2531 return nullptr;
2532 case LibFunc_copysign:
2533 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2534 return optimizeBinaryDoubleFP(CI, Builder);
2535 return nullptr;
2536 case LibFunc_fminf:
2537 case LibFunc_fmin:
2538 case LibFunc_fminl:
2539 case LibFunc_fmaxf:
2540 case LibFunc_fmax:
2541 case LibFunc_fmaxl:
2542 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002543 case LibFunc_cabs:
2544 case LibFunc_cabsf:
2545 case LibFunc_cabsl:
2546 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002547 default:
2548 return nullptr;
2549 }
2550}
2551
Chris Bienemanad070d02014-09-17 20:55:46 +00002552Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002553 // TODO: Split out the code below that operates on FP calls so that
2554 // we can all non-FP calls with the StrictFP attribute to be
2555 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002556 if (CI->isNoBuiltin())
2557 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002558
David L. Jonesd21529f2017-01-23 23:16:46 +00002559 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002560 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002561
2562 SmallVector<OperandBundleDef, 2> OpBundles;
2563 CI->getOperandBundlesAsDefs(OpBundles);
2564 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002565 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002566
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002567 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002568 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002569 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002570 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2571 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002572 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002573 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002574
Sanjay Patel848309d2014-10-23 21:52:45 +00002575 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002576 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002577 if (!isCallingConvC)
2578 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002579 // The FP intrinsics have corresponding constrained versions so we don't
2580 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002581 switch (II->getIntrinsicID()) {
2582 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002583 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002584 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002585 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002586 case Intrinsic::log:
2587 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002588 case Intrinsic::sqrt:
2589 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002590 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002591 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002592 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002593 }
2594 }
2595
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002596 // Also try to simplify calls to fortified library functions.
2597 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2598 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002599 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002600 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2601 // Use an IR Builder from SimplifiedCI if available instead of CI
2602 // to guarantee we reach all uses we might replace later on.
2603 IRBuilder<> TmpBuilder(SimplifiedCI);
2604 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002605 // If we were able to further simplify, remove the now redundant call.
2606 SimplifiedCI->replaceAllUsesWith(V);
Amara Emerson54f60252018-10-11 14:51:11 +00002607 eraseFromParent(SimplifiedCI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002608 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002609 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002610 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002611 return SimplifiedFortifiedCI;
2612 }
2613
Meador Inge20255ef2013-03-12 00:08:29 +00002614 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002615 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002616 // We never change the calling convention.
2617 if (!ignoreCallingConv(Func) && !isCallingConvC)
2618 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002619 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2620 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002621 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2622 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002623 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002624 case LibFunc_ffs:
2625 case LibFunc_ffsl:
2626 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002627 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002628 case LibFunc_fls:
2629 case LibFunc_flsl:
2630 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002631 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002632 case LibFunc_abs:
2633 case LibFunc_labs:
2634 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002635 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002636 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002637 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002638 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002639 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002640 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002641 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002642 case LibFunc_atoi:
2643 case LibFunc_atol:
2644 case LibFunc_atoll:
2645 return optimizeAtoi(CI, Builder);
2646 case LibFunc_strtol:
2647 case LibFunc_strtoll:
2648 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002649 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002650 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002651 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002652 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002653 case LibFunc_snprintf:
2654 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002655 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002656 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002657 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002658 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002659 case LibFunc_fread:
2660 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002661 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002662 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002663 case LibFunc_fgets:
2664 return optimizeFGets(CI, Builder);
2665 case LibFunc_fputc:
2666 return optimizeFPutc(CI, Builder);
2667 case LibFunc_fgetc:
2668 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002669 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002670 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002671 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002672 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002673 case LibFunc_vfprintf:
2674 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002675 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002676 default:
2677 return nullptr;
2678 }
Meador Inge20255ef2013-03-12 00:08:29 +00002679 }
Craig Topperf40110f2014-04-25 05:29:35 +00002680 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002681}
2682
Chandler Carruth92803822015-01-21 02:11:59 +00002683LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002684 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002685 OptimizationRemarkEmitter &ORE,
Amara Emerson54f60252018-10-11 14:51:11 +00002686 function_ref<void(Instruction *, Value *)> Replacer,
2687 function_ref<void(Instruction *)> Eraser)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002688 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
Amara Emerson54f60252018-10-11 14:51:11 +00002689 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002690
2691void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2692 // Indirect through the replacer used in this instance.
2693 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002694}
2695
Amara Emerson54f60252018-10-11 14:51:11 +00002696void LibCallSimplifier::eraseFromParent(Instruction *I) {
2697 Eraser(I);
2698}
2699
Meador Ingedfb08a22013-06-20 19:48:07 +00002700// TODO:
2701// Additional cases that we need to add to this file:
2702//
2703// cbrt:
2704// * cbrt(expN(X)) -> expN(x/3)
2705// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002706// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002707//
2708// exp, expf, expl:
2709// * exp(log(x)) -> x
2710//
2711// log, logf, logl:
2712// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002713// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002714// * log(exp10(y)) -> y*log(10)
2715// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002716//
Meador Ingedfb08a22013-06-20 19:48:07 +00002717// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002718// * pow(sqrt(x),y) -> pow(x,y*0.5)
2719// * pow(pow(x,y),z)-> pow(x,y*z)
2720//
Meador Ingedfb08a22013-06-20 19:48:07 +00002721// signbit:
2722// * signbit(cnst) -> cnst'
2723// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2724//
2725// sqrt, sqrtf, sqrtl:
2726// * sqrt(expN(x)) -> expN(x*0.5)
2727// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2728// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2729//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002730
2731//===----------------------------------------------------------------------===//
2732// Fortified Library Call Optimizations
2733//===----------------------------------------------------------------------===//
2734
2735bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2736 unsigned ObjSizeOp,
2737 unsigned SizeOp,
2738 bool isString) {
2739 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2740 return true;
2741 if (ConstantInt *ObjSizeCI =
2742 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002743 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002744 return true;
2745 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2746 if (OnlyLowerUnknownSize)
2747 return false;
2748 if (isString) {
David Bolvansky1f343fa2018-05-22 20:27:36 +00002749 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002750 // If the length is 0 we don't know how long it is and so we can't
2751 // remove the check.
2752 if (Len == 0)
2753 return false;
2754 return ObjSizeCI->getZExtValue() >= Len;
2755 }
2756 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2757 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2758 }
2759 return false;
2760}
2761
Sanjay Pateld707db92015-12-31 16:10:49 +00002762Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2763 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002764 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002765 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2766 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002767 return CI->getArgOperand(0);
2768 }
2769 return nullptr;
2770}
2771
Sanjay Pateld707db92015-12-31 16:10:49 +00002772Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2773 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002774 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002775 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2776 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002777 return CI->getArgOperand(0);
2778 }
2779 return nullptr;
2780}
2781
Sanjay Pateld707db92015-12-31 16:10:49 +00002782Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2783 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002784 // TODO: Try foldMallocMemset() here.
2785
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002786 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2787 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2788 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2789 return CI->getArgOperand(0);
2790 }
2791 return nullptr;
2792}
2793
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002794Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2795 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002796 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002797 Function *Callee = CI->getCalledFunction();
2798 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002799 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002800 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2801 *ObjSize = CI->getArgOperand(2);
2802
2803 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002804 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002805 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002806 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002807 }
2808
2809 // If a) we don't have any length information, or b) we know this will
2810 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2811 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2812 // TODO: It might be nice to get a maximum length out of the possible
2813 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002814 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002815 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002816
David Blaikie65fab6d2015-04-03 21:32:06 +00002817 if (OnlyLowerUnknownSize)
2818 return nullptr;
2819
2820 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002821 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002822 if (Len == 0)
2823 return nullptr;
2824
2825 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2826 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002827 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002828 // If the function was an __stpcpy_chk, and we were able to fold it into
2829 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002830 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002831 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2832 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002833}
2834
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002835Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2836 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002837 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002838 Function *Callee = CI->getCalledFunction();
2839 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002840 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002841 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002842 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002843 return Ret;
2844 }
2845 return nullptr;
2846}
2847
2848Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002849 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2850 // Some clang users checked for _chk libcall availability using:
2851 // __has_builtin(__builtin___memcpy_chk)
2852 // When compiling with -fno-builtin, this is always true.
2853 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2854 // end up with fortified libcalls, which isn't acceptable in a freestanding
2855 // environment which only provides their non-fortified counterparts.
2856 //
2857 // Until we change clang and/or teach external users to check for availability
2858 // differently, disregard the "nobuiltin" attribute and TLI::has.
2859 //
2860 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002861
David L. Jonesd21529f2017-01-23 23:16:46 +00002862 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002863 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002864
2865 SmallVector<OperandBundleDef, 2> OpBundles;
2866 CI->getOperandBundlesAsDefs(OpBundles);
2867 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002868 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002869
Ahmed Bougachad765a822016-04-27 19:04:35 +00002870 // First, check that this is a known library functions and that the prototype
2871 // is correct.
2872 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002873 return nullptr;
2874
2875 // We never change the calling convention.
2876 if (!ignoreCallingConv(Func) && !isCallingConvC)
2877 return nullptr;
2878
2879 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002880 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002881 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002882 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002883 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002884 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002885 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002886 case LibFunc_stpcpy_chk:
2887 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002888 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002889 case LibFunc_stpncpy_chk:
2890 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002891 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002892 default:
2893 break;
2894 }
2895 return nullptr;
2896}
2897
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002898FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2899 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Sanjay Patel4b969352018-05-22 23:29:40 +00002900 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}