blob: 1fb4f28f33641f4e0047d7936c989a35715b9e25 [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"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000019#include "llvm/Analysis/BlockFrequencyInfo.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000020#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000021#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000022#include "llvm/Analysis/ProfileSummaryInfo.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000024#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000025#include "llvm/Analysis/ValueTracking.h"
David Bolvanskyca22d422018-05-16 11:39:52 +000026#include "llvm/Analysis/CaptureTracking.h"
David Bolvansky909889b2018-08-10 04:32:54 +000027#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000031#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000035#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000036#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000037#include "llvm/Support/KnownBits.h"
Evandro Menezes110b1132019-09-30 20:52:21 +000038#include "llvm/Support/MathExtras.h"
Meador Ingedf796f82012-10-13 16:45:24 +000039#include "llvm/Transforms/Utils/BuildLibCalls.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000040#include "llvm/Transforms/Utils/SizeOpts.h"
Meador Ingedf796f82012-10-13 16:45:24 +000041
42using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000043using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000044
Hal Finkel66cd3f12013-11-17 02:06:35 +000045static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000046 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
47 cl::init(false),
48 cl::desc("Enable unsafe double to float "
49 "shrinking for math lib calls"));
50
51
Meador Ingedf796f82012-10-13 16:45:24 +000052//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000053// Helper Functions
54//===----------------------------------------------------------------------===//
55
David L. Jonesd21529f2017-01-23 23:16:46 +000056static bool ignoreCallingConv(LibFunc Func) {
57 return Func == LibFunc_abs || Func == LibFunc_labs ||
58 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000059}
60
Sam Parker214f7bf2016-09-13 12:10:14 +000061static bool isCallingConvCCompatible(CallInst *CI) {
62 switch(CI->getCallingConv()) {
63 default:
64 return false;
65 case llvm::CallingConv::C:
66 return true;
67 case llvm::CallingConv::ARM_APCS:
68 case llvm::CallingConv::ARM_AAPCS:
69 case llvm::CallingConv::ARM_AAPCS_VFP: {
70
71 // The iOS ABI diverges from the standard in some cases, so for now don't
72 // try to simplify those calls.
73 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
74 return false;
75
76 auto *FuncTy = CI->getFunctionType();
77
78 if (!FuncTy->getReturnType()->isPointerTy() &&
79 !FuncTy->getReturnType()->isIntegerTy() &&
80 !FuncTy->getReturnType()->isVoidTy())
81 return false;
82
83 for (auto Param : FuncTy->params()) {
84 if (!Param->isPointerTy() && !Param->isIntegerTy())
85 return false;
86 }
87 return true;
88 }
89 }
90 return false;
91}
92
Sanjay Pateld707db92015-12-31 16:10:49 +000093/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000094static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000095 for (User *U : V->users()) {
96 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000097 if (IC->isEquality() && IC->getOperand(1) == With)
98 continue;
99 // Unknown instruction.
100 return false;
101 }
102 return true;
103}
104
Meador Inge08ca1152012-11-26 20:37:20 +0000105static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000106 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000107 return OI->getType()->isFloatingPointTy();
108 });
Meador Inge08ca1152012-11-26 20:37:20 +0000109}
110
Alon Zakaib4f99912019-04-03 01:08:35 +0000111static bool callHasFP128Argument(const CallInst *CI) {
112 return any_of(CI->operands(), [](const Use &OI) {
113 return OI->getType()->isFP128Ty();
114 });
115}
116
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000117static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
118 if (Base < 2 || Base > 36)
119 // handle special zero base
120 if (Base != 0)
121 return nullptr;
122
123 char *End;
124 std::string nptr = Str.str();
125 errno = 0;
126 long long int Result = strtoll(nptr.c_str(), &End, Base);
127 if (errno)
128 return nullptr;
129
130 // if we assume all possible target locales are ASCII supersets,
131 // then if strtoll successfully parses a number on the host,
132 // it will also successfully parse the same way on the target
133 if (*End != '\0')
134 return nullptr;
135
136 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
137 return nullptr;
138
139 return ConstantInt::get(CI->getType(), Result);
140}
141
David Bolvanskyca22d422018-05-16 11:39:52 +0000142static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
143 const TargetLibraryInfo *TLI) {
144 CallInst *FOpen = dyn_cast<CallInst>(File);
145 if (!FOpen)
146 return false;
147
148 Function *InnerCallee = FOpen->getCalledFunction();
149 if (!InnerCallee)
150 return false;
151
152 LibFunc Func;
153 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
154 Func != LibFunc_fopen)
155 return false;
156
David Bolvansky7c7760d2018-10-16 21:18:31 +0000157 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
David Bolvanskyca22d422018-05-16 11:39:52 +0000158 if (PointerMayBeCaptured(File, true, true))
159 return false;
160
161 return true;
162}
163
David Bolvansky909889b2018-08-10 04:32:54 +0000164static bool isOnlyUsedInComparisonWithZero(Value *V) {
165 for (User *U : V->users()) {
166 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
167 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
168 if (C->isNullValue())
169 continue;
170 // Unknown instruction.
171 return false;
172 }
173 return true;
174}
175
176static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
177 const DataLayout &DL) {
178 if (!isOnlyUsedInComparisonWithZero(CI))
179 return false;
180
181 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
182 return false;
Matt Morehousee62fc3d2018-09-19 19:37:24 +0000183
184 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
185 return false;
186
David Bolvansky909889b2018-08-10 04:32:54 +0000187 return true;
188}
189
David Bolvansky39130312019-08-13 09:11:49 +0000190static void annotateDereferenceableBytes(CallInst *CI,
191 ArrayRef<unsigned> ArgNos,
David Bolvansky90a30fd2019-08-13 16:44:16 +0000192 uint64_t DereferenceableBytes) {
David Bolvanskye80fcf02019-09-17 09:32:52 +0000193 const Function *F = CI->getCaller();
David Bolvanskyf94460d2019-08-14 17:15:20 +0000194 if (!F)
195 return;
David Bolvansky39130312019-08-13 09:11:49 +0000196 for (unsigned ArgNo : ArgNos) {
David Bolvanskyf94460d2019-08-14 17:15:20 +0000197 uint64_t DerefBytes = DereferenceableBytes;
198 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
David Bolvanskye80fcf02019-09-17 09:32:52 +0000199 if (!llvm::NullPointerIsDefined(F, AS) ||
200 CI->paramHasAttr(ArgNo, Attribute::NonNull))
David Bolvanskyf94460d2019-08-14 17:15:20 +0000201 DerefBytes = std::max(CI->getDereferenceableOrNullBytes(
202 ArgNo + AttributeList::FirstArgIndex),
203 DereferenceableBytes);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000204
David Bolvansky39130312019-08-13 09:11:49 +0000205 if (CI->getDereferenceableBytes(ArgNo + AttributeList::FirstArgIndex) <
206 DerefBytes) {
207 CI->removeParamAttr(ArgNo, Attribute::Dereferenceable);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000208 if (!llvm::NullPointerIsDefined(F, AS) ||
209 CI->paramHasAttr(ArgNo, Attribute::NonNull))
David Bolvanskyf94460d2019-08-14 17:15:20 +0000210 CI->removeParamAttr(ArgNo, Attribute::DereferenceableOrNull);
David Bolvansky39130312019-08-13 09:11:49 +0000211 CI->addParamAttr(ArgNo, Attribute::getWithDereferenceableBytes(
212 CI->getContext(), DerefBytes));
213 }
214 }
215}
216
David Bolvanskye80fcf02019-09-17 09:32:52 +0000217static void annotateNonNullBasedOnAccess(CallInst *CI,
218 ArrayRef<unsigned> ArgNos) {
219 Function *F = CI->getCaller();
220 if (!F)
221 return;
222
223 for (unsigned ArgNo : ArgNos) {
224 if (CI->paramHasAttr(ArgNo, Attribute::NonNull))
225 continue;
226 unsigned AS = CI->getArgOperand(ArgNo)->getType()->getPointerAddressSpace();
227 if (llvm::NullPointerIsDefined(F, AS))
228 continue;
229
230 CI->addParamAttr(ArgNo, Attribute::NonNull);
231 annotateDereferenceableBytes(CI, ArgNo, 1);
232 }
233}
234
235static void annotateNonNullAndDereferenceable(CallInst *CI, ArrayRef<unsigned> ArgNos,
236 Value *Size, const DataLayout &DL) {
237 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size)) {
238 annotateNonNullBasedOnAccess(CI, ArgNos);
239 annotateDereferenceableBytes(CI, ArgNos, LenC->getZExtValue());
240 } else if (isKnownNonZero(Size, DL)) {
241 annotateNonNullBasedOnAccess(CI, ArgNos);
242 const APInt *X, *Y;
243 uint64_t DerefMin = 1;
244 if (match(Size, m_Select(m_Value(), m_APInt(X), m_APInt(Y)))) {
245 DerefMin = std::min(X->getZExtValue(), Y->getZExtValue());
246 annotateDereferenceableBytes(CI, ArgNos, DerefMin);
247 }
248 }
249}
250
Meador Inged589ac62012-10-31 03:33:06 +0000251//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000252// String and Memory Library Call Optimizations
253//===----------------------------------------------------------------------===//
254
Chris Bienemanad070d02014-09-17 20:55:46 +0000255Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000256 // Extract some information from the instruction
257 Value *Dst = CI->getArgOperand(0);
258 Value *Src = CI->getArgOperand(1);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000259 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000260
261 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000262 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000263 if (Len)
264 annotateDereferenceableBytes(CI, 1, Len);
265 else
Chris Bienemanad070d02014-09-17 20:55:46 +0000266 return nullptr;
267 --Len; // Unbias length.
268
269 // Handle the simple, do-nothing case: strcat(x, "") -> x
270 if (Len == 0)
271 return Dst;
272
Chris Bienemanad070d02014-09-17 20:55:46 +0000273 return emitStrLenMemCpy(Src, Dst, Len, B);
274}
275
276Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
277 IRBuilder<> &B) {
278 // We need to find the end of the destination string. That's where the
279 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000280 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000281 if (!DstLen)
282 return nullptr;
283
284 // Now that we have the destination's length, we must index into the
285 // destination's pointer to get the actual memcpy destination (end of
286 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000287 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000288
289 // We have enough information to now generate the memcpy call to do the
290 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000291 B.CreateMemCpy(CpyDst, 1, Src, 1,
292 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000293 return Dst;
294}
295
296Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000297 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000298 Value *Dst = CI->getArgOperand(0);
299 Value *Src = CI->getArgOperand(1);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000300 Value *Size = CI->getArgOperand(2);
Chris Bienemanad070d02014-09-17 20:55:46 +0000301 uint64_t Len;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000302 annotateNonNullBasedOnAccess(CI, 0);
303 if (isKnownNonZero(Size, DL))
304 annotateNonNullBasedOnAccess(CI, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000305
Sanjay Pateld707db92015-12-31 16:10:49 +0000306 // We don't do anything if length is not constant.
David Bolvanskye80fcf02019-09-17 09:32:52 +0000307 ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size);
308 if (LengthArg) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000309 Len = LengthArg->getZExtValue();
David Bolvanskye80fcf02019-09-17 09:32:52 +0000310 // strncat(x, c, 0) -> x
311 if (!Len)
312 return Dst;
313 } else {
Chris Bienemanad070d02014-09-17 20:55:46 +0000314 return nullptr;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000315 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000316
317 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000318 uint64_t SrcLen = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000319 if (SrcLen) {
320 annotateDereferenceableBytes(CI, 1, SrcLen);
321 --SrcLen; // Unbias length.
322 } else {
Chris Bienemanad070d02014-09-17 20:55:46 +0000323 return nullptr;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000324 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000325
Chris Bienemanad070d02014-09-17 20:55:46 +0000326 // strncat(x, "", c) -> x
David Bolvanskye80fcf02019-09-17 09:32:52 +0000327 if (SrcLen == 0)
Chris Bienemanad070d02014-09-17 20:55:46 +0000328 return Dst;
329
Sanjay Pateld707db92015-12-31 16:10:49 +0000330 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000331 if (Len < SrcLen)
332 return nullptr;
333
334 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000335 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000336 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
337}
338
339Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
340 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000341 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000342 Value *SrcStr = CI->getArgOperand(0);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000343 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000344
345 // If the second operand is non-constant, see if we can compute the length
346 // of the input string and turn this into memchr.
347 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
348 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000349 uint64_t Len = GetStringLength(SrcStr);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000350 if (Len)
351 annotateDereferenceableBytes(CI, 0, Len);
352 else
353 return nullptr;
354 if (!FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
Chris Bienemanad070d02014-09-17 20:55:46 +0000355 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000356
Sanjay Pateld3112a52016-01-19 19:46:10 +0000357 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000358 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
359 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000360 }
361
Chris Bienemanad070d02014-09-17 20:55:46 +0000362 // Otherwise, the character is a constant, see if the first argument is
363 // a string literal. If so, we can constant fold.
364 StringRef Str;
365 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000366 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000367 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000368 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000369 return nullptr;
370 }
371
372 // Compute the offset, make sure to handle the case when we're searching for
373 // zero (a weird way to spell strlen).
374 size_t I = (0xFF & CharC->getSExtValue()) == 0
375 ? Str.size()
376 : Str.find(CharC->getSExtValue());
377 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
378 return Constant::getNullValue(CI->getType());
379
380 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000381 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000382}
383
384Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000385 Value *SrcStr = CI->getArgOperand(0);
386 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000387 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000388
389 // Cannot fold anything if we're not looking for a constant.
390 if (!CharC)
391 return nullptr;
392
393 StringRef Str;
394 if (!getConstantStringInfo(SrcStr, Str)) {
395 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000397 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000398 return nullptr;
399 }
400
401 // Compute the offset.
402 size_t I = (0xFF & CharC->getSExtValue()) == 0
403 ? Str.size()
404 : Str.rfind(CharC->getSExtValue());
405 if (I == StringRef::npos) // Didn't find the char. Return null.
406 return Constant::getNullValue(CI->getType());
407
408 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000409 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000410}
411
412Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000413 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
414 if (Str1P == Str2P) // strcmp(x,x) -> 0
415 return ConstantInt::get(CI->getType(), 0);
416
417 StringRef Str1, Str2;
418 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
419 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
420
421 // strcmp(x, y) -> cnst (if both x and y are constant strings)
422 if (HasStr1 && HasStr2)
423 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
424
425 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000426 return B.CreateNeg(B.CreateZExt(
427 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000428
429 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000430 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
431 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000432
433 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000434 uint64_t Len1 = GetStringLength(Str1P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000435 if (Len1)
436 annotateDereferenceableBytes(CI, 0, Len1);
David Bolvansky1f343fa2018-05-22 20:27:36 +0000437 uint64_t Len2 = GetStringLength(Str2P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000438 if (Len2)
439 annotateDereferenceableBytes(CI, 1, Len2);
440
Chris Bienemanad070d02014-09-17 20:55:46 +0000441 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000442 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000443 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000444 std::min(Len1, Len2)),
445 B, DL, TLI);
446 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000447
David Bolvansky909889b2018-08-10 04:32:54 +0000448 // strcmp to memcmp
449 if (!HasStr1 && HasStr2) {
450 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
451 return emitMemCmp(
452 Str1P, Str2P,
453 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
454 TLI);
455 } else if (HasStr1 && !HasStr2) {
456 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
457 return emitMemCmp(
458 Str1P, Str2P,
459 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
460 TLI);
461 }
462
David Bolvanskye80fcf02019-09-17 09:32:52 +0000463 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000464 return nullptr;
465}
466
467Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
David Bolvanskye80fcf02019-09-17 09:32:52 +0000468 Value *Str1P = CI->getArgOperand(0);
469 Value *Str2P = CI->getArgOperand(1);
470 Value *Size = CI->getArgOperand(2);
Chris Bienemanad070d02014-09-17 20:55:46 +0000471 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
472 return ConstantInt::get(CI->getType(), 0);
473
David Bolvanskye80fcf02019-09-17 09:32:52 +0000474 if (isKnownNonZero(Size, DL))
475 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000476 // Get the length argument if it is constant.
477 uint64_t Length;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000478 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
Chris Bienemanad070d02014-09-17 20:55:46 +0000479 Length = LengthArg->getZExtValue();
480 else
481 return nullptr;
482
483 if (Length == 0) // strncmp(x,y,0) -> 0
484 return ConstantInt::get(CI->getType(), 0);
485
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
David Bolvanskye80fcf02019-09-17 09:32:52 +0000487 return emitMemCmp(Str1P, Str2P, Size, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000488
489 StringRef Str1, Str2;
490 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
491 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
492
493 // strncmp(x, y) -> cnst (if both x and y are constant strings)
494 if (HasStr1 && HasStr2) {
495 StringRef SubStr1 = Str1.substr(0, Length);
496 StringRef SubStr2 = Str2.substr(0, Length);
497 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
498 }
499
500 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000501 return B.CreateNeg(B.CreateZExt(
502 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000503
504 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000505 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
506 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000507
David Bolvansky909889b2018-08-10 04:32:54 +0000508 uint64_t Len1 = GetStringLength(Str1P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000509 if (Len1)
510 annotateDereferenceableBytes(CI, 0, Len1);
David Bolvansky909889b2018-08-10 04:32:54 +0000511 uint64_t Len2 = GetStringLength(Str2P);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000512 if (Len2)
513 annotateDereferenceableBytes(CI, 1, Len2);
David Bolvansky909889b2018-08-10 04:32:54 +0000514
515 // strncmp to memcmp
516 if (!HasStr1 && HasStr2) {
517 Len2 = std::min(Len2, Length);
518 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
519 return emitMemCmp(
520 Str1P, Str2P,
521 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
522 TLI);
523 } else if (HasStr1 && !HasStr2) {
524 Len1 = std::min(Len1, Length);
525 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
526 return emitMemCmp(
527 Str1P, Str2P,
528 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
529 TLI);
530 }
531
Chris Bienemanad070d02014-09-17 20:55:46 +0000532 return nullptr;
533}
534
David Bolvansky8d520162019-09-23 18:20:01 +0000535Value *LibCallSimplifier::optimizeStrNDup(CallInst *CI, IRBuilder<> &B) {
536 Value *Src = CI->getArgOperand(0);
537 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
538 uint64_t SrcLen = GetStringLength(Src);
539 if (SrcLen && Size) {
540 annotateDereferenceableBytes(CI, 0, SrcLen);
541 if (SrcLen <= Size->getZExtValue() + 1)
542 return emitStrDup(Src, B, TLI);
543 }
544
545 return nullptr;
546}
547
Chris Bienemanad070d02014-09-17 20:55:46 +0000548Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000549 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
550 if (Dst == Src) // strcpy(x,x) -> x
551 return Src;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000552
553 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +0000554 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000555 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000556 if (Len)
557 annotateDereferenceableBytes(CI, 1, Len);
558 else
Chris Bienemanad070d02014-09-17 20:55:46 +0000559 return nullptr;
560
561 // We have enough information to now generate the memcpy call to do the
562 // copy for us. Make a memcpy to copy the nul byte with align = 1.
David Bolvanskye80fcf02019-09-17 09:32:52 +0000563 CallInst *NewCI =
564 B.CreateMemCpy(Dst, 1, Src, 1,
565 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
566 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000567 return Dst;
568}
569
570Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
571 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000572 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
573 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000574 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000575 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000576 }
577
578 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000579 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000580 if (Len)
581 annotateDereferenceableBytes(CI, 1, Len);
582 else
Chris Bienemanad070d02014-09-17 20:55:46 +0000583 return nullptr;
584
Davide Italianob7487e62015-11-02 23:07:14 +0000585 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000587 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
588 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000589
590 // We have enough information to now generate the memcpy call to do the
591 // copy for us. Make a memcpy to copy the nul byte with align = 1.
David Bolvanskye80fcf02019-09-17 09:32:52 +0000592 CallInst *NewCI = B.CreateMemCpy(Dst, 1, Src, 1, LenV);
593 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000594 return DstEnd;
595}
596
597Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
598 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000599 Value *Dst = CI->getArgOperand(0);
600 Value *Src = CI->getArgOperand(1);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000601 Value *Size = CI->getArgOperand(2);
602 annotateNonNullBasedOnAccess(CI, 0);
603 if (isKnownNonZero(Size, DL))
604 annotateNonNullBasedOnAccess(CI, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000605
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 uint64_t Len;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000607 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(Size))
Chris Bienemanad070d02014-09-17 20:55:46 +0000608 Len = LengthArg->getZExtValue();
609 else
610 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000611
David Bolvanskye80fcf02019-09-17 09:32:52 +0000612 // strncpy(x, y, 0) -> x
Chris Bienemanad070d02014-09-17 20:55:46 +0000613 if (Len == 0)
David Bolvanskye80fcf02019-09-17 09:32:52 +0000614 return Dst;
615
616 // See if we can get the length of the input string.
617 uint64_t SrcLen = GetStringLength(Src);
618 if (SrcLen) {
619 annotateDereferenceableBytes(CI, 1, SrcLen);
620 --SrcLen; // Unbias length.
621 } else {
622 return nullptr;
623 }
624
625 if (SrcLen == 0) {
626 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
David Bolvansky0c0de792019-09-17 17:12:24 +0000627 CallInst *NewCI = B.CreateMemSet(Dst, B.getInt8('\0'), Size, 1);
628 AttrBuilder ArgAttrs(CI->getAttributes().getParamAttributes(0));
629 NewCI->setAttributes(NewCI->getAttributes().addParamAttributes(
630 CI->getContext(), 0, ArgAttrs));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000631 return Dst;
632 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000633
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 // Let strncpy handle the zero padding
635 if (Len > SrcLen + 1)
636 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000637
Davide Italianob7487e62015-11-02 23:07:14 +0000638 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000639 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
David Bolvanskye80fcf02019-09-17 09:32:52 +0000640 CallInst *NewCI = B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000641 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000642 return Dst;
643}
Meador Inge7fb2f732012-10-13 16:45:32 +0000644
Matthias Braun50ec0b52017-05-19 22:37:09 +0000645Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
646 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000647 Value *Src = CI->getArgOperand(0);
648
649 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000650 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000651 return ConstantInt::get(CI->getType(), Len - 1);
652
David L Kreitzer752c1442016-04-13 14:31:06 +0000653 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000654 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000655 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000656 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000657 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000658 // subtraction. This will make the optimization more complex, and it's not
659 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000660 // very uncommon.
661 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000662 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000663 return nullptr;
664
Matthias Braun50ec0b52017-05-19 22:37:09 +0000665 ConstantDataArraySlice Slice;
666 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
667 uint64_t NullTermIdx;
668 if (Slice.Array == nullptr) {
669 NullTermIdx = 0;
670 } else {
671 NullTermIdx = ~((uint64_t)0);
672 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
673 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
674 NullTermIdx = I;
675 break;
676 }
677 }
678 // If the string does not have '\0', leave it to strlen to compute
679 // its length.
680 if (NullTermIdx == ~((uint64_t)0))
681 return nullptr;
682 }
683
David L Kreitzer752c1442016-04-13 14:31:06 +0000684 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000685 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000686 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000687 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000688 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
689
Matthias Braun50ec0b52017-05-19 22:37:09 +0000690 // KnownZero's bits are flipped, so zeros in KnownZero now represent
691 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000692 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000693 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000694 // unsigned-less-than NullTermIdx.
695 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000696 // If Offset is not provably in the range [0, NullTermIdx], we can still
697 // optimize if we can prove that the program has undefined behavior when
698 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000699 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000700 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000701 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000702 NullTermIdx == ArrSize - 1)) {
703 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
704 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000705 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000706 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000707 }
708
709 return nullptr;
710 }
711
Chris Bienemanad070d02014-09-17 20:55:46 +0000712 // strlen(x?"foo":"bars") --> x ? 3 : 4
713 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000714 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
715 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000716 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000717 ORE.emit([&]() {
718 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
719 << "folded strlen(select) to select of constants";
720 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 return B.CreateSelect(SI->getCondition(),
722 ConstantInt::get(CI->getType(), LenTrue - 1),
723 ConstantInt::get(CI->getType(), LenFalse - 1));
724 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000725 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000726
Chris Bienemanad070d02014-09-17 20:55:46 +0000727 // strlen(x) != 0 --> *x != 0
728 // strlen(x) == 0 --> *x == 0
729 if (isOnlyUsedInZeroEqualityComparison(CI))
James Y Knight14359ef2019-02-01 20:44:24 +0000730 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"),
731 CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000732
Chris Bienemanad070d02014-09-17 20:55:46 +0000733 return nullptr;
734}
Meador Inge17418502012-10-13 16:45:37 +0000735
Matthias Braun50ec0b52017-05-19 22:37:09 +0000736Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
David Bolvanskye80fcf02019-09-17 09:32:52 +0000737 if (Value *V = optimizeStringLength(CI, B, 8))
738 return V;
739 annotateNonNullBasedOnAccess(CI, 0);
740 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000741}
742
743Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000744 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000745 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000746 // We cannot perform this optimization without wchar_size metadata.
747 if (WCharSize == 0)
748 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000749
750 return optimizeStringLength(CI, B, WCharSize);
751}
752
Chris Bienemanad070d02014-09-17 20:55:46 +0000753Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000754 StringRef S1, S2;
755 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
756 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000757
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000758 // strpbrk(s, "") -> nullptr
759 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000760 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
761 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000762
Chris Bienemanad070d02014-09-17 20:55:46 +0000763 // Constant folding.
764 if (HasS1 && HasS2) {
765 size_t I = S1.find_first_of(S2);
766 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000767 return Constant::getNullValue(CI->getType());
768
Sanjay Pateld707db92015-12-31 16:10:49 +0000769 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
770 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000771 }
Meador Inge17418502012-10-13 16:45:37 +0000772
Chris Bienemanad070d02014-09-17 20:55:46 +0000773 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000774 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000775 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000776
777 return nullptr;
778}
779
780Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000781 Value *EndPtr = CI->getArgOperand(1);
782 if (isa<ConstantPointerNull>(EndPtr)) {
783 // With a null EndPtr, this function won't capture the main argument.
784 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000785 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000786 }
787
788 return nullptr;
789}
790
791Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000792 StringRef S1, S2;
793 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
794 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
795
796 // strspn(s, "") -> 0
797 // strspn("", s) -> 0
798 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
799 return Constant::getNullValue(CI->getType());
800
801 // Constant folding.
802 if (HasS1 && HasS2) {
803 size_t Pos = S1.find_first_not_of(S2);
804 if (Pos == StringRef::npos)
805 Pos = S1.size();
806 return ConstantInt::get(CI->getType(), Pos);
807 }
808
809 return nullptr;
810}
811
812Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000813 StringRef S1, S2;
814 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
815 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
816
817 // strcspn("", s) -> 0
818 if (HasS1 && S1.empty())
819 return Constant::getNullValue(CI->getType());
820
821 // Constant folding.
822 if (HasS1 && HasS2) {
823 size_t Pos = S1.find_first_of(S2);
824 if (Pos == StringRef::npos)
825 Pos = S1.size();
826 return ConstantInt::get(CI->getType(), Pos);
827 }
828
829 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000830 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000831 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000832
833 return nullptr;
834}
835
836Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000837 // fold strstr(x, x) -> x.
838 if (CI->getArgOperand(0) == CI->getArgOperand(1))
839 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
840
841 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000842 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000843 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000844 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000845 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000846 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 StrLen, B, DL, TLI);
848 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000849 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000850 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
851 ICmpInst *Old = cast<ICmpInst>(*UI++);
852 Value *Cmp =
853 B.CreateICmp(Old->getPredicate(), StrNCmp,
854 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
855 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000856 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000857 return CI;
858 }
Meador Inge17418502012-10-13 16:45:37 +0000859
Chris Bienemanad070d02014-09-17 20:55:46 +0000860 // See if either input string is a constant string.
861 StringRef SearchStr, ToFindStr;
862 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
863 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
864
865 // fold strstr(x, "") -> x.
866 if (HasStr2 && ToFindStr.empty())
867 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
868
869 // If both strings are known, constant fold it.
870 if (HasStr1 && HasStr2) {
871 size_t Offset = SearchStr.find(ToFindStr);
872
873 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000874 return Constant::getNullValue(CI->getType());
875
Chris Bienemanad070d02014-09-17 20:55:46 +0000876 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000877 Value *Result = castToCStr(CI->getArgOperand(0), B);
James Y Knight77160752019-02-01 20:44:47 +0000878 Result =
879 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000880 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000881 }
Meador Inge17418502012-10-13 16:45:37 +0000882
Chris Bienemanad070d02014-09-17 20:55:46 +0000883 // fold strstr(x, "y") -> strchr(x, 'y').
884 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000885 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000886 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
887 }
David Bolvanskye80fcf02019-09-17 09:32:52 +0000888
889 annotateNonNullBasedOnAccess(CI, {0, 1});
890 return nullptr;
891}
892
893Value *LibCallSimplifier::optimizeMemRChr(CallInst *CI, IRBuilder<> &B) {
894 if (isKnownNonZero(CI->getOperand(2), DL))
895 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000896 return nullptr;
897}
Meador Inge40b6fac2012-10-15 03:47:37 +0000898
Benjamin Kramer691363e2015-03-21 15:36:21 +0000899Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000900 Value *SrcStr = CI->getArgOperand(0);
David Bolvanskye80fcf02019-09-17 09:32:52 +0000901 Value *Size = CI->getArgOperand(2);
902 annotateNonNullAndDereferenceable(CI, 0, Size, DL);
Benjamin Kramer691363e2015-03-21 15:36:21 +0000903 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
David Bolvanskye80fcf02019-09-17 09:32:52 +0000904 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
Benjamin Kramer691363e2015-03-21 15:36:21 +0000905
906 // memchr(x, y, 0) -> null
David Bolvansky39130312019-08-13 09:11:49 +0000907 if (LenC) {
908 if (LenC->isZero())
909 return Constant::getNullValue(CI->getType());
David Bolvanskye80fcf02019-09-17 09:32:52 +0000910 } else {
911 // From now on we need at least constant length and string.
912 return nullptr;
David Bolvansky39130312019-08-13 09:11:49 +0000913 }
David Bolvanskye80fcf02019-09-17 09:32:52 +0000914
Benjamin Kramer691363e2015-03-21 15:36:21 +0000915 StringRef Str;
David Bolvanskye80fcf02019-09-17 09:32:52 +0000916 if (!getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000917 return nullptr;
918
919 // Truncate the string to LenC. If Str is smaller than LenC we will still only
920 // scan the string, as reading past the end of it is undefined and we can just
921 // return null if we don't find the char.
922 Str = Str.substr(0, LenC->getZExtValue());
923
Benjamin Kramer7857d722015-03-21 21:09:33 +0000924 // If the char is variable but the input str and length are not we can turn
925 // this memchr call into a simple bit field test. Of course this only works
926 // when the return value is only checked against null.
927 //
928 // It would be really nice to reuse switch lowering here but we can't change
929 // the CFG at this point.
930 //
Fangrui Songf2609672019-03-12 10:31:52 +0000931 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
932 // != 0
Benjamin Kramer7857d722015-03-21 21:09:33 +0000933 // after bounds check.
934 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000935 unsigned char Max =
936 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
937 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000938
939 // Make sure the bit field we're about to create fits in a register on the
940 // target.
941 // FIXME: On a 64 bit architecture this prevents us from using the
942 // interesting range of alpha ascii chars. We could do better by emitting
943 // two bitfields or shifting the range by 64 if no lower chars are used.
944 if (!DL.fitsInLegalInteger(Max + 1))
945 return nullptr;
946
947 // For the bit field use a power-of-2 type with at least 8 bits to avoid
948 // creating unnecessary illegal types.
949 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
950
951 // Now build the bit field.
952 APInt Bitfield(Width, 0);
953 for (char C : Str)
954 Bitfield.setBit((unsigned char)C);
955 Value *BitfieldC = B.getInt(Bitfield);
956
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000957 // Adjust width of "C" to the bitfield width, then mask off the high bits.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000958 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000959 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
960
961 // First check that the bit field access is within bounds.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000962 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
963 "memchr.bounds");
964
965 // Create code that checks if the given bit is set in the field.
966 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
967 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
968
969 // Finally merge both checks and cast to pointer type. The inttoptr
970 // implicitly zexts the i1 to intptr type.
971 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
972 }
973
974 // Check if all arguments are constants. If so, we can constant fold.
975 if (!CharC)
976 return nullptr;
977
Benjamin Kramer691363e2015-03-21 15:36:21 +0000978 // Compute the offset.
979 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
980 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
981 return Constant::getNullValue(CI->getType());
982
983 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000984 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000985}
986
Clement Courbet8e16d732019-03-08 09:07:45 +0000987static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
988 uint64_t Len, IRBuilder<> &B,
989 const DataLayout &DL) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000990 if (Len == 0) // memcmp(s1,s2,0) -> 0
991 return Constant::getNullValue(CI->getType());
992
993 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
994 if (Len == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +0000995 Value *LHSV =
996 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
997 CI->getType(), "lhsv");
998 Value *RHSV =
999 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
1000 CI->getType(), "rhsv");
Chris Bienemanad070d02014-09-17 20:55:46 +00001001 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +00001002 }
Meador Inge40b6fac2012-10-15 03:47:37 +00001003
Chad Rosierdc655322015-08-28 18:30:18 +00001004 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +00001005 // TODO: The case where both inputs are constants does not need to be limited
1006 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +00001007 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +00001008 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
1009 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
1010
Sanjay Patel82ec8722017-08-21 19:13:14 +00001011 // First, see if we can fold either argument to a constant.
1012 Value *LHSV = nullptr;
1013 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
1014 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
1015 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
1016 }
1017 Value *RHSV = nullptr;
1018 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
1019 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
1020 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
1021 }
Chad Rosierdc655322015-08-28 18:30:18 +00001022
Sanjay Patel82ec8722017-08-21 19:13:14 +00001023 // Don't generate unaligned loads. If either source is constant data,
1024 // alignment doesn't matter for that source because there is no load.
1025 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
1026 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
1027 if (!LHSV) {
1028 Type *LHSPtrTy =
1029 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +00001030 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +00001031 }
1032 if (!RHSV) {
1033 Type *RHSPtrTy =
1034 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +00001035 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +00001036 }
Sanjay Patel7756edf2017-08-21 13:55:49 +00001037 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +00001038 }
Chad Rosierdc655322015-08-28 18:30:18 +00001039 }
1040
Sanjay Patel82ec8722017-08-21 19:13:14 +00001041 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
1042 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +00001043 StringRef LHSStr, RHSStr;
1044 if (getConstantStringInfo(LHS, LHSStr) &&
1045 getConstantStringInfo(RHS, RHSStr)) {
1046 // Make sure we're not reading out-of-bounds memory.
1047 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +00001048 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001049 // Fold the memcmp and normalize the result. This way we get consistent
1050 // results across multiple platforms.
1051 uint64_t Ret = 0;
1052 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1053 if (Cmp < 0)
1054 Ret = -1;
1055 else if (Cmp > 0)
1056 Ret = 1;
1057 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +00001058 }
David Bolvanskye80fcf02019-09-17 09:32:52 +00001059
Clement Courbet8e16d732019-03-08 09:07:45 +00001060 return nullptr;
1061}
1062
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001063// Most simplifications for memcmp also apply to bcmp.
1064Value *LibCallSimplifier::optimizeMemCmpBCmpCommon(CallInst *CI,
1065 IRBuilder<> &B) {
Clement Courbet8e16d732019-03-08 09:07:45 +00001066 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
1067 Value *Size = CI->getArgOperand(2);
1068
1069 if (LHS == RHS) // memcmp(s,s,x) -> 0
1070 return Constant::getNullValue(CI->getType());
1071
David Bolvanskye80fcf02019-09-17 09:32:52 +00001072 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
Clement Courbet8e16d732019-03-08 09:07:45 +00001073 // Handle constant lengths.
David Bolvanskye80fcf02019-09-17 09:32:52 +00001074 ConstantInt *LenC = dyn_cast<ConstantInt>(Size);
1075 if (!LenC)
1076 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001077
David Bolvanskye80fcf02019-09-17 09:32:52 +00001078 // memcmp(d,s,0) -> 0
1079 if (LenC->getZExtValue() == 0)
1080 return Constant::getNullValue(CI->getType());
1081
1082 if (Value *Res =
1083 optimizeMemCmpConstantSize(CI, LHS, RHS, LenC->getZExtValue(), B, DL))
1084 return Res;
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001085 return nullptr;
1086}
1087
1088Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
1089 if (Value *V = optimizeMemCmpBCmpCommon(CI, B))
1090 return V;
1091
Clement Courbet8e16d732019-03-08 09:07:45 +00001092 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
Evandro Menezes5cd5f9b2019-07-24 23:31:04 +00001093 // bcmp can be more efficient than memcmp because it only has to know that
1094 // there is a difference, not how different one is to the other.
1095 if (TLI->has(LibFunc_bcmp) && isOnlyUsedInZeroEqualityComparison(CI)) {
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001096 Value *LHS = CI->getArgOperand(0);
1097 Value *RHS = CI->getArgOperand(1);
1098 Value *Size = CI->getArgOperand(2);
Clement Courbet8e16d732019-03-08 09:07:45 +00001099 return emitBCmp(LHS, RHS, Size, B, DL, TLI);
1100 }
Meador Inge000dbcc2012-10-18 18:12:40 +00001101
Chris Bienemanad070d02014-09-17 20:55:46 +00001102 return nullptr;
1103}
Meador Inge9a6a1902012-10-31 00:20:56 +00001104
Clement Courbet9e1f2a72019-05-06 09:15:22 +00001105Value *LibCallSimplifier::optimizeBCmp(CallInst *CI, IRBuilder<> &B) {
1106 return optimizeMemCmpBCmpCommon(CI, B);
1107}
1108
David Bolvanskye80fcf02019-09-17 09:32:52 +00001109Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
David Bolvansky39130312019-08-13 09:11:49 +00001110 Value *Size = CI->getArgOperand(2);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001111 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1112 if (isa<IntrinsicInst>(CI))
David Bolvansky39130312019-08-13 09:11:49 +00001113 return nullptr;
1114
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001115 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
David Bolvanskye80fcf02019-09-17 09:32:52 +00001116 CallInst *NewCI =
1117 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size);
1118 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001119 return CI->getArgOperand(0);
1120}
Meador Inge05a625a2012-10-31 14:58:26 +00001121
David Bolvanskyff0ad3c2019-08-31 18:19:05 +00001122Value *LibCallSimplifier::optimizeMemPCpy(CallInst *CI, IRBuilder<> &B) {
1123 Value *Dst = CI->getArgOperand(0);
1124 Value *N = CI->getArgOperand(2);
1125 // mempcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n), x + n
1126 CallInst *NewCI = B.CreateMemCpy(Dst, 1, CI->getArgOperand(1), 1, N);
1127 NewCI->setAttributes(CI->getAttributes());
1128 return B.CreateInBoundsGEP(B.getInt8Ty(), Dst, N);
1129}
1130
David Bolvanskye80fcf02019-09-17 09:32:52 +00001131Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
David Bolvansky39130312019-08-13 09:11:49 +00001132 Value *Size = CI->getArgOperand(2);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001133 annotateNonNullAndDereferenceable(CI, {0, 1}, Size, DL);
1134 if (isa<IntrinsicInst>(CI))
David Bolvansky39130312019-08-13 09:11:49 +00001135 return nullptr;
1136
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001137 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
David Bolvanskye80fcf02019-09-17 09:32:52 +00001138 CallInst *NewCI =
1139 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, Size);
1140 NewCI->setAttributes(CI->getAttributes());
1141 return CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001142}
Meador Ingebcd88ef72012-11-10 15:16:48 +00001143
Sanjay Patel980b2802016-01-26 16:17:24 +00001144/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +00001145Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00001146 // This has to be a memset of zeros (bzero).
1147 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
1148 if (!FillValue || FillValue->getZExtValue() != 0)
1149 return nullptr;
1150
1151 // TODO: We should handle the case where the malloc has more than one use.
1152 // This is necessary to optimize common patterns such as when the result of
1153 // the malloc is checked against null or when a memset intrinsic is used in
1154 // place of a memset library call.
1155 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
1156 if (!Malloc || !Malloc->hasOneUse())
1157 return nullptr;
1158
1159 // Is the inner call really malloc()?
1160 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +00001161 if (!InnerCallee)
1162 return nullptr;
1163
David L. Jonesd21529f2017-01-23 23:16:46 +00001164 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +00001165 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +00001166 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +00001167 return nullptr;
1168
Sanjay Patel980b2802016-01-26 16:17:24 +00001169 // The memset must cover the same number of bytes that are malloc'd.
1170 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
1171 return nullptr;
1172
1173 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +00001174 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +00001175 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
1176 const DataLayout &DL = Malloc->getModule()->getDataLayout();
1177 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
Evandro Menezes7d677ad2019-09-06 22:07:11 +00001178 if (Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
1179 Malloc->getArgOperand(0),
1180 Malloc->getAttributes(), B, *TLI)) {
1181 substituteInParent(Malloc, Calloc);
1182 return Calloc;
1183 }
Sanjay Patel980b2802016-01-26 16:17:24 +00001184
Evandro Menezes7d677ad2019-09-06 22:07:11 +00001185 return nullptr;
Sanjay Patel980b2802016-01-26 16:17:24 +00001186}
1187
David Bolvanskye80fcf02019-09-17 09:32:52 +00001188Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
David Bolvansky39130312019-08-13 09:11:49 +00001189 Value *Size = CI->getArgOperand(2);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001190 annotateNonNullAndDereferenceable(CI, 0, Size, DL);
1191 if (isa<IntrinsicInst>(CI))
David Bolvansky39130312019-08-13 09:11:49 +00001192 return nullptr;
1193
Amara Emerson54f60252018-10-11 14:51:11 +00001194 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +00001195 return Calloc;
1196
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001197 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +00001198 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
David Bolvanskye80fcf02019-09-17 09:32:52 +00001199 CallInst *NewCI = B.CreateMemSet(CI->getArgOperand(0), Val, Size, 1);
1200 NewCI->setAttributes(CI->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001201 return CI->getArgOperand(0);
1202}
Meador Inged4825782012-11-11 06:49:03 +00001203
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00001204Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
1205 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1206 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1207
1208 return nullptr;
1209}
1210
Meador Inge193e0352012-11-13 04:16:17 +00001211//===----------------------------------------------------------------------===//
1212// Math Library Optimizations
1213//===----------------------------------------------------------------------===//
1214
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001215// Replace a libcall \p CI with a call to intrinsic \p IID
1216static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1217 // Propagate fast-math flags from the existing call to the new call.
1218 IRBuilder<>::FastMathFlagGuard Guard(B);
1219 B.setFastMathFlags(CI->getFastMathFlags());
1220
1221 Module *M = CI->getModule();
1222 Value *V = CI->getArgOperand(0);
1223 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1224 CallInst *NewCall = B.CreateCall(F, V);
1225 NewCall->takeName(CI);
1226 return NewCall;
1227}
1228
Matthias Braund34e4d22014-12-03 21:46:33 +00001229/// Return a variant of Val with float type.
1230/// Currently this works in two cases: If Val is an FPExtension of a float
1231/// value to something bigger, simply return the operand.
1232/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1233/// loss of precision do so.
1234static Value *valueHasFloatPrecision(Value *Val) {
1235 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1236 Value *Op = Cast->getOperand(0);
1237 if (Op->getType()->isFloatTy())
1238 return Op;
1239 }
1240 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1241 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001242 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001243 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001244 &losesInfo);
1245 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001246 return ConstantFP::get(Const->getContext(), F);
1247 }
1248 return nullptr;
1249}
1250
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001251/// Shrink double -> float functions.
1252static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001253 bool isBinary, bool isPrecise = false) {
Simon Pilgrim364ef5d2019-05-06 19:51:54 +00001254 Function *CalleeFn = CI->getCalledFunction();
1255 if (!CI->getType()->isDoubleTy() || !CalleeFn)
Chris Bienemanad070d02014-09-17 20:55:46 +00001256 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001257
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001258 // If not all the uses of the function are converted to float, then bail out.
1259 // This matters if the precision of the result is more important than the
1260 // precision of the arguments.
1261 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001262 for (User *U : CI->users()) {
1263 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1264 if (!Cast || !Cast->getType()->isFloatTy())
1265 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001266 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001267
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001268 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1269 Value *V[2];
1270 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1271 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1272 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001273 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001274
Andrew Ng1606fc02017-04-25 12:36:14 +00001275 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001276 // same name as the float version of this call, otherwise the result is an
1277 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001278 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001279 // float expf(float val) { return (float) exp((double) val); }
Sanjay Pateld46bf632019-09-18 14:33:40 +00001280 StringRef CalleeName = CalleeFn->getName();
1281 bool IsIntrinsic = CalleeFn->isIntrinsic();
1282 if (!IsIntrinsic) {
1283 StringRef CallerName = CI->getFunction()->getName();
1284 if (!CallerName.empty() && CallerName.back() == 'f' &&
1285 CallerName.size() == (CalleeName.size() + 1) &&
1286 CallerName.startswith(CalleeName))
Andrew Ng1606fc02017-04-25 12:36:14 +00001287 return nullptr;
1288 }
1289
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001290 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001291 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001292 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001293
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001294 // g((double) float) -> (double) gf(float)
1295 Value *R;
Sanjay Pateld46bf632019-09-18 14:33:40 +00001296 if (IsIntrinsic) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001297 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001298 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1299 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1300 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Pateld46bf632019-09-18 14:33:40 +00001301 } else {
1302 AttributeList CalleeAttrs = CalleeFn->getAttributes();
1303 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeName, B, CalleeAttrs)
1304 : emitUnaryFloatFnCall(V[0], CalleeName, B, CalleeAttrs);
Sanjay Patel848309d2014-10-23 21:52:45 +00001305 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001306 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001307}
Meador Inge193e0352012-11-13 04:16:17 +00001308
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001309/// Shrink double -> float for unary functions.
1310static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001311 bool isPrecise = false) {
1312 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001313}
1314
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001315/// Shrink double -> float for binary functions.
1316static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001317 bool isPrecise = false) {
1318 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001319}
1320
Hal Finkel2ff24732017-12-16 01:26:25 +00001321// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1322Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1323 if (!CI->isFast())
1324 return nullptr;
1325
1326 // Propagate fast-math flags from the existing call to new instructions.
1327 IRBuilder<>::FastMathFlagGuard Guard(B);
1328 B.setFastMathFlags(CI->getFastMathFlags());
1329
1330 Value *Real, *Imag;
1331 if (CI->getNumArgOperands() == 1) {
1332 Value *Op = CI->getArgOperand(0);
1333 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1334 Real = B.CreateExtractValue(Op, 0, "real");
1335 Imag = B.CreateExtractValue(Op, 1, "imag");
1336 } else {
1337 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1338 Real = CI->getArgOperand(0);
1339 Imag = CI->getArgOperand(1);
1340 }
1341
1342 Value *RealReal = B.CreateFMul(Real, Real);
1343 Value *ImagImag = B.CreateFMul(Imag, Imag);
1344
1345 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1346 CI->getType());
1347 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1348}
1349
Sanjay Patele45a83d2018-08-13 19:24:41 +00001350static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1351 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001352 if (!isa<FPMathOperator>(Call))
1353 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001354
Sanjay Patel15bff182018-08-13 21:49:19 +00001355 IRBuilder<>::FastMathFlagGuard Guard(B);
1356 B.setFastMathFlags(Call->getFastMathFlags());
Clement Courbet8e16d732019-03-08 09:07:45 +00001357
Sanjay Patele45a83d2018-08-13 19:24:41 +00001358 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001359 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001360 switch (Func) {
1361 case LibFunc_sin:
1362 case LibFunc_sinf:
1363 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001364 case LibFunc_tan:
1365 case LibFunc_tanf:
1366 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001367 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001368 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001369 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001370 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001371 break;
1372 case LibFunc_cos:
1373 case LibFunc_cosf:
1374 case LibFunc_cosl:
1375 // cos(-X) --> cos(X)
1376 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1377 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1378 break;
1379 default:
1380 break;
1381 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001382 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001383}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001384
Weiming Zhao82130722015-12-04 22:00:47 +00001385static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1386 // Multiplications calculated using Addition Chains.
1387 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1388
1389 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1390
1391 if (InnerChain[Exp])
1392 return InnerChain[Exp];
1393
1394 static const unsigned AddChain[33][2] = {
1395 {0, 0}, // Unused.
1396 {0, 0}, // Unused (base case = pow1).
1397 {1, 1}, // Unused (pre-computed).
1398 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1399 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1400 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1401 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1402 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1403 };
1404
1405 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1406 getPow(InnerChain, AddChain[Exp][1], B));
1407 return InnerChain[Exp];
1408}
1409
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001410// Return a properly extended 32-bit integer if the operation is an itofp.
1411static Value *getIntToFPVal(Value *I2F, IRBuilder<> &B) {
1412 if (isa<SIToFPInst>(I2F) || isa<UIToFPInst>(I2F)) {
1413 Value *Op = cast<Instruction>(I2F)->getOperand(0);
1414 // Make sure that the exponent fits inside an int32_t,
1415 // thus avoiding any range issues that FP has not.
1416 unsigned BitWidth = Op->getType()->getPrimitiveSizeInBits();
1417 if (BitWidth < 32 ||
1418 (BitWidth == 32 && isa<SIToFPInst>(I2F)))
1419 return isa<SIToFPInst>(I2F) ? B.CreateSExt(Op, B.getInt32Ty())
1420 : B.CreateZExt(Op, B.getInt32Ty());
1421 }
1422
1423 return nullptr;
1424}
1425
Evandro Menezes4b390102018-08-17 17:59:53 +00001426/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001427/// ldexp(1.0, x) for pow(2.0, itofp(x)); exp2(n * x) for pow(2.0 ** n, x);
1428/// exp10(x) for pow(10.0, x); exp2(log2(n) * x) for pow(n, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001429Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1430 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1431 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1432 Module *Mod = Pow->getModule();
1433 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001434 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001435
1436 // Evaluate special cases related to a nested function as the base.
1437
1438 // pow(exp(x), y) -> exp(x * y)
1439 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001440 // If exp{,2}() is used only once, it is better to fold two transcendental
1441 // math functions into one. If used again, exp{,2}() would still have to be
1442 // called with the original argument, then keep both original transcendental
1443 // functions. However, this transformation is only safe with fully relaxed
1444 // math semantics, since, besides rounding differences, it changes overflow
1445 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001446 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1447 // Whereas:
1448 // exp(1000 * 0.001) = exp(1)
1449 // TODO: Loosen the requirement for fully relaxed math semantics.
1450 // TODO: Handle exp10() when more targets have it available.
1451 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001452 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001453 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001454
Evandro Menezes4b390102018-08-17 17:59:53 +00001455 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001456 if (CalleeFn &&
1457 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1458 StringRef ExpName;
1459 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001460 Value *ExpFn;
Evandro Menezes110b1132019-09-30 20:52:21 +00001461 LibFunc LibFnFloat, LibFnDouble, LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001462
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001463 switch (LibFn) {
1464 default:
1465 return nullptr;
1466 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001467 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001468 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001469 LibFnFloat = LibFunc_expf;
1470 LibFnDouble = LibFunc_exp;
1471 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001472 break;
1473 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001474 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001475 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001476 LibFnFloat = LibFunc_exp2f;
1477 LibFnDouble = LibFunc_exp2;
1478 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001479 break;
1480 }
1481
Evandro Menezes253991c2018-08-27 22:11:15 +00001482 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001483 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001484 ExpFn = BaseFn->doesNotAccessMemory()
1485 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1486 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001487 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1488 LibFnLongDouble, B,
1489 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001490
1491 // Since the new exp{,2}() is different from the original one, dead code
1492 // elimination cannot be trusted to remove it, since it may have side
1493 // effects (e.g., errno). When the only consumer for the original
1494 // exp{,2}() is pow(), then it has to be explicitly erased.
Evandro Menezes7d677ad2019-09-06 22:07:11 +00001495 substituteInParent(BaseFn, ExpFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001496 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001497 }
1498 }
1499
1500 // Evaluate special cases related to a constant base.
1501
Evandro Menezes2123ea72018-08-30 19:04:51 +00001502 const APFloat *BaseF;
1503 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1504 return nullptr;
1505
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001506 // pow(2.0, itofp(x)) -> ldexp(1.0, x)
1507 if (match(Base, m_SpecificFP(2.0)) &&
1508 (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo)) &&
1509 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
1510 if (Value *ExpoI = getIntToFPVal(Expo, B))
1511 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), ExpoI, TLI,
1512 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1513 B, Attrs);
1514 }
1515
Evandro Menezes2123ea72018-08-30 19:04:51 +00001516 // pow(2.0 ** n, x) -> exp2(n * x)
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001517 if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
Evandro Menezes2123ea72018-08-30 19:04:51 +00001518 APFloat BaseR = APFloat(1.0);
1519 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1520 BaseR = BaseR / *BaseF;
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001521 bool IsInteger = BaseF->isInteger(), IsReciprocal = BaseR.isInteger();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001522 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1523 APSInt NI(64, false);
1524 if ((IsInteger || IsReciprocal) &&
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001525 NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) ==
1526 APFloat::opOK &&
Evandro Menezes2123ea72018-08-30 19:04:51 +00001527 NI > 1 && NI.isPowerOf2()) {
1528 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1529 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1530 if (Pow->doesNotAccessMemory())
1531 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1532 FMul, "exp2");
1533 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001534 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1535 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001536 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001537 }
1538
1539 // pow(10.0, x) -> exp10(x)
1540 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1541 if (match(Base, m_SpecificFP(10.0)) &&
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001542 hasFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001543 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1544 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001545
Evandro Menezesb2169262019-07-12 00:33:49 +00001546 // pow(n, x) -> exp2(log2(n) * x)
David Bolvansky0735cc12019-07-10 14:43:27 +00001547 if (Pow->hasOneUse() && Pow->hasApproxFunc() && Pow->hasNoNaNs() &&
1548 Pow->hasNoInfs() && BaseF->isNormal() && !BaseF->isNegative()) {
1549 Value *Log = nullptr;
1550 if (Ty->isFloatTy())
1551 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToFloat()));
1552 else if (Ty->isDoubleTy())
1553 Log = ConstantFP::get(Ty, std::log2(BaseF->convertToDouble()));
1554
1555 if (Log) {
1556 Value *FMul = B.CreateFMul(Log, Expo, "mul");
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001557 if (Pow->doesNotAccessMemory())
David Bolvansky0735cc12019-07-10 14:43:27 +00001558 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1559 FMul, "exp2");
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001560 else if (hasFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l))
1561 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1562 LibFunc_exp2l, B, Attrs);
David Bolvansky0735cc12019-07-10 14:43:27 +00001563 }
1564 }
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001565
Evandro Menezes4b390102018-08-17 17:59:53 +00001566 return nullptr;
1567}
1568
Florian Hahncc9dc592018-09-03 17:37:39 +00001569static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1570 Module *M, IRBuilder<> &B,
1571 const TargetLibraryInfo *TLI) {
1572 // If errno is never set, then use the intrinsic for sqrt().
1573 if (NoErrno) {
1574 Function *SqrtFn =
1575 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1576 return B.CreateCall(SqrtFn, V, "sqrt");
1577 }
1578
1579 // Otherwise, use the libcall for sqrt().
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001580 if (hasFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf, LibFunc_sqrtl))
Florian Hahncc9dc592018-09-03 17:37:39 +00001581 // TODO: We also should check that the target can in fact lower the sqrt()
1582 // libcall. We currently have no way to ask this question, so we ask if
1583 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001584 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1585 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001586
1587 return nullptr;
1588}
1589
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001590/// Use square root in place of pow(x, +/-0.5).
1591Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001592 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001593 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1594 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001595 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001596
Evandro Menezesa7d48282018-07-30 16:20:04 +00001597 const APFloat *ExpoF;
1598 if (!match(Expo, m_APFloat(ExpoF)) ||
1599 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1600 return nullptr;
1601
Florian Hahncc9dc592018-09-03 17:37:39 +00001602 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1603 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001604 return nullptr;
1605
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001606 // Handle signed zero base by expanding to fabs(sqrt(x)).
1607 if (!Pow->hasNoSignedZeros()) {
1608 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1609 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1610 }
1611
1612 // Handle non finite base by expanding to
1613 // (x == -infinity ? +infinity : sqrt(x)).
1614 if (!Pow->hasNoInfs()) {
1615 Value *PosInf = ConstantFP::getInfinity(Ty),
1616 *NegInf = ConstantFP::getInfinity(Ty, true);
1617 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1618 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1619 }
1620
Evandro Menezes61e4e402018-07-31 22:11:02 +00001621 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001622 if (ExpoF->isNegative())
1623 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001624
1625 return Sqrt;
1626}
1627
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001628static Value *createPowWithIntegerExponent(Value *Base, Value *Expo, Module *M,
1629 IRBuilder<> &B) {
1630 Value *Args[] = {Base, Expo};
1631 Function *F = Intrinsic::getDeclaration(M, Intrinsic::powi, Base->getType());
1632 return B.CreateCall(F, Args);
1633}
1634
Evandro Menezesa7d48282018-07-30 16:20:04 +00001635Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001636 Value *Base = Pow->getArgOperand(0);
1637 Value *Expo = Pow->getArgOperand(1);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001638 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001639 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001640 Type *Ty = Pow->getType();
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001641 Module *M = Pow->getModule();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001642 Value *Shrunk = nullptr;
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001643 bool AllowApprox = Pow->hasApproxFunc();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001644 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001645
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001646 // Bail out if simplifying libcalls to pow() is disabled.
Evandro Menezesc6c00cd2019-08-09 16:04:18 +00001647 if (!hasFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001648 return nullptr;
1649
Evandro Menezes61e4e402018-07-31 22:11:02 +00001650 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001651 IRBuilder<>::FastMathFlagGuard Guard(B);
1652 B.setFastMathFlags(Pow->getFastMathFlags());
1653
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001654 // Shrink pow() to powf() if the arguments are single precision,
1655 // unless the result is expected to be double precision.
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001656 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_pow) &&
1657 hasFloatVersion(Name))
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001658 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1659
Evandro Menezesa7d48282018-07-30 16:20:04 +00001660 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001661
1662 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001663 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001664 return Base;
1665
David Bolvanskye23be092019-07-11 10:55:04 +00001666 if (Value *Exp = replacePowWithExp(Pow, B))
1667 return Exp;
1668
Evandro Menezesa7d48282018-07-30 16:20:04 +00001669 // Evaluate special cases related to the exponent.
1670
Evandro Menezesa7d48282018-07-30 16:20:04 +00001671 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001672 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001673 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1674
Sanjay Patel4f0e4292019-09-06 16:10:18 +00001675 // pow(x, +/-0.0) -> 1.0
1676 if (match(Expo, m_AnyZeroFP()))
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001677 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001678
1679 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001680 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001681 return Base;
1682
1683 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001684 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001685 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001686
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001687 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1688 return Sqrt;
1689
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001690 // pow(x, n) -> x * x * x * ...
1691 const APFloat *ExpoF;
Evandro Menezesb2169262019-07-12 00:33:49 +00001692 if (AllowApprox && match(Expo, m_APFloat(ExpoF))) {
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001693 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001694 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1695 // additional fmul.
1696 // TODO: This whole transformation should be backend specific (e.g. some
1697 // backends might prefer libcalls or the limit for the exponent might
1698 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001699 APFloat LimF(ExpoF->getSemantics(), 33.0),
1700 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001701 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1702 // This transformation applies to integer or integer+0.5 exponents only.
1703 // For integer+0.5, we create a sqrt(Base) call.
1704 Value *Sqrt = nullptr;
1705 if (!ExpoA.isInteger()) {
1706 APFloat Expo2 = ExpoA;
1707 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1708 // is no floating point exception and the result is an integer, then
1709 // ExpoA == integer + 0.5
1710 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1711 return nullptr;
1712
1713 if (!Expo2.isInteger())
1714 return nullptr;
1715
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001716 Sqrt = getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1717 Pow->doesNotAccessMemory(), M, B, TLI);
Florian Hahncc9dc592018-09-03 17:37:39 +00001718 }
1719
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001720 // We will memoize intermediate products of the Addition Chain.
1721 Value *InnerChain[33] = {nullptr};
1722 InnerChain[1] = Base;
1723 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001724
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001725 // We cannot readily convert a non-double type (like float) to a double.
1726 // So we first convert it to something which could be converted to double.
1727 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1728 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001729
Florian Hahncc9dc592018-09-03 17:37:39 +00001730 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1731 if (Sqrt)
1732 FMul = B.CreateFMul(FMul, Sqrt);
1733
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001734 // If the exponent is negative, then get the reciprocal.
1735 if (ExpoF->isNegative())
1736 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001737
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001738 return FMul;
1739 }
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001740
1741 APSInt IntExpo(32, /*isUnsigned=*/false);
Evandro Menezesb2169262019-07-12 00:33:49 +00001742 // powf(x, n) -> powi(x, n) if n is a constant signed integer value
David Bolvansky10ee3ac2019-07-02 21:16:34 +00001743 if (ExpoF->isInteger() &&
1744 ExpoF->convertToInteger(IntExpo, APFloat::rmTowardZero, &Ignored) ==
1745 APFloat::opOK) {
David Bolvanskycb1a5a72019-07-02 15:58:45 +00001746 return createPowWithIntegerExponent(
1747 Base, ConstantInt::get(B.getInt32Ty(), IntExpo), M, B);
1748 }
Weiming Zhao82130722015-12-04 22:00:47 +00001749 }
1750
Evandro Menezesb2169262019-07-12 00:33:49 +00001751 // powf(x, itofp(y)) -> powi(x, y)
1752 if (AllowApprox && (isa<SIToFPInst>(Expo) || isa<UIToFPInst>(Expo))) {
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001753 if (Value *ExpoI = getIntToFPVal(Expo, B))
1754 return createPowWithIntegerExponent(Base, ExpoI, M, B);
Evandro Menezesb2169262019-07-12 00:33:49 +00001755 }
1756
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001757 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001758}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001759
Chris Bienemanad070d02014-09-17 20:55:46 +00001760Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1761 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001762 StringRef Name = Callee->getName();
Evandro Menezes59fbe512019-08-09 17:22:56 +00001763 Value *Ret = nullptr;
1764 if (UnsafeFPShrink && Name == TLI->getName(LibFunc_exp2) &&
1765 hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001766 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001767
Evandro Menezes59fbe512019-08-09 17:22:56 +00001768 Type *Ty = CI->getType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 Value *Op = CI->getArgOperand(0);
Evandro Menezes59fbe512019-08-09 17:22:56 +00001770
Chris Bienemanad070d02014-09-17 20:55:46 +00001771 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1772 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Evandro Menezes59fbe512019-08-09 17:22:56 +00001773 if ((isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) &&
1774 hasFloatFn(TLI, Ty, LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl)) {
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001775 if (Value *Exp = getIntToFPVal(Op, B))
Evandro Menezes59fbe512019-08-09 17:22:56 +00001776 return emitBinaryFloatFnCall(ConstantFP::get(Ty, 1.0), Exp, TLI,
1777 LibFunc_ldexp, LibFunc_ldexpf, LibFunc_ldexpl,
1778 B, CI->getCalledFunction()->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001779 }
Evandro Menezes05e9c2a2019-08-16 15:33:41 +00001780
Chris Bienemanad070d02014-09-17 20:55:46 +00001781 return Ret;
1782}
1783
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001784Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1785 // If we can shrink the call to a float function rather than a double
1786 // function, do that first.
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001787 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001788 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001789 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1790 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001791 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001792
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001793 // The LLVM intrinsics minnum/maxnum correspond to fmin/fmax. Canonicalize to
1794 // the intrinsics for improved optimization (for example, vectorization).
1795 // No-signed-zeros is implied by the definitions of fmax/fmin themselves.
1796 // From the C standard draft WG14/N1256:
1797 // "Ideally, fmax would be sensitive to the sign of zero, for example
1798 // fmax(-0.0, +0.0) would return +0; however, implementation in software
1799 // might be impractical."
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001800 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001801 FastMathFlags FMF = CI->getFastMathFlags();
1802 FMF.setNoSignedZeros();
Sanjay Patela2528152016-01-12 18:03:37 +00001803 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001804
Sanjay Patel77dc1e82019-06-29 14:28:54 +00001805 Intrinsic::ID IID = Callee->getName().startswith("fmin") ? Intrinsic::minnum
1806 : Intrinsic::maxnum;
1807 Function *F = Intrinsic::getDeclaration(CI->getModule(), IID, CI->getType());
1808 return B.CreateCall(F, { CI->getArgOperand(0), CI->getArgOperand(1) });
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001809}
1810
Evandro Menezes110b1132019-09-30 20:52:21 +00001811Value *LibCallSimplifier::optimizeLog(CallInst *Log, IRBuilder<> &B) {
1812 Function *LogFn = Log->getCalledFunction();
1813 AttributeList Attrs = LogFn->getAttributes();
1814 StringRef LogNm = LogFn->getName();
1815 Intrinsic::ID LogID = LogFn->getIntrinsicID();
1816 Module *Mod = Log->getModule();
1817 Type *Ty = Log->getType();
Davide Italianob8b71332015-11-29 20:58:04 +00001818 Value *Ret = nullptr;
Davide Italianob8b71332015-11-29 20:58:04 +00001819
Evandro Menezes110b1132019-09-30 20:52:21 +00001820 if (UnsafeFPShrink && hasFloatVersion(LogNm))
1821 Ret = optimizeUnaryDoubleFP(Log, B, true);
Sanjay Patele896ede2016-01-11 23:31:48 +00001822
Sanjay Patel629c4112017-11-06 16:27:15 +00001823 // The earlier call must also be 'fast' in order to do these transforms.
Evandro Menezes110b1132019-09-30 20:52:21 +00001824 CallInst *Arg = dyn_cast<CallInst>(Log->getArgOperand(0));
1825 if (!Log->isFast() || !Arg || !Arg->isFast() || !Arg->hasOneUse())
Davide Italianob8b71332015-11-29 20:58:04 +00001826 return Ret;
1827
Evandro Menezes110b1132019-09-30 20:52:21 +00001828 LibFunc LogLb, ExpLb, Exp2Lb, Exp10Lb, PowLb;
1829
1830 // This is only applicable to log(), log2(), log10().
1831 if (TLI->getLibFunc(LogNm, LogLb))
1832 switch (LogLb) {
1833 case LibFunc_logf:
1834 LogID = Intrinsic::log;
1835 ExpLb = LibFunc_expf;
1836 Exp2Lb = LibFunc_exp2f;
1837 Exp10Lb = LibFunc_exp10f;
1838 PowLb = LibFunc_powf;
1839 break;
1840 case LibFunc_log:
1841 LogID = Intrinsic::log;
1842 ExpLb = LibFunc_exp;
1843 Exp2Lb = LibFunc_exp2;
1844 Exp10Lb = LibFunc_exp10;
1845 PowLb = LibFunc_pow;
1846 break;
1847 case LibFunc_logl:
1848 LogID = Intrinsic::log;
1849 ExpLb = LibFunc_expl;
1850 Exp2Lb = LibFunc_exp2l;
1851 Exp10Lb = LibFunc_exp10l;
1852 PowLb = LibFunc_powl;
1853 break;
1854 case LibFunc_log2f:
1855 LogID = Intrinsic::log2;
1856 ExpLb = LibFunc_expf;
1857 Exp2Lb = LibFunc_exp2f;
1858 Exp10Lb = LibFunc_exp10f;
1859 PowLb = LibFunc_powf;
1860 break;
1861 case LibFunc_log2:
1862 LogID = Intrinsic::log2;
1863 ExpLb = LibFunc_exp;
1864 Exp2Lb = LibFunc_exp2;
1865 Exp10Lb = LibFunc_exp10;
1866 PowLb = LibFunc_pow;
1867 break;
1868 case LibFunc_log2l:
1869 LogID = Intrinsic::log2;
1870 ExpLb = LibFunc_expl;
1871 Exp2Lb = LibFunc_exp2l;
1872 Exp10Lb = LibFunc_exp10l;
1873 PowLb = LibFunc_powl;
1874 break;
1875 case LibFunc_log10f:
1876 LogID = Intrinsic::log10;
1877 ExpLb = LibFunc_expf;
1878 Exp2Lb = LibFunc_exp2f;
1879 Exp10Lb = LibFunc_exp10f;
1880 PowLb = LibFunc_powf;
1881 break;
1882 case LibFunc_log10:
1883 LogID = Intrinsic::log10;
1884 ExpLb = LibFunc_exp;
1885 Exp2Lb = LibFunc_exp2;
1886 Exp10Lb = LibFunc_exp10;
1887 PowLb = LibFunc_pow;
1888 break;
1889 case LibFunc_log10l:
1890 LogID = Intrinsic::log10;
1891 ExpLb = LibFunc_expl;
1892 Exp2Lb = LibFunc_exp2l;
1893 Exp10Lb = LibFunc_exp10l;
1894 PowLb = LibFunc_powl;
1895 break;
1896 default:
1897 return Ret;
1898 }
1899 else if (LogID == Intrinsic::log || LogID == Intrinsic::log2 ||
1900 LogID == Intrinsic::log10) {
1901 if (Ty->getScalarType()->isFloatTy()) {
1902 ExpLb = LibFunc_expf;
1903 Exp2Lb = LibFunc_exp2f;
1904 Exp10Lb = LibFunc_exp10f;
1905 PowLb = LibFunc_powf;
1906 } else if (Ty->getScalarType()->isDoubleTy()) {
1907 ExpLb = LibFunc_exp;
1908 Exp2Lb = LibFunc_exp2;
1909 Exp10Lb = LibFunc_exp10;
1910 PowLb = LibFunc_pow;
1911 } else
1912 return Ret;
1913 } else
Davide Italianob8b71332015-11-29 20:58:04 +00001914 return Ret;
1915
1916 IRBuilder<>::FastMathFlagGuard Guard(B);
Evandro Menezes110b1132019-09-30 20:52:21 +00001917 B.setFastMathFlags(FastMathFlags::getFast());
Davide Italianob8b71332015-11-29 20:58:04 +00001918
Evandro Menezes110b1132019-09-30 20:52:21 +00001919 Function *ArgFn = Arg->getCalledFunction();
1920 StringRef ArgNm = ArgFn->getName();
1921 Intrinsic::ID ArgID = ArgFn->getIntrinsicID();
1922 LibFunc ArgLb = NotLibFunc;
1923 TLI->getLibFunc(ArgNm, ArgLb);
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001924
Evandro Menezes110b1132019-09-30 20:52:21 +00001925 // log(pow(x,y)) -> y*log(x)
1926 if (ArgLb == PowLb || ArgID == Intrinsic::pow) {
1927 Value *LogX =
1928 Log->doesNotAccessMemory()
1929 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
1930 Arg->getOperand(0), "log")
1931 : emitUnaryFloatFnCall(Arg->getOperand(0), LogNm, B, Attrs);
1932 Value *MulY = B.CreateFMul(Arg->getArgOperand(1), LogX, "mul");
1933 // Since pow() may have side effects, e.g. errno,
1934 // dead code elimination may not be trusted to remove it.
1935 substituteInParent(Arg, MulY);
1936 return MulY;
1937 }
1938 // log(exp{,2,10}(y)) -> y*log({e,2,10})
1939 // TODO: There is no exp10() intrinsic yet.
1940 else if (ArgLb == ExpLb || ArgLb == Exp2Lb || ArgLb == Exp10Lb ||
1941 ArgID == Intrinsic::exp || ArgID == Intrinsic::exp2) {
1942 Constant *Eul;
1943 if (ArgLb == ExpLb || ArgID == Intrinsic::exp)
Evandro Menezes41ead422019-09-30 23:21:02 +00001944 // FIXME: The Euler number should be M_E, but it's place of definition
1945 // is not quite standard.
1946 Eul = ConstantFP::get(Log->getType(), 2.7182818284590452354);
Evandro Menezes110b1132019-09-30 20:52:21 +00001947 else if (ArgLb == Exp2Lb || ArgID == Intrinsic::exp2)
1948 Eul = ConstantFP::get(Log->getType(), 2.0);
1949 else
1950 Eul = ConstantFP::get(Log->getType(), 10.0);
1951 Value *LogE = Log->doesNotAccessMemory()
1952 ? B.CreateCall(Intrinsic::getDeclaration(Mod, LogID, Ty),
1953 Eul, "log")
1954 : emitUnaryFloatFnCall(Eul, LogNm, B, Attrs);
1955 Value *MulY = B.CreateFMul(Arg->getArgOperand(0), LogE, "mul");
1956 // Since exp() may have side effects, e.g. errno,
1957 // dead code elimination may not be trusted to remove it.
1958 substituteInParent(Arg, MulY);
1959 return MulY;
1960 }
1961
Davide Italianob8b71332015-11-29 20:58:04 +00001962 return Ret;
1963}
1964
Sanjay Patelc699a612014-10-16 18:48:17 +00001965Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1966 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001967 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001968 // TODO: Once we have a way (other than checking for the existince of the
1969 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1970 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001971 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001972 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001973 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001974
Sanjay Patel629c4112017-11-06 16:27:15 +00001975 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001976 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001977
Sanjay Patelc2d64612016-01-06 20:52:21 +00001978 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001979 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001980 return Ret;
1981
1982 // We're looking for a repeated factor in a multiplication tree,
1983 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001984 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001985 Value *Op0 = I->getOperand(0);
1986 Value *Op1 = I->getOperand(1);
1987 Value *RepeatOp = nullptr;
1988 Value *OtherOp = nullptr;
1989 if (Op0 == Op1) {
1990 // Simple match: the operands of the multiply are identical.
1991 RepeatOp = Op0;
1992 } else {
1993 // Look for a more complicated pattern: one of the operands is itself
1994 // a multiply, so search for a common factor in that multiply.
1995 // Note: We don't bother looking any deeper than this first level or for
1996 // variations of this pattern because instcombine's visitFMUL and/or the
1997 // reassociation pass should give us this form.
1998 Value *OtherMul0, *OtherMul1;
1999 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
2000 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00002001 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00002002 // Matched: sqrt((x * x) * z)
2003 RepeatOp = OtherMul0;
2004 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00002005 }
2006 }
2007 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00002008 if (!RepeatOp)
2009 return Ret;
2010
2011 // Fast math flags for any created instructions should match the sqrt
2012 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00002013 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00002014 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00002015
Sanjay Patelc2d64612016-01-06 20:52:21 +00002016 // If we found a repeated factor, hoist it out of the square root and
2017 // replace it with the fabs of that factor.
2018 Module *M = Callee->getParent();
2019 Type *ArgType = I->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00002020 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00002021 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
2022 if (OtherOp) {
2023 // If we found a non-repeated factor, we still need to get its square
2024 // root. We then multiply that by the value that was simplified out
2025 // of the square root calculation.
James Y Knight7976eb52019-02-01 20:43:25 +00002026 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00002027 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
2028 return B.CreateFMul(FabsCall, SqrtCall);
2029 }
2030 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00002031}
2032
Sanjay Patelcddcd722016-01-06 19:23:35 +00002033// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00002034Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
2035 Function *Callee = CI->getCalledFunction();
2036 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00002037 StringRef Name = Callee->getName();
2038 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00002039 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00002040
Davide Italiano51507d22015-11-04 23:36:56 +00002041 Value *Op1 = CI->getArgOperand(0);
2042 auto *OpC = dyn_cast<CallInst>(Op1);
2043 if (!OpC)
2044 return Ret;
2045
Sanjay Patel629c4112017-11-06 16:27:15 +00002046 // Both calls must be 'fast' in order to remove them.
2047 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00002048 return Ret;
2049
Davide Italiano51507d22015-11-04 23:36:56 +00002050 // tan(atan(x)) -> x
2051 // tanf(atanf(x)) -> x
2052 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00002053 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00002054 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00002055 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00002056 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
2057 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
2058 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00002059 Ret = OpC->getArgOperand(0);
2060 return Ret;
2061}
2062
Sanjay Patel57747212016-01-21 23:38:43 +00002063static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00002064 // We can only hope to do anything useful if we can ignore things like errno
2065 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002066 // We already checked the prototype.
2067 return CI->hasFnAttr(Attribute::NoUnwind) &&
2068 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00002069}
2070
Chris Bienemanad070d02014-09-17 20:55:46 +00002071static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
2072 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00002073 Value *&SinCos) {
2074 Type *ArgTy = Arg->getType();
2075 Type *ResTy;
2076 StringRef Name;
2077
2078 Triple T(OrigCallee->getParent()->getTargetTriple());
2079 if (UseFloat) {
2080 Name = "__sincospif_stret";
2081
2082 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
2083 // x86_64 can't use {float, float} since that would be returned in both
2084 // xmm0 and xmm1, which isn't what a real struct would do.
2085 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00002086 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
2087 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00002088 } else {
2089 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00002090 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00002091 }
2092
2093 Module *M = OrigCallee->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002094 FunctionCallee Callee =
2095 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00002096
2097 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
2098 // If the argument is an instruction, it must dominate all uses so put our
2099 // sincos call there.
2100 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
2101 } else {
2102 // Otherwise (e.g. for a constant) the beginning of the function is as
2103 // good a place as any.
2104 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
2105 B.SetInsertPoint(&EntryBB, EntryBB.begin());
2106 }
2107
2108 SinCos = B.CreateCall(Callee, Arg, "sincospi");
2109
2110 if (SinCos->getType()->isStructTy()) {
2111 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
2112 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
2113 } else {
2114 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
2115 "sinpi");
2116 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
2117 "cospi");
2118 }
2119}
Chris Bienemanad070d02014-09-17 20:55:46 +00002120
2121Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002122 // Make sure the prototype is as expected, otherwise the rest of the
2123 // function is probably invalid and likely to abort.
2124 if (!isTrigLibCall(CI))
2125 return nullptr;
2126
2127 Value *Arg = CI->getArgOperand(0);
2128 SmallVector<CallInst *, 1> SinCalls;
2129 SmallVector<CallInst *, 1> CosCalls;
2130 SmallVector<CallInst *, 1> SinCosCalls;
2131
2132 bool IsFloat = Arg->getType()->isFloatTy();
2133
2134 // Look for all compatible sinpi, cospi and sincospi calls with the same
2135 // argument. If there are enough (in some sense) we can make the
2136 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00002137 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002138 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00002139 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00002140
2141 // It's only worthwhile if both sinpi and cospi are actually used.
2142 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
2143 return nullptr;
2144
2145 Value *Sin, *Cos, *SinCos;
2146 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
2147
Davide Italianof024a562016-12-16 02:28:38 +00002148 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
2149 Value *Res) {
2150 for (CallInst *C : Calls)
2151 replaceAllUsesWith(C, Res);
2152 };
2153
Chris Bienemanad070d02014-09-17 20:55:46 +00002154 replaceTrigInsts(SinCalls, Sin);
2155 replaceTrigInsts(CosCalls, Cos);
2156 replaceTrigInsts(SinCosCalls, SinCos);
2157
2158 return nullptr;
2159}
2160
David Majnemerabae6b52016-03-19 04:53:02 +00002161void LibCallSimplifier::classifyArgUse(
2162 Value *Val, Function *F, bool IsFloat,
2163 SmallVectorImpl<CallInst *> &SinCalls,
2164 SmallVectorImpl<CallInst *> &CosCalls,
2165 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002166 CallInst *CI = dyn_cast<CallInst>(Val);
2167
2168 if (!CI)
2169 return;
2170
David Majnemerabae6b52016-03-19 04:53:02 +00002171 // Don't consider calls in other functions.
2172 if (CI->getFunction() != F)
2173 return;
2174
Chris Bienemanad070d02014-09-17 20:55:46 +00002175 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00002176 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00002177 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00002178 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00002179 return;
2180
2181 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002182 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00002183 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002184 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00002185 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002186 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00002187 SinCosCalls.push_back(CI);
2188 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00002189 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00002190 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002191 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00002192 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00002193 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00002194 SinCosCalls.push_back(CI);
2195 }
2196}
2197
Meador Inge7415f842012-11-25 20:45:27 +00002198//===----------------------------------------------------------------------===//
2199// Integer Library Call Optimizations
2200//===----------------------------------------------------------------------===//
2201
Chris Bienemanad070d02014-09-17 20:55:46 +00002202Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002203 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00002204 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002205 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00002206 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2207 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00002208 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00002209 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
2210 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00002211
Chris Bienemanad070d02014-09-17 20:55:46 +00002212 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
2213 return B.CreateSelect(Cond, V, B.getInt32(0));
2214}
Meador Ingea0b6d872012-11-26 00:24:07 +00002215
Davide Italiano85ad36b2016-12-15 23:45:11 +00002216Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
2217 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
2218 Value *Op = CI->getArgOperand(0);
2219 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00002220 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
2221 Intrinsic::ctlz, ArgType);
Davide Italiano85ad36b2016-12-15 23:45:11 +00002222 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
2223 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
2224 V);
2225 return B.CreateIntCast(V, CI->getType(), false);
2226}
2227
Chris Bienemanad070d02014-09-17 20:55:46 +00002228Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00002229 // abs(x) -> x <s 0 ? -x : x
2230 // The negation has 'nsw' because abs of INT_MIN is undefined.
2231 Value *X = CI->getArgOperand(0);
2232 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
2233 Value *NegX = B.CreateNSWNeg(X, "neg");
2234 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00002235}
Meador Inge9a59ab62012-11-26 02:31:59 +00002236
Chris Bienemanad070d02014-09-17 20:55:46 +00002237Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002238 // isdigit(c) -> (c-'0') <u 10
2239 Value *Op = CI->getArgOperand(0);
2240 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
2241 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
2242 return B.CreateZExt(Op, CI->getType());
2243}
Meador Ingea62a39e2012-11-26 03:10:07 +00002244
Chris Bienemanad070d02014-09-17 20:55:46 +00002245Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002246 // isascii(c) -> c <u 128
2247 Value *Op = CI->getArgOperand(0);
2248 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
2249 return B.CreateZExt(Op, CI->getType());
2250}
2251
2252Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002253 // toascii(c) -> c & 0x7f
2254 return B.CreateAnd(CI->getArgOperand(0),
2255 ConstantInt::get(CI->getType(), 0x7F));
2256}
Meador Inge604937d2012-11-26 03:38:52 +00002257
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002258Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
2259 StringRef Str;
2260 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2261 return nullptr;
2262
2263 return convertStrToNumber(CI, Str, 10);
2264}
2265
2266Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
2267 StringRef Str;
2268 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2269 return nullptr;
2270
2271 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
2272 return nullptr;
2273
2274 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
2275 return convertStrToNumber(CI, Str, CInt->getSExtValue());
2276 }
2277
2278 return nullptr;
2279}
2280
Meador Inge08ca1152012-11-26 20:37:20 +00002281//===----------------------------------------------------------------------===//
2282// Formatting and IO Library Call Optimizations
2283//===----------------------------------------------------------------------===//
2284
Chris Bienemanad070d02014-09-17 20:55:46 +00002285static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00002286
Chris Bienemanad070d02014-09-17 20:55:46 +00002287Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
2288 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00002289 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002290 // Error reporting calls should be cold, mark them as such.
2291 // This applies even to non-builtin calls: it is only a hint and applies to
2292 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002293
Chris Bienemanad070d02014-09-17 20:55:46 +00002294 // This heuristic was suggested in:
2295 // Improving Static Branch Prediction in a Compiler
2296 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
2297 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00002298 if (!CI->hasFnAttr(Attribute::Cold) &&
2299 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00002300 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00002301 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00002302
Chris Bienemanad070d02014-09-17 20:55:46 +00002303 return nullptr;
2304}
2305
2306static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00002307 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00002308 return false;
2309
2310 if (StreamArg < 0)
2311 return true;
2312
2313 // These functions might be considered cold, but only if their stream
2314 // argument is stderr.
2315
2316 if (StreamArg >= (int)CI->getNumArgOperands())
2317 return false;
2318 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
2319 if (!LI)
2320 return false;
2321 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
2322 if (!GV || !GV->isDeclaration())
2323 return false;
2324 return GV->getName() == "stderr";
2325}
2326
2327Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
2328 // Check for a fixed format string.
2329 StringRef FormatStr;
2330 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002331 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00002332
Chris Bienemanad070d02014-09-17 20:55:46 +00002333 // Empty format string -> noop.
2334 if (FormatStr.empty()) // Tolerate printf's declared void.
2335 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00002336
Chris Bienemanad070d02014-09-17 20:55:46 +00002337 // Do not do any of the following transformations if the printf return value
2338 // is used, in general the printf return value is not compatible with either
2339 // putchar() or puts().
2340 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00002341 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00002342
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00002343 // printf("x") -> putchar('x'), even for "%" and "%%".
2344 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00002345 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00002346
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002347 // printf("%s", "a") --> putchar('a')
2348 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
2349 StringRef ChrStr;
2350 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
2351 return nullptr;
2352 if (ChrStr.size() != 1)
2353 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00002354 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002355 }
2356
Chris Bienemanad070d02014-09-17 20:55:46 +00002357 // printf("foo\n") --> puts("foo")
2358 if (FormatStr[FormatStr.size() - 1] == '\n' &&
2359 FormatStr.find('%') == StringRef::npos) { // No format characters.
2360 // Create a string literal with no \n on it. We expect the constant merge
2361 // pass to be run after this pass, to merge duplicate strings.
2362 FormatStr = FormatStr.drop_back();
2363 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00002364 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002365 }
Meador Inge08ca1152012-11-26 20:37:20 +00002366
Chris Bienemanad070d02014-09-17 20:55:46 +00002367 // Optimize specific format strings.
2368 // printf("%c", chr) --> putchar(chr)
2369 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002370 CI->getArgOperand(1)->getType()->isIntegerTy())
2371 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002372
2373 // printf("%s\n", str) --> puts(str)
2374 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002375 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002376 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002377 return nullptr;
2378}
2379
2380Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2381
2382 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002383 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002384 if (Value *V = optimizePrintFString(CI, B)) {
2385 return V;
2386 }
2387
2388 // printf(format, ...) -> iprintf(format, ...) if no floating point
2389 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002390 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002391 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002392 FunctionCallee IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002393 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002394 CallInst *New = cast<CallInst>(CI->clone());
2395 New->setCalledFunction(IPrintFFn);
2396 B.Insert(New);
2397 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002398 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002399
2400 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2401 // arguments.
2402 if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) {
2403 Module *M = B.GetInsertBlock()->getParent()->getParent();
2404 auto SmallPrintFFn =
2405 M->getOrInsertFunction(TLI->getName(LibFunc_small_printf),
2406 FT, Callee->getAttributes());
2407 CallInst *New = cast<CallInst>(CI->clone());
2408 New->setCalledFunction(SmallPrintFFn);
2409 B.Insert(New);
2410 return New;
2411 }
2412
David Bolvanskye80fcf02019-09-17 09:32:52 +00002413 annotateNonNullBasedOnAccess(CI, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002414 return nullptr;
2415}
Meador Inge08ca1152012-11-26 20:37:20 +00002416
Chris Bienemanad070d02014-09-17 20:55:46 +00002417Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2418 // Check for a fixed format string.
2419 StringRef FormatStr;
David Bolvansky40375822019-10-01 13:19:04 +00002420 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002421 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002422
Chris Bienemanad070d02014-09-17 20:55:46 +00002423 // If we just have a format string (nothing else crazy) transform it.
2424 if (CI->getNumArgOperands() == 2) {
2425 // Make sure there's no % in the constant array. We could try to handle
2426 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002427 if (FormatStr.find('%') != StringRef::npos)
2428 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002429
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002430 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
David Bolvansky40375822019-10-01 13:19:04 +00002431 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2432 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2433 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002434 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002435 }
Meador Ingef8e72502012-11-29 15:45:43 +00002436
Chris Bienemanad070d02014-09-17 20:55:46 +00002437 // The remaining optimizations require the format string to be "%s" or "%c"
2438 // and have an extra operand.
2439 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2440 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002441 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002442
Chris Bienemanad070d02014-09-17 20:55:46 +00002443 // Decode the second character of the format string.
2444 if (FormatStr[1] == 'c') {
2445 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
David Bolvansky40375822019-10-01 13:19:04 +00002446 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00002447 return nullptr;
David Bolvansky40375822019-10-01 13:19:04 +00002448 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
2449 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002450 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002451 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002452 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002453
Chris Bienemanad070d02014-09-17 20:55:46 +00002454 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002455 }
2456
Chris Bienemanad070d02014-09-17 20:55:46 +00002457 if (FormatStr[1] == 's') {
Fangrui Songf2609672019-03-12 10:31:52 +00002458 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2459 // strlen(str)+1)
David Bolvansky40375822019-10-01 13:19:04 +00002460 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2461 return nullptr;
2462
2463 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002464 if (!Len)
2465 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002466 Value *IncLen =
2467 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
David Bolvansky40375822019-10-01 13:19:04 +00002468 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002469
2470 // The sprintf result is the unincremented number of bytes in the string.
2471 return B.CreateIntCast(Len, CI->getType(), false);
2472 }
2473 return nullptr;
2474}
2475
2476Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2477 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002478 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002479 if (Value *V = optimizeSPrintFString(CI, B)) {
2480 return V;
2481 }
2482
2483 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2484 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002486 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002487 FunctionCallee SIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002488 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2489 CallInst *New = cast<CallInst>(CI->clone());
2490 New->setCalledFunction(SIPrintFFn);
2491 B.Insert(New);
2492 return New;
2493 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002494
2495 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2496 // floating point arguments.
2497 if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) {
2498 Module *M = B.GetInsertBlock()->getParent()->getParent();
2499 auto SmallSPrintFFn =
2500 M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf),
2501 FT, Callee->getAttributes());
2502 CallInst *New = cast<CallInst>(CI->clone());
2503 New->setCalledFunction(SmallSPrintFFn);
2504 B.Insert(New);
2505 return New;
2506 }
2507
David Bolvanskye80fcf02019-09-17 09:32:52 +00002508 annotateNonNullBasedOnAccess(CI, {0, 1});
Chris Bienemanad070d02014-09-17 20:55:46 +00002509 return nullptr;
2510}
2511
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002512Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002513 // Check for size
2514 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2515 if (!Size)
2516 return nullptr;
2517
2518 uint64_t N = Size->getZExtValue();
David Bolvanskye80fcf02019-09-17 09:32:52 +00002519 // Check for a fixed format string.
2520 StringRef FormatStr;
2521 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2522 return nullptr;
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002523
2524 // If we just have a format string (nothing else crazy) transform it.
2525 if (CI->getNumArgOperands() == 3) {
2526 // Make sure there's no % in the constant array. We could try to handle
2527 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002528 if (FormatStr.find('%') != StringRef::npos)
2529 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002530
2531 if (N == 0)
2532 return ConstantInt::get(CI->getType(), FormatStr.size());
2533 else if (N < FormatStr.size() + 1)
2534 return nullptr;
2535
Fangrui Songf2609672019-03-12 10:31:52 +00002536 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002537 // strlen(fmt)+1)
2538 B.CreateMemCpy(
2539 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2540 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2541 FormatStr.size() + 1)); // Copy the null byte.
2542 return ConstantInt::get(CI->getType(), FormatStr.size());
2543 }
2544
2545 // The remaining optimizations require the format string to be "%s" or "%c"
2546 // and have an extra operand.
2547 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2548 CI->getNumArgOperands() == 4) {
2549
2550 // Decode the second character of the format string.
2551 if (FormatStr[1] == 'c') {
2552 if (N == 0)
2553 return ConstantInt::get(CI->getType(), 1);
2554 else if (N == 1)
2555 return nullptr;
2556
2557 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2558 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2559 return nullptr;
2560 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2561 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2562 B.CreateStore(V, Ptr);
2563 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2564 B.CreateStore(B.getInt8(0), Ptr);
2565
2566 return ConstantInt::get(CI->getType(), 1);
2567 }
2568
2569 if (FormatStr[1] == 's') {
2570 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2571 StringRef Str;
2572 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2573 return nullptr;
2574
2575 if (N == 0)
2576 return ConstantInt::get(CI->getType(), Str.size());
2577 else if (N < Str.size() + 1)
2578 return nullptr;
2579
2580 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2581 ConstantInt::get(CI->getType(), Str.size() + 1));
2582
2583 // The snprintf result is the unincremented number of bytes in the string.
2584 return ConstantInt::get(CI->getType(), Str.size());
2585 }
2586 }
2587 return nullptr;
2588}
2589
2590Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2591 if (Value *V = optimizeSnPrintFString(CI, B)) {
2592 return V;
2593 }
2594
David Bolvanskye80fcf02019-09-17 09:32:52 +00002595 if (isKnownNonZero(CI->getOperand(1), DL))
2596 annotateNonNullBasedOnAccess(CI, 0);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002597 return nullptr;
2598}
2599
Chris Bienemanad070d02014-09-17 20:55:46 +00002600Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2601 optimizeErrorReporting(CI, B, 0);
2602
2603 // All the optimizations depend on the format string.
2604 StringRef FormatStr;
2605 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2606 return nullptr;
2607
2608 // Do not do any of the following transformations if the fprintf return
2609 // value is used, in general the fprintf return value is not compatible
2610 // with fwrite(), fputc() or fputs().
2611 if (!CI->use_empty())
2612 return nullptr;
2613
2614 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2615 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002616 // Could handle %% -> % if we cared.
2617 if (FormatStr.find('%') != StringRef::npos)
2618 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002619
Sanjay Pateld3112a52016-01-19 19:46:10 +00002620 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002621 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002622 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002623 CI->getArgOperand(0), B, DL, TLI);
2624 }
2625
2626 // The remaining optimizations require the format string to be "%s" or "%c"
2627 // and have an extra operand.
2628 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2629 CI->getNumArgOperands() < 3)
2630 return nullptr;
2631
2632 // Decode the second character of the format string.
2633 if (FormatStr[1] == 'c') {
2634 // fprintf(F, "%c", chr) --> fputc(chr, F)
2635 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2636 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002637 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002638 }
2639
2640 if (FormatStr[1] == 's') {
2641 // fprintf(F, "%s", str) --> fputs(str, F)
2642 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2643 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002644 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002645 }
2646 return nullptr;
2647}
2648
2649Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2650 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002651 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002652 if (Value *V = optimizeFPrintFString(CI, B)) {
2653 return V;
2654 }
2655
2656 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2657 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002658 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002659 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002660 FunctionCallee FIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002661 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2662 CallInst *New = cast<CallInst>(CI->clone());
2663 New->setCalledFunction(FIPrintFFn);
2664 B.Insert(New);
2665 return New;
2666 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002667
2668 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2669 // 128-bit floating point arguments.
2670 if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) {
2671 Module *M = B.GetInsertBlock()->getParent()->getParent();
2672 auto SmallFPrintFFn =
2673 M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf),
2674 FT, Callee->getAttributes());
2675 CallInst *New = cast<CallInst>(CI->clone());
2676 New->setCalledFunction(SmallFPrintFFn);
2677 B.Insert(New);
2678 return New;
2679 }
2680
Chris Bienemanad070d02014-09-17 20:55:46 +00002681 return nullptr;
2682}
2683
2684Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2685 optimizeErrorReporting(CI, B, 3);
2686
Chris Bienemanad070d02014-09-17 20:55:46 +00002687 // Get the element size and count.
2688 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2689 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002690 if (SizeC && CountC) {
2691 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002692
David Bolvanskyca22d422018-05-16 11:39:52 +00002693 // If this is writing zero records, remove the call (it's a noop).
2694 if (Bytes == 0)
2695 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002696
David Bolvanskyca22d422018-05-16 11:39:52 +00002697 // If this is writing one byte, turn it into fputc.
2698 // This optimisation is only valid, if the return value is unused.
2699 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
James Y Knight14359ef2019-02-01 20:44:24 +00002700 Value *Char = B.CreateLoad(B.getInt8Ty(),
2701 castToCStr(CI->getArgOperand(0), B), "char");
David Bolvanskyca22d422018-05-16 11:39:52 +00002702 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2703 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2704 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002705 }
2706
David Bolvanskyca22d422018-05-16 11:39:52 +00002707 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2708 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2709 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2710 TLI);
2711
Chris Bienemanad070d02014-09-17 20:55:46 +00002712 return nullptr;
2713}
2714
2715Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2716 optimizeErrorReporting(CI, B, 1);
2717
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002718 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2719 // requires more arguments and thus extra MOVs are required.
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002720 bool OptForSize = CI->getFunction()->hasOptSize() ||
2721 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
2722 if (OptForSize)
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002723 return nullptr;
2724
David Bolvanskyca22d422018-05-16 11:39:52 +00002725 // Check if has any use
2726 if (!CI->use_empty()) {
2727 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2728 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2729 TLI);
2730 else
2731 // We can't optimize if return value is used.
2732 return nullptr;
2733 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002734
Fangrui Songf2609672019-03-12 10:31:52 +00002735 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002736 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002737 if (!Len)
2738 return nullptr;
2739
2740 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002741 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002742 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002743 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002744 CI->getArgOperand(1), B, DL, TLI);
2745}
2746
David Bolvanskyca22d422018-05-16 11:39:52 +00002747Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2748 optimizeErrorReporting(CI, B, 1);
2749
2750 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2751 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2752 TLI);
2753
2754 return nullptr;
2755}
2756
2757Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2758 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2759 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2760
2761 return nullptr;
2762}
2763
2764Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2765 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2766 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2767 CI->getArgOperand(2), B, TLI);
2768
2769 return nullptr;
2770}
2771
2772Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2773 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2774 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2775 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2776 TLI);
2777
2778 return nullptr;
2779}
2780
Chris Bienemanad070d02014-09-17 20:55:46 +00002781Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
David Bolvanskye80fcf02019-09-17 09:32:52 +00002782 annotateNonNullBasedOnAccess(CI, 0);
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002783 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00002784 return nullptr;
2785
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002786 // Check for a constant string.
2787 // puts("") -> putchar('\n')
2788 StringRef Str;
2789 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2790 return emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002791
2792 return nullptr;
2793}
2794
David Bolvansky6b4502962019-10-02 22:49:20 +00002795Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilder<> &B) {
2796 // bcopy(src, dst, n) -> llvm.memmove(dst, src, n)
2797 return B.CreateMemMove(CI->getArgOperand(1), 1, CI->getArgOperand(0), 1,
2798 CI->getArgOperand(2));
2799}
2800
Chris Bienemanad070d02014-09-17 20:55:46 +00002801bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002802 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002803 SmallString<20> FloatFuncName = FuncName;
2804 FloatFuncName += 'f';
2805 if (TLI->getLibFunc(FloatFuncName, Func))
2806 return TLI->has(Func);
2807 return false;
2808}
Meador Inge7fb2f732012-10-13 16:45:32 +00002809
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002810Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2811 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002812 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002813 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002814 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002815 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002816 // Make sure we never change the calling convention.
2817 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002818 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002819 "Optimizing string/memory libcall would change the calling convention");
2820 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002821 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002822 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002823 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002824 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002825 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002826 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002827 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002828 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002829 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002830 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002831 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002832 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002833 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002834 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002835 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002836 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002837 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002838 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002839 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002840 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002841 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002842 return optimizeStrPBrk(CI, Builder);
David Bolvansky8d520162019-09-23 18:20:01 +00002843 case LibFunc_strndup:
2844 return optimizeStrNDup(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002845 case LibFunc_strtol:
2846 case LibFunc_strtod:
2847 case LibFunc_strtof:
2848 case LibFunc_strtoul:
2849 case LibFunc_strtoll:
2850 case LibFunc_strtold:
2851 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002852 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002853 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002854 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002855 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002856 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002857 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002858 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002859 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002860 return optimizeMemChr(CI, Builder);
David Bolvanskye80fcf02019-09-17 09:32:52 +00002861 case LibFunc_memrchr:
2862 return optimizeMemRChr(CI, Builder);
Clement Courbet9e1f2a72019-05-06 09:15:22 +00002863 case LibFunc_bcmp:
2864 return optimizeBCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002865 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002866 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002867 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002868 return optimizeMemCpy(CI, Builder);
David Bolvanskyff0ad3c2019-08-31 18:19:05 +00002869 case LibFunc_mempcpy:
2870 return optimizeMemPCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002871 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002872 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002873 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002874 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002875 case LibFunc_realloc:
2876 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002877 case LibFunc_wcslen:
2878 return optimizeWcslen(CI, Builder);
David Bolvansky6b4502962019-10-02 22:49:20 +00002879 case LibFunc_bcopy:
2880 return optimizeBCopy(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002881 default:
2882 break;
2883 }
2884 }
2885 return nullptr;
2886}
2887
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002888Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2889 LibFunc Func,
2890 IRBuilder<> &Builder) {
2891 // Don't optimize calls that require strict floating point semantics.
2892 if (CI->isStrictFP())
2893 return nullptr;
2894
Sanjay Patele45a83d2018-08-13 19:24:41 +00002895 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2896 return V;
2897
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002898 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002899 case LibFunc_sinpif:
2900 case LibFunc_sinpi:
2901 case LibFunc_cospif:
2902 case LibFunc_cospi:
2903 return optimizeSinCosPi(CI, Builder);
2904 case LibFunc_powf:
2905 case LibFunc_pow:
2906 case LibFunc_powl:
2907 return optimizePow(CI, Builder);
2908 case LibFunc_exp2l:
2909 case LibFunc_exp2:
2910 case LibFunc_exp2f:
2911 return optimizeExp2(CI, Builder);
2912 case LibFunc_fabsf:
2913 case LibFunc_fabs:
2914 case LibFunc_fabsl:
2915 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2916 case LibFunc_sqrtf:
2917 case LibFunc_sqrt:
2918 case LibFunc_sqrtl:
2919 return optimizeSqrt(CI, Builder);
Evandro Menezes110b1132019-09-30 20:52:21 +00002920 case LibFunc_logf:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002921 case LibFunc_log:
Evandro Menezes110b1132019-09-30 20:52:21 +00002922 case LibFunc_logl:
2923 case LibFunc_log10f:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002924 case LibFunc_log10:
Evandro Menezes110b1132019-09-30 20:52:21 +00002925 case LibFunc_log10l:
2926 case LibFunc_log1pf:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002927 case LibFunc_log1p:
Evandro Menezes110b1132019-09-30 20:52:21 +00002928 case LibFunc_log1pl:
2929 case LibFunc_log2f:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002930 case LibFunc_log2:
Evandro Menezes110b1132019-09-30 20:52:21 +00002931 case LibFunc_log2l:
2932 case LibFunc_logbf:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002933 case LibFunc_logb:
Evandro Menezes110b1132019-09-30 20:52:21 +00002934 case LibFunc_logbl:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002935 return optimizeLog(CI, Builder);
2936 case LibFunc_tan:
2937 case LibFunc_tanf:
2938 case LibFunc_tanl:
2939 return optimizeTan(CI, Builder);
2940 case LibFunc_ceil:
2941 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2942 case LibFunc_floor:
2943 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2944 case LibFunc_round:
2945 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2946 case LibFunc_nearbyint:
2947 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2948 case LibFunc_rint:
2949 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2950 case LibFunc_trunc:
2951 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2952 case LibFunc_acos:
2953 case LibFunc_acosh:
2954 case LibFunc_asin:
2955 case LibFunc_asinh:
2956 case LibFunc_atan:
2957 case LibFunc_atanh:
2958 case LibFunc_cbrt:
2959 case LibFunc_cosh:
2960 case LibFunc_exp:
2961 case LibFunc_exp10:
2962 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002963 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002964 case LibFunc_sin:
2965 case LibFunc_sinh:
2966 case LibFunc_tanh:
2967 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2968 return optimizeUnaryDoubleFP(CI, Builder, true);
2969 return nullptr;
2970 case LibFunc_copysign:
2971 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2972 return optimizeBinaryDoubleFP(CI, Builder);
2973 return nullptr;
2974 case LibFunc_fminf:
2975 case LibFunc_fmin:
2976 case LibFunc_fminl:
2977 case LibFunc_fmaxf:
2978 case LibFunc_fmax:
2979 case LibFunc_fmaxl:
2980 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002981 case LibFunc_cabs:
2982 case LibFunc_cabsf:
2983 case LibFunc_cabsl:
2984 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002985 default:
2986 return nullptr;
2987 }
2988}
2989
Chris Bienemanad070d02014-09-17 20:55:46 +00002990Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002991 // TODO: Split out the code below that operates on FP calls so that
2992 // we can all non-FP calls with the StrictFP attribute to be
2993 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002994 if (CI->isNoBuiltin())
2995 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002996
David L. Jonesd21529f2017-01-23 23:16:46 +00002997 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002998 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002999
3000 SmallVector<OperandBundleDef, 2> OpBundles;
3001 CI->getOperandBundlesAsDefs(OpBundles);
3002 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00003003 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00003004
Sanjay Pateld1f4f032016-01-19 18:38:52 +00003005 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00003006 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00003007 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00003008 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
3009 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00003010 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00003011 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00003012
Sanjay Patel848309d2014-10-23 21:52:45 +00003013 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00003014 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00003015 if (!isCallingConvC)
3016 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00003017 // The FP intrinsics have corresponding constrained versions so we don't
3018 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00003019 switch (II->getIntrinsicID()) {
3020 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00003021 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00003022 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00003023 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00003024 case Intrinsic::log:
Evandro Menezes110b1132019-09-30 20:52:21 +00003025 case Intrinsic::log2:
3026 case Intrinsic::log10:
Davide Italianob8b71332015-11-29 20:58:04 +00003027 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00003028 case Intrinsic::sqrt:
3029 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00003030 // TODO: Use foldMallocMemset() with memset intrinsic.
David Bolvansky39130312019-08-13 09:11:49 +00003031 case Intrinsic::memset:
David Bolvanskye80fcf02019-09-17 09:32:52 +00003032 return optimizeMemSet(CI, Builder);
David Bolvansky39130312019-08-13 09:11:49 +00003033 case Intrinsic::memcpy:
David Bolvanskye80fcf02019-09-17 09:32:52 +00003034 return optimizeMemCpy(CI, Builder);
David Bolvansky39130312019-08-13 09:11:49 +00003035 case Intrinsic::memmove:
David Bolvanskye80fcf02019-09-17 09:32:52 +00003036 return optimizeMemMove(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00003037 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00003038 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00003039 }
3040 }
3041
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003042 // Also try to simplify calls to fortified library functions.
3043 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
3044 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00003045 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00003046 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
3047 // Use an IR Builder from SimplifiedCI if available instead of CI
3048 // to guarantee we reach all uses we might replace later on.
3049 IRBuilder<> TmpBuilder(SimplifiedCI);
3050 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003051 // If we were able to further simplify, remove the now redundant call.
Evandro Menezes7d677ad2019-09-06 22:07:11 +00003052 substituteInParent(SimplifiedCI, V);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003053 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003054 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00003055 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003056 return SimplifiedFortifiedCI;
3057 }
3058
Meador Inge20255ef2013-03-12 00:08:29 +00003059 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00003060 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00003061 // We never change the calling convention.
3062 if (!ignoreCallingConv(Func) && !isCallingConvC)
3063 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00003064 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
3065 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00003066 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
3067 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00003068 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00003069 case LibFunc_ffs:
3070 case LibFunc_ffsl:
3071 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00003072 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003073 case LibFunc_fls:
3074 case LibFunc_flsl:
3075 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00003076 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003077 case LibFunc_abs:
3078 case LibFunc_labs:
3079 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00003080 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003081 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00003082 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003083 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00003084 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003085 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00003086 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00003087 case LibFunc_atoi:
3088 case LibFunc_atol:
3089 case LibFunc_atoll:
3090 return optimizeAtoi(CI, Builder);
3091 case LibFunc_strtol:
3092 case LibFunc_strtoll:
3093 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003094 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003095 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003096 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003097 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00003098 case LibFunc_snprintf:
3099 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003100 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003101 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003102 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00003103 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00003104 case LibFunc_fread:
3105 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003106 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00003107 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00003108 case LibFunc_fgets:
3109 return optimizeFGets(CI, Builder);
3110 case LibFunc_fputc:
3111 return optimizeFPutc(CI, Builder);
3112 case LibFunc_fgetc:
3113 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003114 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00003115 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003116 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00003117 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003118 case LibFunc_vfprintf:
3119 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00003120 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00003121 default:
3122 return nullptr;
3123 }
Meador Inge20255ef2013-03-12 00:08:29 +00003124 }
Craig Topperf40110f2014-04-25 05:29:35 +00003125 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00003126}
3127
Chandler Carruth92803822015-01-21 02:11:59 +00003128LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003129 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00003130 OptimizationRemarkEmitter &ORE,
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00003131 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
Amara Emerson54f60252018-10-11 14:51:11 +00003132 function_ref<void(Instruction *, Value *)> Replacer,
3133 function_ref<void(Instruction *)> Eraser)
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00003134 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
Amara Emerson54f60252018-10-11 14:51:11 +00003135 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00003136
3137void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
3138 // Indirect through the replacer used in this instance.
3139 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00003140}
3141
Amara Emerson54f60252018-10-11 14:51:11 +00003142void LibCallSimplifier::eraseFromParent(Instruction *I) {
3143 Eraser(I);
3144}
3145
Meador Ingedfb08a22013-06-20 19:48:07 +00003146// TODO:
3147// Additional cases that we need to add to this file:
3148//
3149// cbrt:
3150// * cbrt(expN(X)) -> expN(x/3)
3151// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00003152// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00003153//
3154// exp, expf, expl:
3155// * exp(log(x)) -> x
3156//
3157// log, logf, logl:
3158// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00003159// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00003160// * log(exp10(y)) -> y*log(10)
3161// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00003162//
Meador Ingedfb08a22013-06-20 19:48:07 +00003163// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00003164// * pow(sqrt(x),y) -> pow(x,y*0.5)
3165// * pow(pow(x,y),z)-> pow(x,y*z)
3166//
Meador Ingedfb08a22013-06-20 19:48:07 +00003167// signbit:
3168// * signbit(cnst) -> cnst'
3169// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
3170//
3171// sqrt, sqrtf, sqrtl:
3172// * sqrt(expN(x)) -> expN(x*0.5)
3173// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
3174// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
3175//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003176
3177//===----------------------------------------------------------------------===//
3178// Fortified Library Call Optimizations
3179//===----------------------------------------------------------------------===//
3180
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003181bool
3182FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
3183 unsigned ObjSizeOp,
3184 Optional<unsigned> SizeOp,
3185 Optional<unsigned> StrOp,
3186 Optional<unsigned> FlagOp) {
3187 // If this function takes a flag argument, the implementation may use it to
3188 // perform extra checks. Don't fold into the non-checking variant.
3189 if (FlagOp) {
3190 ConstantInt *Flag = dyn_cast<ConstantInt>(CI->getArgOperand(*FlagOp));
3191 if (!Flag || !Flag->isZero())
3192 return false;
3193 }
3194
3195 if (SizeOp && CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(*SizeOp))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003196 return true;
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003197
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003198 if (ConstantInt *ObjSizeCI =
3199 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00003200 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003201 return true;
3202 // If the object size wasn't -1 (unknown), bail out if we were asked to.
3203 if (OnlyLowerUnknownSize)
3204 return false;
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003205 if (StrOp) {
3206 uint64_t Len = GetStringLength(CI->getArgOperand(*StrOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003207 // If the length is 0 we don't know how long it is and so we can't
3208 // remove the check.
David Bolvanskye80fcf02019-09-17 09:32:52 +00003209 if (Len)
3210 annotateDereferenceableBytes(CI, *StrOp, Len);
3211 else
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003212 return false;
3213 return ObjSizeCI->getZExtValue() >= Len;
3214 }
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003215
3216 if (SizeOp) {
3217 if (ConstantInt *SizeCI =
3218 dyn_cast<ConstantInt>(CI->getArgOperand(*SizeOp)))
3219 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
3220 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003221 }
3222 return false;
3223}
3224
Sanjay Pateld707db92015-12-31 16:10:49 +00003225Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
3226 IRBuilder<> &B) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003227 if (isFortifiedCallFoldable(CI, 3, 2)) {
David Bolvanskye80fcf02019-09-17 09:32:52 +00003228 CallInst *NewCI = B.CreateMemCpy(
3229 CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, CI->getArgOperand(2));
3230 NewCI->setAttributes(CI->getAttributes());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003231 return CI->getArgOperand(0);
3232 }
3233 return nullptr;
3234}
3235
Sanjay Pateld707db92015-12-31 16:10:49 +00003236Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
3237 IRBuilder<> &B) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003238 if (isFortifiedCallFoldable(CI, 3, 2)) {
David Bolvanskye80fcf02019-09-17 09:32:52 +00003239 CallInst *NewCI = B.CreateMemMove(
3240 CI->getArgOperand(0), 1, CI->getArgOperand(1), 1, CI->getArgOperand(2));
3241 NewCI->setAttributes(CI->getAttributes());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003242 return CI->getArgOperand(0);
3243 }
3244 return nullptr;
3245}
3246
Sanjay Pateld707db92015-12-31 16:10:49 +00003247Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
3248 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00003249 // TODO: Try foldMallocMemset() here.
3250
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003251 if (isFortifiedCallFoldable(CI, 3, 2)) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003252 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
David Bolvanskye80fcf02019-09-17 09:32:52 +00003253 CallInst *NewCI =
3254 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
3255 NewCI->setAttributes(CI->getAttributes());
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003256 return CI->getArgOperand(0);
3257 }
3258 return nullptr;
3259}
3260
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003261Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
3262 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00003263 LibFunc Func) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003264 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003265 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
3266 *ObjSize = CI->getArgOperand(2);
3267
3268 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00003269 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00003270 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00003271 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003272 }
3273
3274 // If a) we don't have any length information, or b) we know this will
3275 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
3276 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
3277 // TODO: It might be nice to get a maximum length out of the possible
3278 // string lengths for varying.
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003279 if (isFortifiedCallFoldable(CI, 2, None, 1)) {
Erik Pilkington52349212019-05-31 22:41:31 +00003280 if (Func == LibFunc_strcpy_chk)
3281 return emitStrCpy(Dst, Src, B, TLI);
3282 else
3283 return emitStpCpy(Dst, Src, B, TLI);
3284 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003285
David Blaikie65fab6d2015-04-03 21:32:06 +00003286 if (OnlyLowerUnknownSize)
3287 return nullptr;
3288
3289 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00003290 uint64_t Len = GetStringLength(Src);
David Bolvanskye80fcf02019-09-17 09:32:52 +00003291 if (Len)
3292 annotateDereferenceableBytes(CI, 1, Len);
3293 else
David Blaikie65fab6d2015-04-03 21:32:06 +00003294 return nullptr;
3295
3296 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
3297 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00003298 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00003299 // If the function was an __stpcpy_chk, and we were able to fold it into
3300 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00003301 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00003302 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
3303 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003304}
3305
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003306Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
3307 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00003308 LibFunc Func) {
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003309 if (isFortifiedCallFoldable(CI, 3, 2)) {
Erik Pilkington52349212019-05-31 22:41:31 +00003310 if (Func == LibFunc_strncpy_chk)
3311 return emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003312 CI->getArgOperand(2), B, TLI);
Erik Pilkington52349212019-05-31 22:41:31 +00003313 else
3314 return emitStpNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3315 CI->getArgOperand(2), B, TLI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003316 }
Erik Pilkington52349212019-05-31 22:41:31 +00003317
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003318 return nullptr;
3319}
3320
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003321Value *FortifiedLibCallSimplifier::optimizeMemCCpyChk(CallInst *CI,
3322 IRBuilder<> &B) {
3323 if (isFortifiedCallFoldable(CI, 4, 3))
3324 return emitMemCCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3325 CI->getArgOperand(2), CI->getArgOperand(3), B, TLI);
3326
3327 return nullptr;
3328}
3329
3330Value *FortifiedLibCallSimplifier::optimizeSNPrintfChk(CallInst *CI,
3331 IRBuilder<> &B) {
3332 if (isFortifiedCallFoldable(CI, 3, 1, None, 2)) {
3333 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 5, CI->arg_end());
3334 return emitSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3335 CI->getArgOperand(4), VariadicArgs, B, TLI);
3336 }
3337
3338 return nullptr;
3339}
3340
3341Value *FortifiedLibCallSimplifier::optimizeSPrintfChk(CallInst *CI,
3342 IRBuilder<> &B) {
3343 if (isFortifiedCallFoldable(CI, 2, None, None, 1)) {
3344 SmallVector<Value *, 8> VariadicArgs(CI->arg_begin() + 4, CI->arg_end());
3345 return emitSPrintf(CI->getArgOperand(0), CI->getArgOperand(3), VariadicArgs,
3346 B, TLI);
3347 }
3348
3349 return nullptr;
3350}
3351
3352Value *FortifiedLibCallSimplifier::optimizeStrCatChk(CallInst *CI,
3353 IRBuilder<> &B) {
3354 if (isFortifiedCallFoldable(CI, 2))
3355 return emitStrCat(CI->getArgOperand(0), CI->getArgOperand(1), B, TLI);
3356
3357 return nullptr;
3358}
3359
3360Value *FortifiedLibCallSimplifier::optimizeStrLCat(CallInst *CI,
3361 IRBuilder<> &B) {
3362 if (isFortifiedCallFoldable(CI, 3))
3363 return emitStrLCat(CI->getArgOperand(0), CI->getArgOperand(1),
3364 CI->getArgOperand(2), B, TLI);
3365
3366 return nullptr;
3367}
3368
3369Value *FortifiedLibCallSimplifier::optimizeStrNCatChk(CallInst *CI,
3370 IRBuilder<> &B) {
3371 if (isFortifiedCallFoldable(CI, 3))
3372 return emitStrNCat(CI->getArgOperand(0), CI->getArgOperand(1),
3373 CI->getArgOperand(2), B, TLI);
3374
3375 return nullptr;
3376}
3377
3378Value *FortifiedLibCallSimplifier::optimizeStrLCpyChk(CallInst *CI,
3379 IRBuilder<> &B) {
3380 if (isFortifiedCallFoldable(CI, 3))
3381 return emitStrLCpy(CI->getArgOperand(0), CI->getArgOperand(1),
3382 CI->getArgOperand(2), B, TLI);
3383
3384 return nullptr;
3385}
3386
3387Value *FortifiedLibCallSimplifier::optimizeVSNPrintfChk(CallInst *CI,
3388 IRBuilder<> &B) {
3389 if (isFortifiedCallFoldable(CI, 3, 1, None, 2))
3390 return emitVSNPrintf(CI->getArgOperand(0), CI->getArgOperand(1),
3391 CI->getArgOperand(4), CI->getArgOperand(5), B, TLI);
3392
3393 return nullptr;
3394}
3395
3396Value *FortifiedLibCallSimplifier::optimizeVSPrintfChk(CallInst *CI,
3397 IRBuilder<> &B) {
3398 if (isFortifiedCallFoldable(CI, 2, None, None, 1))
3399 return emitVSPrintf(CI->getArgOperand(0), CI->getArgOperand(3),
3400 CI->getArgOperand(4), B, TLI);
3401
3402 return nullptr;
3403}
3404
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003405Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00003406 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
3407 // Some clang users checked for _chk libcall availability using:
3408 // __has_builtin(__builtin___memcpy_chk)
3409 // When compiling with -fno-builtin, this is always true.
3410 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
3411 // end up with fortified libcalls, which isn't acceptable in a freestanding
3412 // environment which only provides their non-fortified counterparts.
3413 //
3414 // Until we change clang and/or teach external users to check for availability
3415 // differently, disregard the "nobuiltin" attribute and TLI::has.
3416 //
3417 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003418
David L. Jonesd21529f2017-01-23 23:16:46 +00003419 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003420 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00003421
3422 SmallVector<OperandBundleDef, 2> OpBundles;
3423 CI->getOperandBundlesAsDefs(OpBundles);
3424 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00003425 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003426
Ahmed Bougachad765a822016-04-27 19:04:35 +00003427 // First, check that this is a known library functions and that the prototype
3428 // is correct.
3429 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003430 return nullptr;
3431
3432 // We never change the calling convention.
3433 if (!ignoreCallingConv(Func) && !isCallingConvC)
3434 return nullptr;
3435
3436 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00003437 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003438 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003439 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003440 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003441 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003442 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00003443 case LibFunc_stpcpy_chk:
3444 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003445 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00003446 case LibFunc_stpncpy_chk:
3447 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00003448 return optimizeStrpNCpyChk(CI, Builder, Func);
Erik Pilkingtonabb2a932019-05-31 22:41:36 +00003449 case LibFunc_memccpy_chk:
3450 return optimizeMemCCpyChk(CI, Builder);
3451 case LibFunc_snprintf_chk:
3452 return optimizeSNPrintfChk(CI, Builder);
3453 case LibFunc_sprintf_chk:
3454 return optimizeSPrintfChk(CI, Builder);
3455 case LibFunc_strcat_chk:
3456 return optimizeStrCatChk(CI, Builder);
3457 case LibFunc_strlcat_chk:
3458 return optimizeStrLCat(CI, Builder);
3459 case LibFunc_strncat_chk:
3460 return optimizeStrNCatChk(CI, Builder);
3461 case LibFunc_strlcpy_chk:
3462 return optimizeStrLCpyChk(CI, Builder);
3463 case LibFunc_vsnprintf_chk:
3464 return optimizeVSNPrintfChk(CI, Builder);
3465 case LibFunc_vsprintf_chk:
3466 return optimizeVSPrintfChk(CI, Builder);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00003467 default:
3468 break;
3469 }
3470 return nullptr;
3471}
3472
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003473FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
3474 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Evandro Menezesb2169262019-07-12 00:33:49 +00003475 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}