blob: c0957c11719ff6ae2025e291f733b527944e0738 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Meador Ingedf796f82012-10-13 16:45:24 +00006//
7//===----------------------------------------------------------------------===//
8//
Craig Topper2915bc02018-03-01 20:05:09 +00009// This file implements the library calls simplifier. It does not implement
10// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Evandro Menezes2123ea72018-08-30 19:04:51 +000015#include "llvm/ADT/APSInt.h"
Meador Inge20255ef2013-03-12 00:08:29 +000016#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000017#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000018#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000019#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000020#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000022#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000023#include "llvm/Analysis/ValueTracking.h"
David Bolvanskyca22d422018-05-16 11:39:52 +000024#include "llvm/Analysis/CaptureTracking.h"
David Bolvansky909889b2018-08-10 04:32:54 +000025#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000029#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000033#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000034#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000035#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036#include "llvm/Transforms/Utils/BuildLibCalls.h"
37
38using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000039using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000040
Hal Finkel66cd3f12013-11-17 02:06:35 +000041static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000042 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
46
47
Meador Ingedf796f82012-10-13 16:45:24 +000048//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000049// Helper Functions
50//===----------------------------------------------------------------------===//
51
David L. Jonesd21529f2017-01-23 23:16:46 +000052static bool ignoreCallingConv(LibFunc Func) {
53 return Func == LibFunc_abs || Func == LibFunc_labs ||
54 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000055}
56
Sam Parker214f7bf2016-09-13 12:10:14 +000057static bool isCallingConvCCompatible(CallInst *CI) {
58 switch(CI->getCallingConv()) {
59 default:
60 return false;
61 case llvm::CallingConv::C:
62 return true;
63 case llvm::CallingConv::ARM_APCS:
64 case llvm::CallingConv::ARM_AAPCS:
65 case llvm::CallingConv::ARM_AAPCS_VFP: {
66
67 // The iOS ABI diverges from the standard in some cases, so for now don't
68 // try to simplify those calls.
69 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
70 return false;
71
72 auto *FuncTy = CI->getFunctionType();
73
74 if (!FuncTy->getReturnType()->isPointerTy() &&
75 !FuncTy->getReturnType()->isIntegerTy() &&
76 !FuncTy->getReturnType()->isVoidTy())
77 return false;
78
79 for (auto Param : FuncTy->params()) {
80 if (!Param->isPointerTy() && !Param->isIntegerTy())
81 return false;
82 }
83 return true;
84 }
85 }
86 return false;
87}
88
Sanjay Pateld707db92015-12-31 16:10:49 +000089/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000090static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000091 for (User *U : V->users()) {
92 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000093 if (IC->isEquality() && IC->getOperand(1) == With)
94 continue;
95 // Unknown instruction.
96 return false;
97 }
98 return true;
99}
100
Meador Inge08ca1152012-11-26 20:37:20 +0000101static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000102 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000103 return OI->getType()->isFloatingPointTy();
104 });
Meador Inge08ca1152012-11-26 20:37:20 +0000105}
106
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000107static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
108 if (Base < 2 || Base > 36)
109 // handle special zero base
110 if (Base != 0)
111 return nullptr;
112
113 char *End;
114 std::string nptr = Str.str();
115 errno = 0;
116 long long int Result = strtoll(nptr.c_str(), &End, Base);
117 if (errno)
118 return nullptr;
119
120 // if we assume all possible target locales are ASCII supersets,
121 // then if strtoll successfully parses a number on the host,
122 // it will also successfully parse the same way on the target
123 if (*End != '\0')
124 return nullptr;
125
126 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
127 return nullptr;
128
129 return ConstantInt::get(CI->getType(), Result);
130}
131
David Bolvanskyca22d422018-05-16 11:39:52 +0000132static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
133 const TargetLibraryInfo *TLI) {
134 CallInst *FOpen = dyn_cast<CallInst>(File);
135 if (!FOpen)
136 return false;
137
138 Function *InnerCallee = FOpen->getCalledFunction();
139 if (!InnerCallee)
140 return false;
141
142 LibFunc Func;
143 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
144 Func != LibFunc_fopen)
145 return false;
146
David Bolvansky7c7760d2018-10-16 21:18:31 +0000147 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
David Bolvanskyca22d422018-05-16 11:39:52 +0000148 if (PointerMayBeCaptured(File, true, true))
149 return false;
150
151 return true;
152}
153
David Bolvansky909889b2018-08-10 04:32:54 +0000154static bool isOnlyUsedInComparisonWithZero(Value *V) {
155 for (User *U : V->users()) {
156 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
157 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
158 if (C->isNullValue())
159 continue;
160 // Unknown instruction.
161 return false;
162 }
163 return true;
164}
165
166static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
167 const DataLayout &DL) {
168 if (!isOnlyUsedInComparisonWithZero(CI))
169 return false;
170
171 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
172 return false;
Matt Morehousee62fc3d2018-09-19 19:37:24 +0000173
174 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
175 return false;
176
David Bolvansky909889b2018-08-10 04:32:54 +0000177 return true;
178}
179
Meador Inged589ac62012-10-31 03:33:06 +0000180//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000181// String and Memory Library Call Optimizations
182//===----------------------------------------------------------------------===//
183
Chris Bienemanad070d02014-09-17 20:55:46 +0000184Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000185 // Extract some information from the instruction
186 Value *Dst = CI->getArgOperand(0);
187 Value *Src = CI->getArgOperand(1);
188
189 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000190 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000191 if (Len == 0)
192 return nullptr;
193 --Len; // Unbias length.
194
195 // Handle the simple, do-nothing case: strcat(x, "") -> x
196 if (Len == 0)
197 return Dst;
198
Chris Bienemanad070d02014-09-17 20:55:46 +0000199 return emitStrLenMemCpy(Src, Dst, Len, B);
200}
201
202Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
203 IRBuilder<> &B) {
204 // We need to find the end of the destination string. That's where the
205 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000206 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 if (!DstLen)
208 return nullptr;
209
210 // Now that we have the destination's length, we must index into the
211 // destination's pointer to get the actual memcpy destination (end of
212 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000213 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000214
215 // We have enough information to now generate the memcpy call to do the
216 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000217 B.CreateMemCpy(CpyDst, 1, Src, 1,
218 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000219 return Dst;
220}
221
222Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000223 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000224 Value *Dst = CI->getArgOperand(0);
225 Value *Src = CI->getArgOperand(1);
226 uint64_t Len;
227
Sanjay Pateld707db92015-12-31 16:10:49 +0000228 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000229 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
230 Len = LengthArg->getZExtValue();
231 else
232 return nullptr;
233
234 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000235 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000236 if (SrcLen == 0)
237 return nullptr;
238 --SrcLen; // Unbias length.
239
240 // Handle the simple, do-nothing cases:
241 // strncat(x, "", c) -> x
242 // strncat(x, c, 0) -> x
243 if (SrcLen == 0 || Len == 0)
244 return Dst;
245
Sanjay Pateld707db92015-12-31 16:10:49 +0000246 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000247 if (Len < SrcLen)
248 return nullptr;
249
250 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000251 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000252 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
253}
254
255Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
256 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000257 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000258 Value *SrcStr = CI->getArgOperand(0);
259
260 // If the second operand is non-constant, see if we can compute the length
261 // of the input string and turn this into memchr.
262 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
263 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000264 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000265 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
266 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000267
Sanjay Pateld3112a52016-01-19 19:46:10 +0000268 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000269 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
270 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000271 }
272
Chris Bienemanad070d02014-09-17 20:55:46 +0000273 // Otherwise, the character is a constant, see if the first argument is
274 // a string literal. If so, we can constant fold.
275 StringRef Str;
276 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000277 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000278 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000279 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000280 return nullptr;
281 }
282
283 // Compute the offset, make sure to handle the case when we're searching for
284 // zero (a weird way to spell strlen).
285 size_t I = (0xFF & CharC->getSExtValue()) == 0
286 ? Str.size()
287 : Str.find(CharC->getSExtValue());
288 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
289 return Constant::getNullValue(CI->getType());
290
291 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000292 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000293}
294
295Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000296 Value *SrcStr = CI->getArgOperand(0);
297 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
298
299 // Cannot fold anything if we're not looking for a constant.
300 if (!CharC)
301 return nullptr;
302
303 StringRef Str;
304 if (!getConstantStringInfo(SrcStr, Str)) {
305 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000307 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000308 return nullptr;
309 }
310
311 // Compute the offset.
312 size_t I = (0xFF & CharC->getSExtValue()) == 0
313 ? Str.size()
314 : Str.rfind(CharC->getSExtValue());
315 if (I == StringRef::npos) // Didn't find the char. Return null.
316 return Constant::getNullValue(CI->getType());
317
318 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000319 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000320}
321
322Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000323 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
324 if (Str1P == Str2P) // strcmp(x,x) -> 0
325 return ConstantInt::get(CI->getType(), 0);
326
327 StringRef Str1, Str2;
328 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
329 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
330
331 // strcmp(x, y) -> cnst (if both x and y are constant strings)
332 if (HasStr1 && HasStr2)
333 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
334
335 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
336 return B.CreateNeg(
337 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
338
339 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
340 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
341
342 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000343 uint64_t Len1 = GetStringLength(Str1P);
344 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000345 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000346 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000348 std::min(Len1, Len2)),
349 B, DL, TLI);
350 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000351
David Bolvansky909889b2018-08-10 04:32:54 +0000352 // strcmp to memcmp
353 if (!HasStr1 && HasStr2) {
354 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
355 return emitMemCmp(
356 Str1P, Str2P,
357 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
358 TLI);
359 } else if (HasStr1 && !HasStr2) {
360 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
361 return emitMemCmp(
362 Str1P, Str2P,
363 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
364 TLI);
365 }
366
Chris Bienemanad070d02014-09-17 20:55:46 +0000367 return nullptr;
368}
369
370Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000371 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
372 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
373 return ConstantInt::get(CI->getType(), 0);
374
375 // Get the length argument if it is constant.
376 uint64_t Length;
377 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
378 Length = LengthArg->getZExtValue();
379 else
380 return nullptr;
381
382 if (Length == 0) // strncmp(x,y,0) -> 0
383 return ConstantInt::get(CI->getType(), 0);
384
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000385 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000386 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000387
388 StringRef Str1, Str2;
389 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
390 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
391
392 // strncmp(x, y) -> cnst (if both x and y are constant strings)
393 if (HasStr1 && HasStr2) {
394 StringRef SubStr1 = Str1.substr(0, Length);
395 StringRef SubStr2 = Str2.substr(0, Length);
396 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
397 }
398
399 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
400 return B.CreateNeg(
401 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
402
403 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
404 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
405
David Bolvansky909889b2018-08-10 04:32:54 +0000406 uint64_t Len1 = GetStringLength(Str1P);
407 uint64_t Len2 = GetStringLength(Str2P);
408
409 // strncmp to memcmp
410 if (!HasStr1 && HasStr2) {
411 Len2 = std::min(Len2, Length);
412 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
413 return emitMemCmp(
414 Str1P, Str2P,
415 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
416 TLI);
417 } else if (HasStr1 && !HasStr2) {
418 Len1 = std::min(Len1, Length);
419 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
420 return emitMemCmp(
421 Str1P, Str2P,
422 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
423 TLI);
424 }
425
Chris Bienemanad070d02014-09-17 20:55:46 +0000426 return nullptr;
427}
428
429Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000430 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
431 if (Dst == Src) // strcpy(x,x) -> x
432 return Src;
433
Chris Bienemanad070d02014-09-17 20:55:46 +0000434 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000435 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000436 if (Len == 0)
437 return nullptr;
438
439 // We have enough information to now generate the memcpy call to do the
440 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000441 B.CreateMemCpy(Dst, 1, Src, 1,
442 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000443 return Dst;
444}
445
446Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
447 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000448 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
449 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000450 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000451 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000452 }
453
454 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000455 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000456 if (Len == 0)
457 return nullptr;
458
Davide Italianob7487e62015-11-02 23:07:14 +0000459 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000460 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000461 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
462 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000463
464 // We have enough information to now generate the memcpy call to do the
465 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000466 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000467 return DstEnd;
468}
469
470Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
471 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000472 Value *Dst = CI->getArgOperand(0);
473 Value *Src = CI->getArgOperand(1);
474 Value *LenOp = CI->getArgOperand(2);
475
476 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000477 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000478 if (SrcLen == 0)
479 return nullptr;
480 --SrcLen;
481
482 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000483 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000484 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000485 return Dst;
486 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000487
Chris Bienemanad070d02014-09-17 20:55:46 +0000488 uint64_t Len;
489 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
490 Len = LengthArg->getZExtValue();
491 else
492 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000493
Chris Bienemanad070d02014-09-17 20:55:46 +0000494 if (Len == 0)
495 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000496
Chris Bienemanad070d02014-09-17 20:55:46 +0000497 // Let strncpy handle the zero padding
498 if (Len > SrcLen + 1)
499 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000500
Davide Italianob7487e62015-11-02 23:07:14 +0000501 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000502 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
503 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 return Dst;
506}
Meador Inge7fb2f732012-10-13 16:45:32 +0000507
Matthias Braun50ec0b52017-05-19 22:37:09 +0000508Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
509 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000510 Value *Src = CI->getArgOperand(0);
511
512 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000513 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000514 return ConstantInt::get(CI->getType(), Len - 1);
515
David L Kreitzer752c1442016-04-13 14:31:06 +0000516 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000517 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000518 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000519 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000520 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000521 // subtraction. This will make the optimization more complex, and it's not
522 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000523 // very uncommon.
524 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000525 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000526 return nullptr;
527
Matthias Braun50ec0b52017-05-19 22:37:09 +0000528 ConstantDataArraySlice Slice;
529 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
530 uint64_t NullTermIdx;
531 if (Slice.Array == nullptr) {
532 NullTermIdx = 0;
533 } else {
534 NullTermIdx = ~((uint64_t)0);
535 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
536 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
537 NullTermIdx = I;
538 break;
539 }
540 }
541 // If the string does not have '\0', leave it to strlen to compute
542 // its length.
543 if (NullTermIdx == ~((uint64_t)0))
544 return nullptr;
545 }
546
David L Kreitzer752c1442016-04-13 14:31:06 +0000547 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000548 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000549 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000550 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000551 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
552
Matthias Braun50ec0b52017-05-19 22:37:09 +0000553 // KnownZero's bits are flipped, so zeros in KnownZero now represent
554 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000555 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000556 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000557 // unsigned-less-than NullTermIdx.
558 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000559 // If Offset is not provably in the range [0, NullTermIdx], we can still
560 // optimize if we can prove that the program has undefined behavior when
561 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000562 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000563 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000564 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000565 NullTermIdx == ArrSize - 1)) {
566 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
567 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000568 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000569 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000570 }
571
572 return nullptr;
573 }
574
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 // strlen(x?"foo":"bars") --> x ? 3 : 4
576 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000577 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
578 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000579 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000580 ORE.emit([&]() {
581 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
582 << "folded strlen(select) to select of constants";
583 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000584 return B.CreateSelect(SI->getCondition(),
585 ConstantInt::get(CI->getType(), LenTrue - 1),
586 ConstantInt::get(CI->getType(), LenFalse - 1));
587 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000588 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000589
Chris Bienemanad070d02014-09-17 20:55:46 +0000590 // strlen(x) != 0 --> *x != 0
591 // strlen(x) == 0 --> *x == 0
592 if (isOnlyUsedInZeroEqualityComparison(CI))
593 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000594
Chris Bienemanad070d02014-09-17 20:55:46 +0000595 return nullptr;
596}
Meador Inge17418502012-10-13 16:45:37 +0000597
Matthias Braun50ec0b52017-05-19 22:37:09 +0000598Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
599 return optimizeStringLength(CI, B, 8);
600}
601
602Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000603 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000604 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000605 // We cannot perform this optimization without wchar_size metadata.
606 if (WCharSize == 0)
607 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000608
609 return optimizeStringLength(CI, B, WCharSize);
610}
611
Chris Bienemanad070d02014-09-17 20:55:46 +0000612Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000613 StringRef S1, S2;
614 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
615 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000616
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000617 // strpbrk(s, "") -> nullptr
618 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000619 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
620 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000621
Chris Bienemanad070d02014-09-17 20:55:46 +0000622 // Constant folding.
623 if (HasS1 && HasS2) {
624 size_t I = S1.find_first_of(S2);
625 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000626 return Constant::getNullValue(CI->getType());
627
Sanjay Pateld707db92015-12-31 16:10:49 +0000628 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
629 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000630 }
Meador Inge17418502012-10-13 16:45:37 +0000631
Chris Bienemanad070d02014-09-17 20:55:46 +0000632 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000633 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000634 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000635
636 return nullptr;
637}
638
639Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000640 Value *EndPtr = CI->getArgOperand(1);
641 if (isa<ConstantPointerNull>(EndPtr)) {
642 // With a null EndPtr, this function won't capture the main argument.
643 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000644 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000645 }
646
647 return nullptr;
648}
649
650Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000651 StringRef S1, S2;
652 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
653 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
654
655 // strspn(s, "") -> 0
656 // strspn("", s) -> 0
657 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
658 return Constant::getNullValue(CI->getType());
659
660 // Constant folding.
661 if (HasS1 && HasS2) {
662 size_t Pos = S1.find_first_not_of(S2);
663 if (Pos == StringRef::npos)
664 Pos = S1.size();
665 return ConstantInt::get(CI->getType(), Pos);
666 }
667
668 return nullptr;
669}
670
671Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000672 StringRef S1, S2;
673 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
674 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
675
676 // strcspn("", s) -> 0
677 if (HasS1 && S1.empty())
678 return Constant::getNullValue(CI->getType());
679
680 // Constant folding.
681 if (HasS1 && HasS2) {
682 size_t Pos = S1.find_first_of(S2);
683 if (Pos == StringRef::npos)
684 Pos = S1.size();
685 return ConstantInt::get(CI->getType(), Pos);
686 }
687
688 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000689 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000690 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000691
692 return nullptr;
693}
694
695Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000696 // fold strstr(x, x) -> x.
697 if (CI->getArgOperand(0) == CI->getArgOperand(1))
698 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
699
700 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000702 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000703 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000704 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000705 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 StrLen, B, DL, TLI);
707 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000708 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000709 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
710 ICmpInst *Old = cast<ICmpInst>(*UI++);
711 Value *Cmp =
712 B.CreateICmp(Old->getPredicate(), StrNCmp,
713 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
714 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000715 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000716 return CI;
717 }
Meador Inge17418502012-10-13 16:45:37 +0000718
Chris Bienemanad070d02014-09-17 20:55:46 +0000719 // See if either input string is a constant string.
720 StringRef SearchStr, ToFindStr;
721 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
722 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
723
724 // fold strstr(x, "") -> x.
725 if (HasStr2 && ToFindStr.empty())
726 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
727
728 // If both strings are known, constant fold it.
729 if (HasStr1 && HasStr2) {
730 size_t Offset = SearchStr.find(ToFindStr);
731
732 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000733 return Constant::getNullValue(CI->getType());
734
Chris Bienemanad070d02014-09-17 20:55:46 +0000735 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000736 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000737 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
738 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000739 }
Meador Inge17418502012-10-13 16:45:37 +0000740
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 // fold strstr(x, "y") -> strchr(x, 'y').
742 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000743 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000744 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
745 }
746 return nullptr;
747}
Meador Inge40b6fac2012-10-15 03:47:37 +0000748
Benjamin Kramer691363e2015-03-21 15:36:21 +0000749Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000750 Value *SrcStr = CI->getArgOperand(0);
751 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
752 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
753
754 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000755 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000756 return Constant::getNullValue(CI->getType());
757
Benjamin Kramer7857d722015-03-21 21:09:33 +0000758 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000759 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000760 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000761 return nullptr;
762
763 // Truncate the string to LenC. If Str is smaller than LenC we will still only
764 // scan the string, as reading past the end of it is undefined and we can just
765 // return null if we don't find the char.
766 Str = Str.substr(0, LenC->getZExtValue());
767
Benjamin Kramer7857d722015-03-21 21:09:33 +0000768 // If the char is variable but the input str and length are not we can turn
769 // this memchr call into a simple bit field test. Of course this only works
770 // when the return value is only checked against null.
771 //
772 // It would be really nice to reuse switch lowering here but we can't change
773 // the CFG at this point.
774 //
775 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
776 // after bounds check.
777 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000778 unsigned char Max =
779 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
780 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000781
782 // Make sure the bit field we're about to create fits in a register on the
783 // target.
784 // FIXME: On a 64 bit architecture this prevents us from using the
785 // interesting range of alpha ascii chars. We could do better by emitting
786 // two bitfields or shifting the range by 64 if no lower chars are used.
787 if (!DL.fitsInLegalInteger(Max + 1))
788 return nullptr;
789
790 // For the bit field use a power-of-2 type with at least 8 bits to avoid
791 // creating unnecessary illegal types.
792 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
793
794 // Now build the bit field.
795 APInt Bitfield(Width, 0);
796 for (char C : Str)
797 Bitfield.setBit((unsigned char)C);
798 Value *BitfieldC = B.getInt(Bitfield);
799
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000800 // Adjust width of "C" to the bitfield width, then mask off the high bits.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000801 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000802 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
803
804 // First check that the bit field access is within bounds.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000805 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
806 "memchr.bounds");
807
808 // Create code that checks if the given bit is set in the field.
809 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
810 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
811
812 // Finally merge both checks and cast to pointer type. The inttoptr
813 // implicitly zexts the i1 to intptr type.
814 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
815 }
816
817 // Check if all arguments are constants. If so, we can constant fold.
818 if (!CharC)
819 return nullptr;
820
Benjamin Kramer691363e2015-03-21 15:36:21 +0000821 // Compute the offset.
822 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
823 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
824 return Constant::getNullValue(CI->getType());
825
826 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000827 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000828}
829
Chris Bienemanad070d02014-09-17 20:55:46 +0000830Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000831 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000832
Chris Bienemanad070d02014-09-17 20:55:46 +0000833 if (LHS == RHS) // memcmp(s,s,x) -> 0
834 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000835
Chris Bienemanad070d02014-09-17 20:55:46 +0000836 // Make sure we have a constant length.
837 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
838 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000839 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000840
Sanjay Patel70db4242017-06-09 14:22:03 +0000841 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000842 if (Len == 0) // memcmp(s1,s2,0) -> 0
843 return Constant::getNullValue(CI->getType());
844
845 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
846 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000847 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000848 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000849 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000850 CI->getType(), "rhsv");
851 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000852 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000853
Chad Rosierdc655322015-08-28 18:30:18 +0000854 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000855 // TODO: The case where both inputs are constants does not need to be limited
856 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000857 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000858 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
859 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
860
Sanjay Patel82ec8722017-08-21 19:13:14 +0000861 // First, see if we can fold either argument to a constant.
862 Value *LHSV = nullptr;
863 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
864 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
865 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
866 }
867 Value *RHSV = nullptr;
868 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
869 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
870 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
871 }
Chad Rosierdc655322015-08-28 18:30:18 +0000872
Sanjay Patel82ec8722017-08-21 19:13:14 +0000873 // Don't generate unaligned loads. If either source is constant data,
874 // alignment doesn't matter for that source because there is no load.
875 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
876 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
877 if (!LHSV) {
878 Type *LHSPtrTy =
879 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
880 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
881 }
882 if (!RHSV) {
883 Type *RHSPtrTy =
884 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
885 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
886 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000887 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000888 }
Chad Rosierdc655322015-08-28 18:30:18 +0000889 }
890
Sanjay Patel82ec8722017-08-21 19:13:14 +0000891 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
892 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000893 StringRef LHSStr, RHSStr;
894 if (getConstantStringInfo(LHS, LHSStr) &&
895 getConstantStringInfo(RHS, RHSStr)) {
896 // Make sure we're not reading out-of-bounds memory.
897 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000898 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000899 // Fold the memcmp and normalize the result. This way we get consistent
900 // results across multiple platforms.
901 uint64_t Ret = 0;
902 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
903 if (Cmp < 0)
904 Ret = -1;
905 else if (Cmp > 0)
906 Ret = 1;
907 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000908 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000909
Chris Bienemanad070d02014-09-17 20:55:46 +0000910 return nullptr;
911}
Meador Inge9a6a1902012-10-31 00:20:56 +0000912
Chris Bienemanad070d02014-09-17 20:55:46 +0000913Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000914 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
915 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
916 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000917 return CI->getArgOperand(0);
918}
Meador Inge05a625a2012-10-31 14:58:26 +0000919
Chris Bienemanad070d02014-09-17 20:55:46 +0000920Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000921 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
922 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
923 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000924 return CI->getArgOperand(0);
925}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000926
Sanjay Patel980b2802016-01-26 16:17:24 +0000927/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +0000928Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000929 // This has to be a memset of zeros (bzero).
930 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
931 if (!FillValue || FillValue->getZExtValue() != 0)
932 return nullptr;
933
934 // TODO: We should handle the case where the malloc has more than one use.
935 // This is necessary to optimize common patterns such as when the result of
936 // the malloc is checked against null or when a memset intrinsic is used in
937 // place of a memset library call.
938 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
939 if (!Malloc || !Malloc->hasOneUse())
940 return nullptr;
941
942 // Is the inner call really malloc()?
943 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000944 if (!InnerCallee)
945 return nullptr;
946
David L. Jonesd21529f2017-01-23 23:16:46 +0000947 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +0000948 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000949 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000950 return nullptr;
951
Sanjay Patel980b2802016-01-26 16:17:24 +0000952 // The memset must cover the same number of bytes that are malloc'd.
953 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
954 return nullptr;
955
956 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +0000957 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +0000958 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
959 const DataLayout &DL = Malloc->getModule()->getDataLayout();
960 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
961 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
962 Malloc->getArgOperand(0), Malloc->getAttributes(),
Amara Emerson54f60252018-10-11 14:51:11 +0000963 B, *TLI);
Sanjay Patel980b2802016-01-26 16:17:24 +0000964 if (!Calloc)
965 return nullptr;
966
967 Malloc->replaceAllUsesWith(Calloc);
Amara Emerson54f60252018-10-11 14:51:11 +0000968 eraseFromParent(Malloc);
Sanjay Patel980b2802016-01-26 16:17:24 +0000969
970 return Calloc;
971}
972
Chris Bienemanad070d02014-09-17 20:55:46 +0000973Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Amara Emerson54f60252018-10-11 14:51:11 +0000974 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +0000975 return Calloc;
976
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000977 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000978 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
979 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
980 return CI->getArgOperand(0);
981}
Meador Inged4825782012-11-11 06:49:03 +0000982
Sanjay Patelb2ab3f22018-04-18 14:21:31 +0000983Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
984 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
985 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
986
987 return nullptr;
988}
989
Meador Inge193e0352012-11-13 04:16:17 +0000990//===----------------------------------------------------------------------===//
991// Math Library Optimizations
992//===----------------------------------------------------------------------===//
993
Evandro Menezes5aa217a2018-08-03 17:50:16 +0000994// Replace a libcall \p CI with a call to intrinsic \p IID
995static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
996 // Propagate fast-math flags from the existing call to the new call.
997 IRBuilder<>::FastMathFlagGuard Guard(B);
998 B.setFastMathFlags(CI->getFastMathFlags());
999
1000 Module *M = CI->getModule();
1001 Value *V = CI->getArgOperand(0);
1002 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1003 CallInst *NewCall = B.CreateCall(F, V);
1004 NewCall->takeName(CI);
1005 return NewCall;
1006}
1007
Matthias Braund34e4d22014-12-03 21:46:33 +00001008/// Return a variant of Val with float type.
1009/// Currently this works in two cases: If Val is an FPExtension of a float
1010/// value to something bigger, simply return the operand.
1011/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1012/// loss of precision do so.
1013static Value *valueHasFloatPrecision(Value *Val) {
1014 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1015 Value *Op = Cast->getOperand(0);
1016 if (Op->getType()->isFloatTy())
1017 return Op;
1018 }
1019 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1020 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001021 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001022 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001023 &losesInfo);
1024 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001025 return ConstantFP::get(Const->getContext(), F);
1026 }
1027 return nullptr;
1028}
1029
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001030/// Shrink double -> float functions.
1031static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001032 bool isBinary, bool isPrecise = false) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001033 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00001034 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001035
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001036 // If not all the uses of the function are converted to float, then bail out.
1037 // This matters if the precision of the result is more important than the
1038 // precision of the arguments.
1039 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001040 for (User *U : CI->users()) {
1041 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1042 if (!Cast || !Cast->getType()->isFloatTy())
1043 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001044 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001045
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001046 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1047 Value *V[2];
1048 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1049 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1050 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001051 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001052
Andrew Ng1606fc02017-04-25 12:36:14 +00001053 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001054 // same name as the float version of this call, otherwise the result is an
1055 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001056 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001057 // float expf(float val) { return (float) exp((double) val); }
1058 Function *CalleeFn = CI->getCalledFunction();
1059 StringRef CalleeNm = CalleeFn->getName();
1060 AttributeList CalleeAt = CalleeFn->getAttributes();
1061 if (CalleeFn && !CalleeFn->isIntrinsic()) {
1062 const Function *Fn = CI->getFunction();
1063 StringRef FnName = Fn->getName();
1064 if (FnName.back() == 'f' &&
1065 FnName.size() == (CalleeNm.size() + 1) &&
1066 FnName.startswith(CalleeNm))
Andrew Ng1606fc02017-04-25 12:36:14 +00001067 return nullptr;
1068 }
1069
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001070 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001071 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001072 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001073
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001074 // g((double) float) -> (double) gf(float)
1075 Value *R;
1076 if (CalleeFn->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001077 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001078 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1079 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1080 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Patel848309d2014-10-23 21:52:45 +00001081 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001082 else
1083 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1084 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
Sanjay Patel848309d2014-10-23 21:52:45 +00001085
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001086 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001087}
Meador Inge193e0352012-11-13 04:16:17 +00001088
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001089/// Shrink double -> float for unary functions.
1090static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001091 bool isPrecise = false) {
1092 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001093}
1094
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001095/// Shrink double -> float for binary functions.
1096static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001097 bool isPrecise = false) {
1098 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001099}
1100
Hal Finkel2ff24732017-12-16 01:26:25 +00001101// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1102Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1103 if (!CI->isFast())
1104 return nullptr;
1105
1106 // Propagate fast-math flags from the existing call to new instructions.
1107 IRBuilder<>::FastMathFlagGuard Guard(B);
1108 B.setFastMathFlags(CI->getFastMathFlags());
1109
1110 Value *Real, *Imag;
1111 if (CI->getNumArgOperands() == 1) {
1112 Value *Op = CI->getArgOperand(0);
1113 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1114 Real = B.CreateExtractValue(Op, 0, "real");
1115 Imag = B.CreateExtractValue(Op, 1, "imag");
1116 } else {
1117 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1118 Real = CI->getArgOperand(0);
1119 Imag = CI->getArgOperand(1);
1120 }
1121
1122 Value *RealReal = B.CreateFMul(Real, Real);
1123 Value *ImagImag = B.CreateFMul(Imag, Imag);
1124
1125 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1126 CI->getType());
1127 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1128}
1129
Sanjay Patele45a83d2018-08-13 19:24:41 +00001130static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1131 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001132 if (!isa<FPMathOperator>(Call))
1133 return nullptr;
1134
1135 IRBuilder<>::FastMathFlagGuard Guard(B);
1136 B.setFastMathFlags(Call->getFastMathFlags());
1137
Sanjay Patele45a83d2018-08-13 19:24:41 +00001138 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001139 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001140 switch (Func) {
1141 case LibFunc_sin:
1142 case LibFunc_sinf:
1143 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001144 case LibFunc_tan:
1145 case LibFunc_tanf:
1146 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001147 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001148 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001149 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001150 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001151 break;
1152 case LibFunc_cos:
1153 case LibFunc_cosf:
1154 case LibFunc_cosl:
1155 // cos(-X) --> cos(X)
1156 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1157 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1158 break;
1159 default:
1160 break;
1161 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001162 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001163}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001164
Weiming Zhao82130722015-12-04 22:00:47 +00001165static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1166 // Multiplications calculated using Addition Chains.
1167 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1168
1169 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1170
1171 if (InnerChain[Exp])
1172 return InnerChain[Exp];
1173
1174 static const unsigned AddChain[33][2] = {
1175 {0, 0}, // Unused.
1176 {0, 0}, // Unused (base case = pow1).
1177 {1, 1}, // Unused (pre-computed).
1178 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1179 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1180 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1181 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1182 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1183 };
1184
1185 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1186 getPow(InnerChain, AddChain[Exp][1], B));
1187 return InnerChain[Exp];
1188}
1189
Evandro Menezes4b390102018-08-17 17:59:53 +00001190/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001191/// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001192Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1193 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1194 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1195 Module *Mod = Pow->getModule();
1196 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001197 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001198
1199 // Evaluate special cases related to a nested function as the base.
1200
1201 // pow(exp(x), y) -> exp(x * y)
1202 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001203 // If exp{,2}() is used only once, it is better to fold two transcendental
1204 // math functions into one. If used again, exp{,2}() would still have to be
1205 // called with the original argument, then keep both original transcendental
1206 // functions. However, this transformation is only safe with fully relaxed
1207 // math semantics, since, besides rounding differences, it changes overflow
1208 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001209 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1210 // Whereas:
1211 // exp(1000 * 0.001) = exp(1)
1212 // TODO: Loosen the requirement for fully relaxed math semantics.
1213 // TODO: Handle exp10() when more targets have it available.
1214 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001215 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001216 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001217
Evandro Menezes4b390102018-08-17 17:59:53 +00001218 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001219 if (CalleeFn &&
1220 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1221 StringRef ExpName;
1222 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001223 Value *ExpFn;
Mikael Holmene3605d02018-10-18 06:27:53 +00001224 LibFunc LibFnFloat;
1225 LibFunc LibFnDouble;
1226 LibFunc LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001227
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001228 switch (LibFn) {
1229 default:
1230 return nullptr;
1231 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001232 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001233 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001234 LibFnFloat = LibFunc_expf;
1235 LibFnDouble = LibFunc_exp;
1236 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001237 break;
1238 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001239 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001240 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001241 LibFnFloat = LibFunc_exp2f;
1242 LibFnDouble = LibFunc_exp2;
1243 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001244 break;
1245 }
1246
Evandro Menezes253991c2018-08-27 22:11:15 +00001247 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001248 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001249 ExpFn = BaseFn->doesNotAccessMemory()
1250 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1251 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001252 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1253 LibFnLongDouble, B,
1254 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001255
1256 // Since the new exp{,2}() is different from the original one, dead code
1257 // elimination cannot be trusted to remove it, since it may have side
1258 // effects (e.g., errno). When the only consumer for the original
1259 // exp{,2}() is pow(), then it has to be explicitly erased.
1260 BaseFn->replaceAllUsesWith(ExpFn);
Amara Emerson54f60252018-10-11 14:51:11 +00001261 eraseFromParent(BaseFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001262
1263 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001264 }
1265 }
1266
1267 // Evaluate special cases related to a constant base.
1268
Evandro Menezes2123ea72018-08-30 19:04:51 +00001269 const APFloat *BaseF;
1270 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1271 return nullptr;
1272
1273 // pow(2.0 ** n, x) -> exp2(n * x)
1274 if (hasUnaryFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1275 APFloat BaseR = APFloat(1.0);
1276 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1277 BaseR = BaseR / *BaseF;
1278 bool IsInteger = BaseF->isInteger(),
1279 IsReciprocal = BaseR.isInteger();
1280 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1281 APSInt NI(64, false);
1282 if ((IsInteger || IsReciprocal) &&
1283 !NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) &&
1284 NI > 1 && NI.isPowerOf2()) {
1285 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1286 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1287 if (Pow->doesNotAccessMemory())
1288 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1289 FMul, "exp2");
1290 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001291 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1292 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001293 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001294 }
1295
1296 // pow(10.0, x) -> exp10(x)
1297 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1298 if (match(Base, m_SpecificFP(10.0)) &&
1299 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001300 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1301 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001302
1303 return nullptr;
1304}
1305
Florian Hahncc9dc592018-09-03 17:37:39 +00001306static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1307 Module *M, IRBuilder<> &B,
1308 const TargetLibraryInfo *TLI) {
1309 // If errno is never set, then use the intrinsic for sqrt().
1310 if (NoErrno) {
1311 Function *SqrtFn =
1312 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1313 return B.CreateCall(SqrtFn, V, "sqrt");
1314 }
1315
1316 // Otherwise, use the libcall for sqrt().
1317 if (hasUnaryFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1318 LibFunc_sqrtl))
1319 // TODO: We also should check that the target can in fact lower the sqrt()
1320 // libcall. We currently have no way to ask this question, so we ask if
1321 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001322 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1323 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001324
1325 return nullptr;
1326}
1327
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001328/// Use square root in place of pow(x, +/-0.5).
1329Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001330 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001331 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1332 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001333 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001334
Evandro Menezesa7d48282018-07-30 16:20:04 +00001335 const APFloat *ExpoF;
1336 if (!match(Expo, m_APFloat(ExpoF)) ||
1337 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1338 return nullptr;
1339
Florian Hahncc9dc592018-09-03 17:37:39 +00001340 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1341 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001342 return nullptr;
1343
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001344 // Handle signed zero base by expanding to fabs(sqrt(x)).
1345 if (!Pow->hasNoSignedZeros()) {
1346 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1347 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1348 }
1349
1350 // Handle non finite base by expanding to
1351 // (x == -infinity ? +infinity : sqrt(x)).
1352 if (!Pow->hasNoInfs()) {
1353 Value *PosInf = ConstantFP::getInfinity(Ty),
1354 *NegInf = ConstantFP::getInfinity(Ty, true);
1355 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1356 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1357 }
1358
Evandro Menezes61e4e402018-07-31 22:11:02 +00001359 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001360 if (ExpoF->isNegative())
1361 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001362
1363 return Sqrt;
1364}
1365
Evandro Menezesa7d48282018-07-30 16:20:04 +00001366Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1367 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1368 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001369 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001370 Type *Ty = Pow->getType();
1371 Value *Shrunk = nullptr;
1372 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001373
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001374 // Bail out if simplifying libcalls to pow() is disabled.
1375 if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1376 return nullptr;
1377
Evandro Menezes61e4e402018-07-31 22:11:02 +00001378 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001379 IRBuilder<>::FastMathFlagGuard Guard(B);
1380 B.setFastMathFlags(Pow->getFastMathFlags());
1381
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001382 // Shrink pow() to powf() if the arguments are single precision,
1383 // unless the result is expected to be double precision.
1384 if (UnsafeFPShrink &&
1385 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1386 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1387
Evandro Menezesa7d48282018-07-30 16:20:04 +00001388 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001389
1390 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001391 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001392 return Base;
1393
Evandro Menezes4b390102018-08-17 17:59:53 +00001394 if (Value *Exp = replacePowWithExp(Pow, B))
1395 return Exp;
Davide Italianoc8a79132015-11-03 20:32:23 +00001396
Evandro Menezesa7d48282018-07-30 16:20:04 +00001397 // Evaluate special cases related to the exponent.
1398
Evandro Menezesa7d48282018-07-30 16:20:04 +00001399 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001400 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001401 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1402
1403 // pow(x, 0.0) -> 1.0
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001404 if (match(Expo, m_SpecificFP(0.0)))
1405 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001406
1407 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001408 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001409 return Base;
1410
1411 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001412 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001413 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001414
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001415 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1416 return Sqrt;
1417
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001418 // pow(x, n) -> x * x * x * ...
1419 const APFloat *ExpoF;
1420 if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
1421 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001422 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1423 // additional fmul.
1424 // TODO: This whole transformation should be backend specific (e.g. some
1425 // backends might prefer libcalls or the limit for the exponent might
1426 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001427 APFloat LimF(ExpoF->getSemantics(), 33.0),
1428 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001429 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1430 // This transformation applies to integer or integer+0.5 exponents only.
1431 // For integer+0.5, we create a sqrt(Base) call.
1432 Value *Sqrt = nullptr;
1433 if (!ExpoA.isInteger()) {
1434 APFloat Expo2 = ExpoA;
1435 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1436 // is no floating point exception and the result is an integer, then
1437 // ExpoA == integer + 0.5
1438 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1439 return nullptr;
1440
1441 if (!Expo2.isInteger())
1442 return nullptr;
1443
1444 Sqrt =
1445 getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1446 Pow->doesNotAccessMemory(), Pow->getModule(), B, TLI);
1447 }
1448
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001449 // We will memoize intermediate products of the Addition Chain.
1450 Value *InnerChain[33] = {nullptr};
1451 InnerChain[1] = Base;
1452 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001453
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001454 // We cannot readily convert a non-double type (like float) to a double.
1455 // So we first convert it to something which could be converted to double.
1456 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1457 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001458
Florian Hahncc9dc592018-09-03 17:37:39 +00001459 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1460 if (Sqrt)
1461 FMul = B.CreateFMul(FMul, Sqrt);
1462
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001463 // If the exponent is negative, then get the reciprocal.
1464 if (ExpoF->isNegative())
1465 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001466
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001467 return FMul;
1468 }
Weiming Zhao82130722015-12-04 22:00:47 +00001469 }
1470
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001471 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001472}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001473
Chris Bienemanad070d02014-09-17 20:55:46 +00001474Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1475 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001476 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001477 StringRef Name = Callee->getName();
1478 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001479 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001480
Chris Bienemanad070d02014-09-17 20:55:46 +00001481 Value *Op = CI->getArgOperand(0);
1482 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1483 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001484 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001485 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001486 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001487 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001488 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001489
1490 if (TLI->has(LdExp)) {
1491 Value *LdExpArg = nullptr;
1492 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1493 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1494 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1495 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1496 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1497 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1498 }
1499
1500 if (LdExpArg) {
1501 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1502 if (!Op->getType()->isFloatTy())
1503 One = ConstantExpr::getFPExtend(One, Op->getType());
1504
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001505 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001506 Value *NewCallee =
1507 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001508 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001509 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001510 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1511 CI->setCallingConv(F->getCallingConv());
1512
1513 return CI;
1514 }
1515 }
1516 return Ret;
1517}
1518
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001519Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001520 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001521 // If we can shrink the call to a float function rather than a double
1522 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001523 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001524 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1525 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001526 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001527
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001528 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001529 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001530 if (CI->isFast()) {
1531 // If the call is 'fast', then anything we create here will also be 'fast'.
1532 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001533 } else {
1534 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001535 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001536 return nullptr;
1537 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1538 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001539 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001540 // might be impractical."
1541 FMF.setNoSignedZeros();
1542 FMF.setNoNaNs();
1543 }
Sanjay Patela2528152016-01-12 18:03:37 +00001544 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001545
1546 // We have a relaxed floating-point environment. We can ignore NaN-handling
1547 // and transform to a compare and select. We do not have to consider errno or
1548 // exceptions, because fmin/fmax do not have those.
1549 Value *Op0 = CI->getArgOperand(0);
1550 Value *Op1 = CI->getArgOperand(1);
1551 Value *Cmp = Callee->getName().startswith("fmin") ?
1552 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1553 return B.CreateSelect(Cmp, Op0, Op1);
1554}
1555
Davide Italianob8b71332015-11-29 20:58:04 +00001556Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1557 Function *Callee = CI->getCalledFunction();
1558 Value *Ret = nullptr;
1559 StringRef Name = Callee->getName();
1560 if (UnsafeFPShrink && hasFloatVersion(Name))
1561 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001562
Sanjay Patel629c4112017-11-06 16:27:15 +00001563 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001564 return Ret;
1565 Value *Op1 = CI->getArgOperand(0);
1566 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001567
Sanjay Patel629c4112017-11-06 16:27:15 +00001568 // The earlier call must also be 'fast' in order to do these transforms.
1569 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001570 return Ret;
1571
1572 // log(pow(x,y)) -> y*log(x)
1573 // This is only applicable to log, log2, log10.
1574 if (Name != "log" && Name != "log2" && Name != "log10")
1575 return Ret;
1576
1577 IRBuilder<>::FastMathFlagGuard Guard(B);
1578 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001579 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001580 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001581
David L. Jonesd21529f2017-01-23 23:16:46 +00001582 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001583 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001584 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001585 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001586 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001587 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001588 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001589
1590 // log(exp2(y)) -> y*log(2)
1591 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001592 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001593 return B.CreateFMul(
1594 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001595 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001596 Callee->getName(), B, Callee->getAttributes()),
1597 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001598 return Ret;
1599}
1600
Sanjay Patelc699a612014-10-16 18:48:17 +00001601Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1602 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001603 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001604 // TODO: Once we have a way (other than checking for the existince of the
1605 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1606 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001607 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001608 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001609 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001610
Sanjay Patel629c4112017-11-06 16:27:15 +00001611 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001612 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001613
Sanjay Patelc2d64612016-01-06 20:52:21 +00001614 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001615 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001616 return Ret;
1617
1618 // We're looking for a repeated factor in a multiplication tree,
1619 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001620 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001621 Value *Op0 = I->getOperand(0);
1622 Value *Op1 = I->getOperand(1);
1623 Value *RepeatOp = nullptr;
1624 Value *OtherOp = nullptr;
1625 if (Op0 == Op1) {
1626 // Simple match: the operands of the multiply are identical.
1627 RepeatOp = Op0;
1628 } else {
1629 // Look for a more complicated pattern: one of the operands is itself
1630 // a multiply, so search for a common factor in that multiply.
1631 // Note: We don't bother looking any deeper than this first level or for
1632 // variations of this pattern because instcombine's visitFMUL and/or the
1633 // reassociation pass should give us this form.
1634 Value *OtherMul0, *OtherMul1;
1635 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1636 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001637 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001638 // Matched: sqrt((x * x) * z)
1639 RepeatOp = OtherMul0;
1640 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001641 }
1642 }
1643 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001644 if (!RepeatOp)
1645 return Ret;
1646
1647 // Fast math flags for any created instructions should match the sqrt
1648 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001649 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001650 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001651
Sanjay Patelc2d64612016-01-06 20:52:21 +00001652 // If we found a repeated factor, hoist it out of the square root and
1653 // replace it with the fabs of that factor.
1654 Module *M = Callee->getParent();
1655 Type *ArgType = I->getType();
1656 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1657 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1658 if (OtherOp) {
1659 // If we found a non-repeated factor, we still need to get its square
1660 // root. We then multiply that by the value that was simplified out
1661 // of the square root calculation.
1662 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1663 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1664 return B.CreateFMul(FabsCall, SqrtCall);
1665 }
1666 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001667}
1668
Sanjay Patelcddcd722016-01-06 19:23:35 +00001669// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001670Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1671 Function *Callee = CI->getCalledFunction();
1672 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001673 StringRef Name = Callee->getName();
1674 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001675 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001676
Davide Italiano51507d22015-11-04 23:36:56 +00001677 Value *Op1 = CI->getArgOperand(0);
1678 auto *OpC = dyn_cast<CallInst>(Op1);
1679 if (!OpC)
1680 return Ret;
1681
Sanjay Patel629c4112017-11-06 16:27:15 +00001682 // Both calls must be 'fast' in order to remove them.
1683 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001684 return Ret;
1685
Davide Italiano51507d22015-11-04 23:36:56 +00001686 // tan(atan(x)) -> x
1687 // tanf(atanf(x)) -> x
1688 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001689 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001690 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001691 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001692 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1693 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1694 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001695 Ret = OpC->getArgOperand(0);
1696 return Ret;
1697}
1698
Sanjay Patel57747212016-01-21 23:38:43 +00001699static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001700 // We can only hope to do anything useful if we can ignore things like errno
1701 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001702 // We already checked the prototype.
1703 return CI->hasFnAttr(Attribute::NoUnwind) &&
1704 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001705}
1706
Chris Bienemanad070d02014-09-17 20:55:46 +00001707static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1708 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001709 Value *&SinCos) {
1710 Type *ArgTy = Arg->getType();
1711 Type *ResTy;
1712 StringRef Name;
1713
1714 Triple T(OrigCallee->getParent()->getTargetTriple());
1715 if (UseFloat) {
1716 Name = "__sincospif_stret";
1717
1718 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1719 // x86_64 can't use {float, float} since that would be returned in both
1720 // xmm0 and xmm1, which isn't what a real struct would do.
1721 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001722 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1723 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001724 } else {
1725 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001726 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001727 }
1728
1729 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001730 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001731 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001732
1733 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1734 // If the argument is an instruction, it must dominate all uses so put our
1735 // sincos call there.
1736 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1737 } else {
1738 // Otherwise (e.g. for a constant) the beginning of the function is as
1739 // good a place as any.
1740 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1741 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1742 }
1743
1744 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1745
1746 if (SinCos->getType()->isStructTy()) {
1747 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1748 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1749 } else {
1750 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1751 "sinpi");
1752 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1753 "cospi");
1754 }
1755}
Chris Bienemanad070d02014-09-17 20:55:46 +00001756
1757Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001758 // Make sure the prototype is as expected, otherwise the rest of the
1759 // function is probably invalid and likely to abort.
1760 if (!isTrigLibCall(CI))
1761 return nullptr;
1762
1763 Value *Arg = CI->getArgOperand(0);
1764 SmallVector<CallInst *, 1> SinCalls;
1765 SmallVector<CallInst *, 1> CosCalls;
1766 SmallVector<CallInst *, 1> SinCosCalls;
1767
1768 bool IsFloat = Arg->getType()->isFloatTy();
1769
1770 // Look for all compatible sinpi, cospi and sincospi calls with the same
1771 // argument. If there are enough (in some sense) we can make the
1772 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001773 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001774 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001775 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001776
1777 // It's only worthwhile if both sinpi and cospi are actually used.
1778 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1779 return nullptr;
1780
1781 Value *Sin, *Cos, *SinCos;
1782 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1783
Davide Italianof024a562016-12-16 02:28:38 +00001784 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1785 Value *Res) {
1786 for (CallInst *C : Calls)
1787 replaceAllUsesWith(C, Res);
1788 };
1789
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 replaceTrigInsts(SinCalls, Sin);
1791 replaceTrigInsts(CosCalls, Cos);
1792 replaceTrigInsts(SinCosCalls, SinCos);
1793
1794 return nullptr;
1795}
1796
David Majnemerabae6b52016-03-19 04:53:02 +00001797void LibCallSimplifier::classifyArgUse(
1798 Value *Val, Function *F, bool IsFloat,
1799 SmallVectorImpl<CallInst *> &SinCalls,
1800 SmallVectorImpl<CallInst *> &CosCalls,
1801 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001802 CallInst *CI = dyn_cast<CallInst>(Val);
1803
1804 if (!CI)
1805 return;
1806
David Majnemerabae6b52016-03-19 04:53:02 +00001807 // Don't consider calls in other functions.
1808 if (CI->getFunction() != F)
1809 return;
1810
Chris Bienemanad070d02014-09-17 20:55:46 +00001811 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001812 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001813 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001814 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001815 return;
1816
1817 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001818 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001819 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001820 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001822 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001823 SinCosCalls.push_back(CI);
1824 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001825 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001826 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001827 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001829 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001830 SinCosCalls.push_back(CI);
1831 }
1832}
1833
Meador Inge7415f842012-11-25 20:45:27 +00001834//===----------------------------------------------------------------------===//
1835// Integer Library Call Optimizations
1836//===----------------------------------------------------------------------===//
1837
Chris Bienemanad070d02014-09-17 20:55:46 +00001838Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001840 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001841 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001842 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1843 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001844 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001845 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1846 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001847
Chris Bienemanad070d02014-09-17 20:55:46 +00001848 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1849 return B.CreateSelect(Cond, V, B.getInt32(0));
1850}
Meador Ingea0b6d872012-11-26 00:24:07 +00001851
Davide Italiano85ad36b2016-12-15 23:45:11 +00001852Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1853 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1854 Value *Op = CI->getArgOperand(0);
1855 Type *ArgType = Op->getType();
1856 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1857 Intrinsic::ctlz, ArgType);
1858 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1859 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1860 V);
1861 return B.CreateIntCast(V, CI->getType(), false);
1862}
1863
Chris Bienemanad070d02014-09-17 20:55:46 +00001864Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001865 // abs(x) -> x <s 0 ? -x : x
1866 // The negation has 'nsw' because abs of INT_MIN is undefined.
1867 Value *X = CI->getArgOperand(0);
1868 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1869 Value *NegX = B.CreateNSWNeg(X, "neg");
1870 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001871}
Meador Inge9a59ab62012-11-26 02:31:59 +00001872
Chris Bienemanad070d02014-09-17 20:55:46 +00001873Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001874 // isdigit(c) -> (c-'0') <u 10
1875 Value *Op = CI->getArgOperand(0);
1876 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1877 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1878 return B.CreateZExt(Op, CI->getType());
1879}
Meador Ingea62a39e2012-11-26 03:10:07 +00001880
Chris Bienemanad070d02014-09-17 20:55:46 +00001881Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001882 // isascii(c) -> c <u 128
1883 Value *Op = CI->getArgOperand(0);
1884 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1885 return B.CreateZExt(Op, CI->getType());
1886}
1887
1888Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001889 // toascii(c) -> c & 0x7f
1890 return B.CreateAnd(CI->getArgOperand(0),
1891 ConstantInt::get(CI->getType(), 0x7F));
1892}
Meador Inge604937d2012-11-26 03:38:52 +00001893
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001894Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1895 StringRef Str;
1896 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1897 return nullptr;
1898
1899 return convertStrToNumber(CI, Str, 10);
1900}
1901
1902Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1903 StringRef Str;
1904 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1905 return nullptr;
1906
1907 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1908 return nullptr;
1909
1910 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1911 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1912 }
1913
1914 return nullptr;
1915}
1916
Meador Inge08ca1152012-11-26 20:37:20 +00001917//===----------------------------------------------------------------------===//
1918// Formatting and IO Library Call Optimizations
1919//===----------------------------------------------------------------------===//
1920
Chris Bienemanad070d02014-09-17 20:55:46 +00001921static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001922
Chris Bienemanad070d02014-09-17 20:55:46 +00001923Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1924 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001925 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001926 // Error reporting calls should be cold, mark them as such.
1927 // This applies even to non-builtin calls: it is only a hint and applies to
1928 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001929
Chris Bienemanad070d02014-09-17 20:55:46 +00001930 // This heuristic was suggested in:
1931 // Improving Static Branch Prediction in a Compiler
1932 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1933 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001934 if (!CI->hasFnAttr(Attribute::Cold) &&
1935 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001936 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001937 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001938
Chris Bienemanad070d02014-09-17 20:55:46 +00001939 return nullptr;
1940}
1941
1942static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001943 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001944 return false;
1945
1946 if (StreamArg < 0)
1947 return true;
1948
1949 // These functions might be considered cold, but only if their stream
1950 // argument is stderr.
1951
1952 if (StreamArg >= (int)CI->getNumArgOperands())
1953 return false;
1954 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1955 if (!LI)
1956 return false;
1957 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1958 if (!GV || !GV->isDeclaration())
1959 return false;
1960 return GV->getName() == "stderr";
1961}
1962
1963Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1964 // Check for a fixed format string.
1965 StringRef FormatStr;
1966 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001967 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001968
Chris Bienemanad070d02014-09-17 20:55:46 +00001969 // Empty format string -> noop.
1970 if (FormatStr.empty()) // Tolerate printf's declared void.
1971 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001972
Chris Bienemanad070d02014-09-17 20:55:46 +00001973 // Do not do any of the following transformations if the printf return value
1974 // is used, in general the printf return value is not compatible with either
1975 // putchar() or puts().
1976 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001977 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001978
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001979 // printf("x") -> putchar('x'), even for "%" and "%%".
1980 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001981 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001982
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001983 // printf("%s", "a") --> putchar('a')
1984 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1985 StringRef ChrStr;
1986 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1987 return nullptr;
1988 if (ChrStr.size() != 1)
1989 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001990 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001991 }
1992
Chris Bienemanad070d02014-09-17 20:55:46 +00001993 // printf("foo\n") --> puts("foo")
1994 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1995 FormatStr.find('%') == StringRef::npos) { // No format characters.
1996 // Create a string literal with no \n on it. We expect the constant merge
1997 // pass to be run after this pass, to merge duplicate strings.
1998 FormatStr = FormatStr.drop_back();
1999 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00002000 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002001 }
Meador Inge08ca1152012-11-26 20:37:20 +00002002
Chris Bienemanad070d02014-09-17 20:55:46 +00002003 // Optimize specific format strings.
2004 // printf("%c", chr) --> putchar(chr)
2005 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002006 CI->getArgOperand(1)->getType()->isIntegerTy())
2007 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002008
2009 // printf("%s\n", str) --> puts(str)
2010 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002011 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002012 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002013 return nullptr;
2014}
2015
2016Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2017
2018 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002019 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002020 if (Value *V = optimizePrintFString(CI, B)) {
2021 return V;
2022 }
2023
2024 // printf(format, ...) -> iprintf(format, ...) if no floating point
2025 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002026 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002027 Module *M = B.GetInsertBlock()->getParent()->getParent();
2028 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002029 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002030 CallInst *New = cast<CallInst>(CI->clone());
2031 New->setCalledFunction(IPrintFFn);
2032 B.Insert(New);
2033 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002034 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002035 return nullptr;
2036}
Meador Inge08ca1152012-11-26 20:37:20 +00002037
Chris Bienemanad070d02014-09-17 20:55:46 +00002038Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2039 // Check for a fixed format string.
2040 StringRef FormatStr;
2041 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002042 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002043
Chris Bienemanad070d02014-09-17 20:55:46 +00002044 // If we just have a format string (nothing else crazy) transform it.
2045 if (CI->getNumArgOperands() == 2) {
2046 // Make sure there's no % in the constant array. We could try to handle
2047 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002048 if (FormatStr.find('%') != StringRef::npos)
2049 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002050
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002051 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2052 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002053 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002054 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002055 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002056 }
Meador Ingef8e72502012-11-29 15:45:43 +00002057
Chris Bienemanad070d02014-09-17 20:55:46 +00002058 // The remaining optimizations require the format string to be "%s" or "%c"
2059 // and have an extra operand.
2060 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2061 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002062 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002063
Chris Bienemanad070d02014-09-17 20:55:46 +00002064 // Decode the second character of the format string.
2065 if (FormatStr[1] == 'c') {
2066 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2067 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2068 return nullptr;
2069 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00002070 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002071 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002072 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002073 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002074
Chris Bienemanad070d02014-09-17 20:55:46 +00002075 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002076 }
2077
Chris Bienemanad070d02014-09-17 20:55:46 +00002078 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00002079 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
2080 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2081 return nullptr;
2082
Sanjay Pateld3112a52016-01-19 19:46:10 +00002083 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002084 if (!Len)
2085 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002086 Value *IncLen =
2087 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002088 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002089
2090 // The sprintf result is the unincremented number of bytes in the string.
2091 return B.CreateIntCast(Len, CI->getType(), false);
2092 }
2093 return nullptr;
2094}
2095
2096Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2097 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002098 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002099 if (Value *V = optimizeSPrintFString(CI, B)) {
2100 return V;
2101 }
2102
2103 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2104 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002105 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002106 Module *M = B.GetInsertBlock()->getParent()->getParent();
2107 Constant *SIPrintFFn =
2108 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2109 CallInst *New = cast<CallInst>(CI->clone());
2110 New->setCalledFunction(SIPrintFFn);
2111 B.Insert(New);
2112 return New;
2113 }
2114 return nullptr;
2115}
2116
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002117Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2118 // Check for a fixed format string.
2119 StringRef FormatStr;
2120 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2121 return nullptr;
2122
2123 // Check for size
2124 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2125 if (!Size)
2126 return nullptr;
2127
2128 uint64_t N = Size->getZExtValue();
2129
2130 // If we just have a format string (nothing else crazy) transform it.
2131 if (CI->getNumArgOperands() == 3) {
2132 // Make sure there's no % in the constant array. We could try to handle
2133 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002134 if (FormatStr.find('%') != StringRef::npos)
2135 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002136
2137 if (N == 0)
2138 return ConstantInt::get(CI->getType(), FormatStr.size());
2139 else if (N < FormatStr.size() + 1)
2140 return nullptr;
2141
2142 // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
2143 // strlen(fmt)+1)
2144 B.CreateMemCpy(
2145 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2146 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2147 FormatStr.size() + 1)); // Copy the null byte.
2148 return ConstantInt::get(CI->getType(), FormatStr.size());
2149 }
2150
2151 // The remaining optimizations require the format string to be "%s" or "%c"
2152 // and have an extra operand.
2153 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2154 CI->getNumArgOperands() == 4) {
2155
2156 // Decode the second character of the format string.
2157 if (FormatStr[1] == 'c') {
2158 if (N == 0)
2159 return ConstantInt::get(CI->getType(), 1);
2160 else if (N == 1)
2161 return nullptr;
2162
2163 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2164 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2165 return nullptr;
2166 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2167 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2168 B.CreateStore(V, Ptr);
2169 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2170 B.CreateStore(B.getInt8(0), Ptr);
2171
2172 return ConstantInt::get(CI->getType(), 1);
2173 }
2174
2175 if (FormatStr[1] == 's') {
2176 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2177 StringRef Str;
2178 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2179 return nullptr;
2180
2181 if (N == 0)
2182 return ConstantInt::get(CI->getType(), Str.size());
2183 else if (N < Str.size() + 1)
2184 return nullptr;
2185
2186 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2187 ConstantInt::get(CI->getType(), Str.size() + 1));
2188
2189 // The snprintf result is the unincremented number of bytes in the string.
2190 return ConstantInt::get(CI->getType(), Str.size());
2191 }
2192 }
2193 return nullptr;
2194}
2195
2196Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2197 if (Value *V = optimizeSnPrintFString(CI, B)) {
2198 return V;
2199 }
2200
2201 return nullptr;
2202}
2203
Chris Bienemanad070d02014-09-17 20:55:46 +00002204Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2205 optimizeErrorReporting(CI, B, 0);
2206
2207 // All the optimizations depend on the format string.
2208 StringRef FormatStr;
2209 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2210 return nullptr;
2211
2212 // Do not do any of the following transformations if the fprintf return
2213 // value is used, in general the fprintf return value is not compatible
2214 // with fwrite(), fputc() or fputs().
2215 if (!CI->use_empty())
2216 return nullptr;
2217
2218 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2219 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002220 // Could handle %% -> % if we cared.
2221 if (FormatStr.find('%') != StringRef::npos)
2222 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002223
Sanjay Pateld3112a52016-01-19 19:46:10 +00002224 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002225 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002226 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002227 CI->getArgOperand(0), B, DL, TLI);
2228 }
2229
2230 // The remaining optimizations require the format string to be "%s" or "%c"
2231 // and have an extra operand.
2232 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2233 CI->getNumArgOperands() < 3)
2234 return nullptr;
2235
2236 // Decode the second character of the format string.
2237 if (FormatStr[1] == 'c') {
2238 // fprintf(F, "%c", chr) --> fputc(chr, F)
2239 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2240 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002241 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002242 }
2243
2244 if (FormatStr[1] == 's') {
2245 // fprintf(F, "%s", str) --> fputs(str, F)
2246 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2247 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002248 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002249 }
2250 return nullptr;
2251}
2252
2253Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2254 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002255 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002256 if (Value *V = optimizeFPrintFString(CI, B)) {
2257 return V;
2258 }
2259
2260 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2261 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002262 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002263 Module *M = B.GetInsertBlock()->getParent()->getParent();
2264 Constant *FIPrintFFn =
2265 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2266 CallInst *New = cast<CallInst>(CI->clone());
2267 New->setCalledFunction(FIPrintFFn);
2268 B.Insert(New);
2269 return New;
2270 }
2271 return nullptr;
2272}
2273
2274Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2275 optimizeErrorReporting(CI, B, 3);
2276
Chris Bienemanad070d02014-09-17 20:55:46 +00002277 // Get the element size and count.
2278 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2279 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002280 if (SizeC && CountC) {
2281 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002282
David Bolvanskyca22d422018-05-16 11:39:52 +00002283 // If this is writing zero records, remove the call (it's a noop).
2284 if (Bytes == 0)
2285 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002286
David Bolvanskyca22d422018-05-16 11:39:52 +00002287 // If this is writing one byte, turn it into fputc.
2288 // This optimisation is only valid, if the return value is unused.
2289 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
2290 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2291 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2292 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2293 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002294 }
2295
David Bolvanskyca22d422018-05-16 11:39:52 +00002296 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2297 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2298 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2299 TLI);
2300
Chris Bienemanad070d02014-09-17 20:55:46 +00002301 return nullptr;
2302}
2303
2304Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2305 optimizeErrorReporting(CI, B, 1);
2306
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002307 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2308 // requires more arguments and thus extra MOVs are required.
David Bolvansky5430b7372018-05-31 16:39:27 +00002309 if (CI->getFunction()->optForSize())
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002310 return nullptr;
2311
David Bolvanskyca22d422018-05-16 11:39:52 +00002312 // Check if has any use
2313 if (!CI->use_empty()) {
2314 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2315 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2316 TLI);
2317 else
2318 // We can't optimize if return value is used.
2319 return nullptr;
2320 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002321
2322 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002323 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002324 if (!Len)
2325 return nullptr;
2326
2327 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002328 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002329 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002330 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002331 CI->getArgOperand(1), B, DL, TLI);
2332}
2333
David Bolvanskyca22d422018-05-16 11:39:52 +00002334Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2335 optimizeErrorReporting(CI, B, 1);
2336
2337 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2338 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2339 TLI);
2340
2341 return nullptr;
2342}
2343
2344Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2345 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2346 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2347
2348 return nullptr;
2349}
2350
2351Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2352 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2353 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2354 CI->getArgOperand(2), B, TLI);
2355
2356 return nullptr;
2357}
2358
2359Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2360 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2361 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2362 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2363 TLI);
2364
2365 return nullptr;
2366}
2367
Chris Bienemanad070d02014-09-17 20:55:46 +00002368Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002369 // Check for a constant string.
2370 StringRef Str;
2371 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2372 return nullptr;
2373
2374 if (Str.empty() && CI->use_empty()) {
2375 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002376 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002377 if (CI->use_empty() || !Res)
2378 return Res;
2379 return B.CreateIntCast(Res, CI->getType(), true);
2380 }
2381
2382 return nullptr;
2383}
2384
2385bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002386 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002387 SmallString<20> FloatFuncName = FuncName;
2388 FloatFuncName += 'f';
2389 if (TLI->getLibFunc(FloatFuncName, Func))
2390 return TLI->has(Func);
2391 return false;
2392}
Meador Inge7fb2f732012-10-13 16:45:32 +00002393
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002394Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2395 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002396 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002397 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002398 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002399 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002400 // Make sure we never change the calling convention.
2401 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002402 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002403 "Optimizing string/memory libcall would change the calling convention");
2404 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002405 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002406 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002407 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002408 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002409 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002410 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002411 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002412 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002413 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002414 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002415 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002416 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002417 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002418 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002419 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002420 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002421 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002422 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002423 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002424 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002425 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002426 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002427 case LibFunc_strtol:
2428 case LibFunc_strtod:
2429 case LibFunc_strtof:
2430 case LibFunc_strtoul:
2431 case LibFunc_strtoll:
2432 case LibFunc_strtold:
2433 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002434 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002435 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002436 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002437 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002438 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002439 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002440 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002441 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002442 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002443 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002444 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002445 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002446 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002447 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002448 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002449 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002450 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002451 case LibFunc_realloc:
2452 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002453 case LibFunc_wcslen:
2454 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002455 default:
2456 break;
2457 }
2458 }
2459 return nullptr;
2460}
2461
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002462Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2463 LibFunc Func,
2464 IRBuilder<> &Builder) {
2465 // Don't optimize calls that require strict floating point semantics.
2466 if (CI->isStrictFP())
2467 return nullptr;
2468
Sanjay Patele45a83d2018-08-13 19:24:41 +00002469 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2470 return V;
2471
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002472 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002473 case LibFunc_sinpif:
2474 case LibFunc_sinpi:
2475 case LibFunc_cospif:
2476 case LibFunc_cospi:
2477 return optimizeSinCosPi(CI, Builder);
2478 case LibFunc_powf:
2479 case LibFunc_pow:
2480 case LibFunc_powl:
2481 return optimizePow(CI, Builder);
2482 case LibFunc_exp2l:
2483 case LibFunc_exp2:
2484 case LibFunc_exp2f:
2485 return optimizeExp2(CI, Builder);
2486 case LibFunc_fabsf:
2487 case LibFunc_fabs:
2488 case LibFunc_fabsl:
2489 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2490 case LibFunc_sqrtf:
2491 case LibFunc_sqrt:
2492 case LibFunc_sqrtl:
2493 return optimizeSqrt(CI, Builder);
2494 case LibFunc_log:
2495 case LibFunc_log10:
2496 case LibFunc_log1p:
2497 case LibFunc_log2:
2498 case LibFunc_logb:
2499 return optimizeLog(CI, Builder);
2500 case LibFunc_tan:
2501 case LibFunc_tanf:
2502 case LibFunc_tanl:
2503 return optimizeTan(CI, Builder);
2504 case LibFunc_ceil:
2505 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2506 case LibFunc_floor:
2507 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2508 case LibFunc_round:
2509 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2510 case LibFunc_nearbyint:
2511 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2512 case LibFunc_rint:
2513 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2514 case LibFunc_trunc:
2515 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2516 case LibFunc_acos:
2517 case LibFunc_acosh:
2518 case LibFunc_asin:
2519 case LibFunc_asinh:
2520 case LibFunc_atan:
2521 case LibFunc_atanh:
2522 case LibFunc_cbrt:
2523 case LibFunc_cosh:
2524 case LibFunc_exp:
2525 case LibFunc_exp10:
2526 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002527 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002528 case LibFunc_sin:
2529 case LibFunc_sinh:
2530 case LibFunc_tanh:
2531 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2532 return optimizeUnaryDoubleFP(CI, Builder, true);
2533 return nullptr;
2534 case LibFunc_copysign:
2535 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2536 return optimizeBinaryDoubleFP(CI, Builder);
2537 return nullptr;
2538 case LibFunc_fminf:
2539 case LibFunc_fmin:
2540 case LibFunc_fminl:
2541 case LibFunc_fmaxf:
2542 case LibFunc_fmax:
2543 case LibFunc_fmaxl:
2544 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002545 case LibFunc_cabs:
2546 case LibFunc_cabsf:
2547 case LibFunc_cabsl:
2548 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002549 default:
2550 return nullptr;
2551 }
2552}
2553
Chris Bienemanad070d02014-09-17 20:55:46 +00002554Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002555 // TODO: Split out the code below that operates on FP calls so that
2556 // we can all non-FP calls with the StrictFP attribute to be
2557 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002558 if (CI->isNoBuiltin())
2559 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002560
David L. Jonesd21529f2017-01-23 23:16:46 +00002561 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002562 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002563
2564 SmallVector<OperandBundleDef, 2> OpBundles;
2565 CI->getOperandBundlesAsDefs(OpBundles);
2566 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002567 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002568
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002569 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002570 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002571 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002572 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2573 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002574 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002575 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002576
Sanjay Patel848309d2014-10-23 21:52:45 +00002577 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002578 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002579 if (!isCallingConvC)
2580 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002581 // The FP intrinsics have corresponding constrained versions so we don't
2582 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002583 switch (II->getIntrinsicID()) {
2584 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002585 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002586 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002587 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002588 case Intrinsic::log:
2589 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002590 case Intrinsic::sqrt:
2591 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002592 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002593 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002594 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002595 }
2596 }
2597
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002598 // Also try to simplify calls to fortified library functions.
2599 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2600 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002601 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002602 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2603 // Use an IR Builder from SimplifiedCI if available instead of CI
2604 // to guarantee we reach all uses we might replace later on.
2605 IRBuilder<> TmpBuilder(SimplifiedCI);
2606 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002607 // If we were able to further simplify, remove the now redundant call.
2608 SimplifiedCI->replaceAllUsesWith(V);
Amara Emerson54f60252018-10-11 14:51:11 +00002609 eraseFromParent(SimplifiedCI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002610 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002611 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002612 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002613 return SimplifiedFortifiedCI;
2614 }
2615
Meador Inge20255ef2013-03-12 00:08:29 +00002616 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002617 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002618 // We never change the calling convention.
2619 if (!ignoreCallingConv(Func) && !isCallingConvC)
2620 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002621 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2622 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002623 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2624 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002625 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002626 case LibFunc_ffs:
2627 case LibFunc_ffsl:
2628 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002629 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002630 case LibFunc_fls:
2631 case LibFunc_flsl:
2632 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002633 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002634 case LibFunc_abs:
2635 case LibFunc_labs:
2636 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002637 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002638 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002639 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002640 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002641 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002642 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002643 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002644 case LibFunc_atoi:
2645 case LibFunc_atol:
2646 case LibFunc_atoll:
2647 return optimizeAtoi(CI, Builder);
2648 case LibFunc_strtol:
2649 case LibFunc_strtoll:
2650 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002651 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002652 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002653 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002654 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002655 case LibFunc_snprintf:
2656 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002657 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002658 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002659 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002660 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002661 case LibFunc_fread:
2662 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002663 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002664 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002665 case LibFunc_fgets:
2666 return optimizeFGets(CI, Builder);
2667 case LibFunc_fputc:
2668 return optimizeFPutc(CI, Builder);
2669 case LibFunc_fgetc:
2670 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002671 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002672 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002673 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002674 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002675 case LibFunc_vfprintf:
2676 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002677 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002678 default:
2679 return nullptr;
2680 }
Meador Inge20255ef2013-03-12 00:08:29 +00002681 }
Craig Topperf40110f2014-04-25 05:29:35 +00002682 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002683}
2684
Chandler Carruth92803822015-01-21 02:11:59 +00002685LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002686 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002687 OptimizationRemarkEmitter &ORE,
Amara Emerson54f60252018-10-11 14:51:11 +00002688 function_ref<void(Instruction *, Value *)> Replacer,
2689 function_ref<void(Instruction *)> Eraser)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002690 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
Amara Emerson54f60252018-10-11 14:51:11 +00002691 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002692
2693void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2694 // Indirect through the replacer used in this instance.
2695 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002696}
2697
Amara Emerson54f60252018-10-11 14:51:11 +00002698void LibCallSimplifier::eraseFromParent(Instruction *I) {
2699 Eraser(I);
2700}
2701
Meador Ingedfb08a22013-06-20 19:48:07 +00002702// TODO:
2703// Additional cases that we need to add to this file:
2704//
2705// cbrt:
2706// * cbrt(expN(X)) -> expN(x/3)
2707// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002708// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002709//
2710// exp, expf, expl:
2711// * exp(log(x)) -> x
2712//
2713// log, logf, logl:
2714// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002715// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002716// * log(exp10(y)) -> y*log(10)
2717// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002718//
Meador Ingedfb08a22013-06-20 19:48:07 +00002719// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002720// * pow(sqrt(x),y) -> pow(x,y*0.5)
2721// * pow(pow(x,y),z)-> pow(x,y*z)
2722//
Meador Ingedfb08a22013-06-20 19:48:07 +00002723// signbit:
2724// * signbit(cnst) -> cnst'
2725// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2726//
2727// sqrt, sqrtf, sqrtl:
2728// * sqrt(expN(x)) -> expN(x*0.5)
2729// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2730// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2731//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002732
2733//===----------------------------------------------------------------------===//
2734// Fortified Library Call Optimizations
2735//===----------------------------------------------------------------------===//
2736
2737bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2738 unsigned ObjSizeOp,
2739 unsigned SizeOp,
2740 bool isString) {
2741 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2742 return true;
2743 if (ConstantInt *ObjSizeCI =
2744 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002745 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002746 return true;
2747 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2748 if (OnlyLowerUnknownSize)
2749 return false;
2750 if (isString) {
David Bolvansky1f343fa2018-05-22 20:27:36 +00002751 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002752 // If the length is 0 we don't know how long it is and so we can't
2753 // remove the check.
2754 if (Len == 0)
2755 return false;
2756 return ObjSizeCI->getZExtValue() >= Len;
2757 }
2758 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2759 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2760 }
2761 return false;
2762}
2763
Sanjay Pateld707db92015-12-31 16:10:49 +00002764Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2765 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002766 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002767 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2768 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002769 return CI->getArgOperand(0);
2770 }
2771 return nullptr;
2772}
2773
Sanjay Pateld707db92015-12-31 16:10:49 +00002774Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2775 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002776 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002777 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2778 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002779 return CI->getArgOperand(0);
2780 }
2781 return nullptr;
2782}
2783
Sanjay Pateld707db92015-12-31 16:10:49 +00002784Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2785 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002786 // TODO: Try foldMallocMemset() here.
2787
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002788 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2789 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2790 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2791 return CI->getArgOperand(0);
2792 }
2793 return nullptr;
2794}
2795
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002796Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2797 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002798 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002799 Function *Callee = CI->getCalledFunction();
2800 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002801 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002802 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2803 *ObjSize = CI->getArgOperand(2);
2804
2805 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002806 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002807 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002808 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002809 }
2810
2811 // If a) we don't have any length information, or b) we know this will
2812 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2813 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2814 // TODO: It might be nice to get a maximum length out of the possible
2815 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002816 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002817 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002818
David Blaikie65fab6d2015-04-03 21:32:06 +00002819 if (OnlyLowerUnknownSize)
2820 return nullptr;
2821
2822 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002823 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002824 if (Len == 0)
2825 return nullptr;
2826
2827 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2828 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002829 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002830 // If the function was an __stpcpy_chk, and we were able to fold it into
2831 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002832 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002833 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2834 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002835}
2836
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002837Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2838 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002839 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002840 Function *Callee = CI->getCalledFunction();
2841 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002842 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002843 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002844 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002845 return Ret;
2846 }
2847 return nullptr;
2848}
2849
2850Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002851 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2852 // Some clang users checked for _chk libcall availability using:
2853 // __has_builtin(__builtin___memcpy_chk)
2854 // When compiling with -fno-builtin, this is always true.
2855 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2856 // end up with fortified libcalls, which isn't acceptable in a freestanding
2857 // environment which only provides their non-fortified counterparts.
2858 //
2859 // Until we change clang and/or teach external users to check for availability
2860 // differently, disregard the "nobuiltin" attribute and TLI::has.
2861 //
2862 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002863
David L. Jonesd21529f2017-01-23 23:16:46 +00002864 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002865 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002866
2867 SmallVector<OperandBundleDef, 2> OpBundles;
2868 CI->getOperandBundlesAsDefs(OpBundles);
2869 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002870 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002871
Ahmed Bougachad765a822016-04-27 19:04:35 +00002872 // First, check that this is a known library functions and that the prototype
2873 // is correct.
2874 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002875 return nullptr;
2876
2877 // We never change the calling convention.
2878 if (!ignoreCallingConv(Func) && !isCallingConvC)
2879 return nullptr;
2880
2881 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002882 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002883 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002884 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002885 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002886 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002887 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002888 case LibFunc_stpcpy_chk:
2889 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002890 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002891 case LibFunc_stpncpy_chk:
2892 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002893 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002894 default:
2895 break;
2896 }
2897 return nullptr;
2898}
2899
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002900FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2901 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Sanjay Patel4b969352018-05-22 23:29:40 +00002902 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}