blob: 23b88dbda263418b4e262a2436124c374f72b9f9 [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"
Meador Ingedf796f82012-10-13 16:45:24 +000038#include "llvm/Transforms/Utils/BuildLibCalls.h"
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +000039#include "llvm/Transforms/Utils/SizeOpts.h"
Meador Ingedf796f82012-10-13 16:45:24 +000040
41using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000042using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000043
Hal Finkel66cd3f12013-11-17 02:06:35 +000044static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000045 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
David L. Jonesd21529f2017-01-23 23:16:46 +000055static bool ignoreCallingConv(LibFunc Func) {
56 return Func == LibFunc_abs || Func == LibFunc_labs ||
57 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000058}
59
Sam Parker214f7bf2016-09-13 12:10:14 +000060static bool isCallingConvCCompatible(CallInst *CI) {
61 switch(CI->getCallingConv()) {
62 default:
63 return false;
64 case llvm::CallingConv::C:
65 return true;
66 case llvm::CallingConv::ARM_APCS:
67 case llvm::CallingConv::ARM_AAPCS:
68 case llvm::CallingConv::ARM_AAPCS_VFP: {
69
70 // The iOS ABI diverges from the standard in some cases, so for now don't
71 // try to simplify those calls.
72 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
73 return false;
74
75 auto *FuncTy = CI->getFunctionType();
76
77 if (!FuncTy->getReturnType()->isPointerTy() &&
78 !FuncTy->getReturnType()->isIntegerTy() &&
79 !FuncTy->getReturnType()->isVoidTy())
80 return false;
81
82 for (auto Param : FuncTy->params()) {
83 if (!Param->isPointerTy() && !Param->isIntegerTy())
84 return false;
85 }
86 return true;
87 }
88 }
89 return false;
90}
91
Sanjay Pateld707db92015-12-31 16:10:49 +000092/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000093static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000094 for (User *U : V->users()) {
95 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000096 if (IC->isEquality() && IC->getOperand(1) == With)
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
103
Meador Inge08ca1152012-11-26 20:37:20 +0000104static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000105 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000106 return OI->getType()->isFloatingPointTy();
107 });
Meador Inge08ca1152012-11-26 20:37:20 +0000108}
109
Alon Zakaib4f99912019-04-03 01:08:35 +0000110static bool callHasFP128Argument(const CallInst *CI) {
111 return any_of(CI->operands(), [](const Use &OI) {
112 return OI->getType()->isFP128Ty();
113 });
114}
115
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000116static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
117 if (Base < 2 || Base > 36)
118 // handle special zero base
119 if (Base != 0)
120 return nullptr;
121
122 char *End;
123 std::string nptr = Str.str();
124 errno = 0;
125 long long int Result = strtoll(nptr.c_str(), &End, Base);
126 if (errno)
127 return nullptr;
128
129 // if we assume all possible target locales are ASCII supersets,
130 // then if strtoll successfully parses a number on the host,
131 // it will also successfully parse the same way on the target
132 if (*End != '\0')
133 return nullptr;
134
135 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
136 return nullptr;
137
138 return ConstantInt::get(CI->getType(), Result);
139}
140
David Bolvanskyca22d422018-05-16 11:39:52 +0000141static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
142 const TargetLibraryInfo *TLI) {
143 CallInst *FOpen = dyn_cast<CallInst>(File);
144 if (!FOpen)
145 return false;
146
147 Function *InnerCallee = FOpen->getCalledFunction();
148 if (!InnerCallee)
149 return false;
150
151 LibFunc Func;
152 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
153 Func != LibFunc_fopen)
154 return false;
155
David Bolvansky7c7760d2018-10-16 21:18:31 +0000156 inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
David Bolvanskyca22d422018-05-16 11:39:52 +0000157 if (PointerMayBeCaptured(File, true, true))
158 return false;
159
160 return true;
161}
162
David Bolvansky909889b2018-08-10 04:32:54 +0000163static bool isOnlyUsedInComparisonWithZero(Value *V) {
164 for (User *U : V->users()) {
165 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
166 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
167 if (C->isNullValue())
168 continue;
169 // Unknown instruction.
170 return false;
171 }
172 return true;
173}
174
175static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
176 const DataLayout &DL) {
177 if (!isOnlyUsedInComparisonWithZero(CI))
178 return false;
179
180 if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
181 return false;
Matt Morehousee62fc3d2018-09-19 19:37:24 +0000182
183 if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
184 return false;
185
David Bolvansky909889b2018-08-10 04:32:54 +0000186 return true;
187}
188
Meador Inged589ac62012-10-31 03:33:06 +0000189//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000190// String and Memory Library Call Optimizations
191//===----------------------------------------------------------------------===//
192
Chris Bienemanad070d02014-09-17 20:55:46 +0000193Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000194 // Extract some information from the instruction
195 Value *Dst = CI->getArgOperand(0);
196 Value *Src = CI->getArgOperand(1);
197
198 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000199 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 if (Len == 0)
201 return nullptr;
202 --Len; // Unbias length.
203
204 // Handle the simple, do-nothing case: strcat(x, "") -> x
205 if (Len == 0)
206 return Dst;
207
Chris Bienemanad070d02014-09-17 20:55:46 +0000208 return emitStrLenMemCpy(Src, Dst, Len, B);
209}
210
211Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
212 IRBuilder<> &B) {
213 // We need to find the end of the destination string. That's where the
214 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000215 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000216 if (!DstLen)
217 return nullptr;
218
219 // Now that we have the destination's length, we must index into the
220 // destination's pointer to get the actual memcpy destination (end of
221 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000222 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000223
224 // We have enough information to now generate the memcpy call to do the
225 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000226 B.CreateMemCpy(CpyDst, 1, Src, 1,
227 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000228 return Dst;
229}
230
231Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000232 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000233 Value *Dst = CI->getArgOperand(0);
234 Value *Src = CI->getArgOperand(1);
235 uint64_t Len;
236
Sanjay Pateld707db92015-12-31 16:10:49 +0000237 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000238 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
239 Len = LengthArg->getZExtValue();
240 else
241 return nullptr;
242
243 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000244 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000245 if (SrcLen == 0)
246 return nullptr;
247 --SrcLen; // Unbias length.
248
249 // Handle the simple, do-nothing cases:
250 // strncat(x, "", c) -> x
251 // strncat(x, c, 0) -> x
252 if (SrcLen == 0 || Len == 0)
253 return Dst;
254
Sanjay Pateld707db92015-12-31 16:10:49 +0000255 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000256 if (Len < SrcLen)
257 return nullptr;
258
259 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000260 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000261 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
262}
263
264Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
265 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000266 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000267 Value *SrcStr = CI->getArgOperand(0);
268
269 // If the second operand is non-constant, see if we can compute the length
270 // of the input string and turn this into memchr.
271 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
272 if (!CharC) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000273 uint64_t Len = GetStringLength(SrcStr);
Chris Bienemanad070d02014-09-17 20:55:46 +0000274 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
275 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000276
Sanjay Pateld3112a52016-01-19 19:46:10 +0000277 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000278 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
279 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000280 }
281
Chris Bienemanad070d02014-09-17 20:55:46 +0000282 // Otherwise, the character is a constant, see if the first argument is
283 // a string literal. If so, we can constant fold.
284 StringRef Str;
285 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000286 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000287 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000288 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000289 return nullptr;
290 }
291
292 // Compute the offset, make sure to handle the case when we're searching for
293 // zero (a weird way to spell strlen).
294 size_t I = (0xFF & CharC->getSExtValue()) == 0
295 ? Str.size()
296 : Str.find(CharC->getSExtValue());
297 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
298 return Constant::getNullValue(CI->getType());
299
300 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000301 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000302}
303
304Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000305 Value *SrcStr = CI->getArgOperand(0);
306 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
307
308 // Cannot fold anything if we're not looking for a constant.
309 if (!CharC)
310 return nullptr;
311
312 StringRef Str;
313 if (!getConstantStringInfo(SrcStr, Str)) {
314 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000316 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000317 return nullptr;
318 }
319
320 // Compute the offset.
321 size_t I = (0xFF & CharC->getSExtValue()) == 0
322 ? Str.size()
323 : Str.rfind(CharC->getSExtValue());
324 if (I == StringRef::npos) // Didn't find the char. Return null.
325 return Constant::getNullValue(CI->getType());
326
327 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000328 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000329}
330
331Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000332 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
333 if (Str1P == Str2P) // strcmp(x,x) -> 0
334 return ConstantInt::get(CI->getType(), 0);
335
336 StringRef Str1, Str2;
337 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
338 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
339
340 // strcmp(x, y) -> cnst (if both x and y are constant strings)
341 if (HasStr1 && HasStr2)
342 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
343
344 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000345 return B.CreateNeg(B.CreateZExt(
346 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000347
348 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000349 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
350 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000351
352 // strcmp(P, "x") -> memcmp(P, "x", 2)
David Bolvansky1f343fa2018-05-22 20:27:36 +0000353 uint64_t Len1 = GetStringLength(Str1P);
354 uint64_t Len2 = GetStringLength(Str2P);
Chris Bienemanad070d02014-09-17 20:55:46 +0000355 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000356 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000357 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000358 std::min(Len1, Len2)),
359 B, DL, TLI);
360 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000361
David Bolvansky909889b2018-08-10 04:32:54 +0000362 // strcmp to memcmp
363 if (!HasStr1 && HasStr2) {
364 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
365 return emitMemCmp(
366 Str1P, Str2P,
367 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
368 TLI);
369 } else if (HasStr1 && !HasStr2) {
370 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
371 return emitMemCmp(
372 Str1P, Str2P,
373 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
374 TLI);
375 }
376
Chris Bienemanad070d02014-09-17 20:55:46 +0000377 return nullptr;
378}
379
380Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000381 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
382 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
383 return ConstantInt::get(CI->getType(), 0);
384
385 // Get the length argument if it is constant.
386 uint64_t Length;
387 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
388 Length = LengthArg->getZExtValue();
389 else
390 return nullptr;
391
392 if (Length == 0) // strncmp(x,y,0) -> 0
393 return ConstantInt::get(CI->getType(), 0);
394
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000396 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000397
398 StringRef Str1, Str2;
399 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
400 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
401
402 // strncmp(x, y) -> cnst (if both x and y are constant strings)
403 if (HasStr1 && HasStr2) {
404 StringRef SubStr1 = Str1.substr(0, Length);
405 StringRef SubStr2 = Str2.substr(0, Length);
406 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
407 }
408
409 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
James Y Knight14359ef2019-02-01 20:44:24 +0000410 return B.CreateNeg(B.CreateZExt(
411 B.CreateLoad(B.getInt8Ty(), Str2P, "strcmpload"), CI->getType()));
Chris Bienemanad070d02014-09-17 20:55:46 +0000412
413 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
James Y Knight14359ef2019-02-01 20:44:24 +0000414 return B.CreateZExt(B.CreateLoad(B.getInt8Ty(), Str1P, "strcmpload"),
415 CI->getType());
Chris Bienemanad070d02014-09-17 20:55:46 +0000416
David Bolvansky909889b2018-08-10 04:32:54 +0000417 uint64_t Len1 = GetStringLength(Str1P);
418 uint64_t Len2 = GetStringLength(Str2P);
419
420 // strncmp to memcmp
421 if (!HasStr1 && HasStr2) {
422 Len2 = std::min(Len2, Length);
423 if (canTransformToMemCmp(CI, Str1P, Len2, DL))
424 return emitMemCmp(
425 Str1P, Str2P,
426 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
427 TLI);
428 } else if (HasStr1 && !HasStr2) {
429 Len1 = std::min(Len1, Length);
430 if (canTransformToMemCmp(CI, Str2P, Len1, DL))
431 return emitMemCmp(
432 Str1P, Str2P,
433 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
434 TLI);
435 }
436
Chris Bienemanad070d02014-09-17 20:55:46 +0000437 return nullptr;
438}
439
440Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
444
Chris Bienemanad070d02014-09-17 20:55:46 +0000445 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000446 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000447 if (Len == 0)
448 return nullptr;
449
450 // We have enough information to now generate the memcpy call to do the
451 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000452 B.CreateMemCpy(Dst, 1, Src, 1,
453 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000454 return Dst;
455}
456
457Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
458 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000459 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
460 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000461 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000462 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000463 }
464
465 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000466 uint64_t Len = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000467 if (Len == 0)
468 return nullptr;
469
Davide Italianob7487e62015-11-02 23:07:14 +0000470 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000471 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000472 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
473 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000474
475 // We have enough information to now generate the memcpy call to do the
476 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000477 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000478 return DstEnd;
479}
480
481Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
482 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000483 Value *Dst = CI->getArgOperand(0);
484 Value *Src = CI->getArgOperand(1);
485 Value *LenOp = CI->getArgOperand(2);
486
487 // See if we can get the length of the input string.
David Bolvansky1f343fa2018-05-22 20:27:36 +0000488 uint64_t SrcLen = GetStringLength(Src);
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 if (SrcLen == 0)
490 return nullptr;
491 --SrcLen;
492
493 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000494 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000495 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000496 return Dst;
497 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000498
Chris Bienemanad070d02014-09-17 20:55:46 +0000499 uint64_t Len;
500 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
501 Len = LengthArg->getZExtValue();
502 else
503 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 if (Len == 0)
506 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000507
Chris Bienemanad070d02014-09-17 20:55:46 +0000508 // Let strncpy handle the zero padding
509 if (Len > SrcLen + 1)
510 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000511
Davide Italianob7487e62015-11-02 23:07:14 +0000512 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000513 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
514 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000515
Chris Bienemanad070d02014-09-17 20:55:46 +0000516 return Dst;
517}
Meador Inge7fb2f732012-10-13 16:45:32 +0000518
Matthias Braun50ec0b52017-05-19 22:37:09 +0000519Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
520 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 Value *Src = CI->getArgOperand(0);
522
523 // Constant folding: strlen("xyz") -> 3
David Bolvansky1f343fa2018-05-22 20:27:36 +0000524 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000525 return ConstantInt::get(CI->getType(), Len - 1);
526
David L Kreitzer752c1442016-04-13 14:31:06 +0000527 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000528 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000529 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000530 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000531 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000532 // subtraction. This will make the optimization more complex, and it's not
533 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000534 // very uncommon.
535 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000536 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000537 return nullptr;
538
Matthias Braun50ec0b52017-05-19 22:37:09 +0000539 ConstantDataArraySlice Slice;
540 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
541 uint64_t NullTermIdx;
542 if (Slice.Array == nullptr) {
543 NullTermIdx = 0;
544 } else {
545 NullTermIdx = ~((uint64_t)0);
546 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
547 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
548 NullTermIdx = I;
549 break;
550 }
551 }
552 // If the string does not have '\0', leave it to strlen to compute
553 // its length.
554 if (NullTermIdx == ~((uint64_t)0))
555 return nullptr;
556 }
557
David L Kreitzer752c1442016-04-13 14:31:06 +0000558 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000559 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000560 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000561 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000562 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
563
Matthias Braun50ec0b52017-05-19 22:37:09 +0000564 // KnownZero's bits are flipped, so zeros in KnownZero now represent
565 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000566 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000567 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000568 // unsigned-less-than NullTermIdx.
569 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000570 // If Offset is not provably in the range [0, NullTermIdx], we can still
571 // optimize if we can prove that the program has undefined behavior when
572 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000573 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000574 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000575 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000576 NullTermIdx == ArrSize - 1)) {
577 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
578 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000579 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000580 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000581 }
582
583 return nullptr;
584 }
585
Chris Bienemanad070d02014-09-17 20:55:46 +0000586 // strlen(x?"foo":"bars") --> x ? 3 : 4
587 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000588 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
589 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000590 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000591 ORE.emit([&]() {
592 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
593 << "folded strlen(select) to select of constants";
594 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000595 return B.CreateSelect(SI->getCondition(),
596 ConstantInt::get(CI->getType(), LenTrue - 1),
597 ConstantInt::get(CI->getType(), LenFalse - 1));
598 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000599 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000600
Chris Bienemanad070d02014-09-17 20:55:46 +0000601 // strlen(x) != 0 --> *x != 0
602 // strlen(x) == 0 --> *x == 0
603 if (isOnlyUsedInZeroEqualityComparison(CI))
James Y Knight14359ef2019-02-01 20:44:24 +0000604 return B.CreateZExt(B.CreateLoad(B.getIntNTy(CharSize), Src, "strlenfirst"),
605 CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000606
Chris Bienemanad070d02014-09-17 20:55:46 +0000607 return nullptr;
608}
Meador Inge17418502012-10-13 16:45:37 +0000609
Matthias Braun50ec0b52017-05-19 22:37:09 +0000610Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
611 return optimizeStringLength(CI, B, 8);
612}
613
614Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
David Bolvansky5430b7372018-05-31 16:39:27 +0000615 Module &M = *CI->getModule();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000616 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000617 // We cannot perform this optimization without wchar_size metadata.
618 if (WCharSize == 0)
619 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000620
621 return optimizeStringLength(CI, B, WCharSize);
622}
623
Chris Bienemanad070d02014-09-17 20:55:46 +0000624Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000625 StringRef S1, S2;
626 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
627 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000628
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000629 // strpbrk(s, "") -> nullptr
630 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000631 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
632 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000633
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 // Constant folding.
635 if (HasS1 && HasS2) {
636 size_t I = S1.find_first_of(S2);
637 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000638 return Constant::getNullValue(CI->getType());
639
Sanjay Pateld707db92015-12-31 16:10:49 +0000640 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
641 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000642 }
Meador Inge17418502012-10-13 16:45:37 +0000643
Chris Bienemanad070d02014-09-17 20:55:46 +0000644 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000646 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000647
648 return nullptr;
649}
650
651Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000652 Value *EndPtr = CI->getArgOperand(1);
653 if (isa<ConstantPointerNull>(EndPtr)) {
654 // With a null EndPtr, this function won't capture the main argument.
655 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000656 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000657 }
658
659 return nullptr;
660}
661
662Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000663 StringRef S1, S2;
664 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
665 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
666
667 // strspn(s, "") -> 0
668 // strspn("", s) -> 0
669 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
670 return Constant::getNullValue(CI->getType());
671
672 // Constant folding.
673 if (HasS1 && HasS2) {
674 size_t Pos = S1.find_first_not_of(S2);
675 if (Pos == StringRef::npos)
676 Pos = S1.size();
677 return ConstantInt::get(CI->getType(), Pos);
678 }
679
680 return nullptr;
681}
682
683Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000684 StringRef S1, S2;
685 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
686 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
687
688 // strcspn("", s) -> 0
689 if (HasS1 && S1.empty())
690 return Constant::getNullValue(CI->getType());
691
692 // Constant folding.
693 if (HasS1 && HasS2) {
694 size_t Pos = S1.find_first_of(S2);
695 if (Pos == StringRef::npos)
696 Pos = S1.size();
697 return ConstantInt::get(CI->getType(), Pos);
698 }
699
700 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000702 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000703
704 return nullptr;
705}
706
707Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000708 // fold strstr(x, x) -> x.
709 if (CI->getArgOperand(0) == CI->getArgOperand(1))
710 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
711
712 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000713 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000714 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000715 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000716 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000717 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000718 StrLen, B, DL, TLI);
719 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000720 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
722 ICmpInst *Old = cast<ICmpInst>(*UI++);
723 Value *Cmp =
724 B.CreateICmp(Old->getPredicate(), StrNCmp,
725 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
726 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000727 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000728 return CI;
729 }
Meador Inge17418502012-10-13 16:45:37 +0000730
Chris Bienemanad070d02014-09-17 20:55:46 +0000731 // See if either input string is a constant string.
732 StringRef SearchStr, ToFindStr;
733 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
734 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
735
736 // fold strstr(x, "") -> x.
737 if (HasStr2 && ToFindStr.empty())
738 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
739
740 // If both strings are known, constant fold it.
741 if (HasStr1 && HasStr2) {
742 size_t Offset = SearchStr.find(ToFindStr);
743
744 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000745 return Constant::getNullValue(CI->getType());
746
Chris Bienemanad070d02014-09-17 20:55:46 +0000747 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000748 Value *Result = castToCStr(CI->getArgOperand(0), B);
James Y Knight77160752019-02-01 20:44:47 +0000749 Result =
750 B.CreateConstInBoundsGEP1_64(B.getInt8Ty(), Result, Offset, "strstr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000751 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000752 }
Meador Inge17418502012-10-13 16:45:37 +0000753
Chris Bienemanad070d02014-09-17 20:55:46 +0000754 // fold strstr(x, "y") -> strchr(x, 'y').
755 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000756 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000757 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
758 }
759 return nullptr;
760}
Meador Inge40b6fac2012-10-15 03:47:37 +0000761
Benjamin Kramer691363e2015-03-21 15:36:21 +0000762Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000763 Value *SrcStr = CI->getArgOperand(0);
764 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
765 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
766
767 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000768 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000769 return Constant::getNullValue(CI->getType());
770
Benjamin Kramer7857d722015-03-21 21:09:33 +0000771 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000772 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000773 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000774 return nullptr;
775
776 // Truncate the string to LenC. If Str is smaller than LenC we will still only
777 // scan the string, as reading past the end of it is undefined and we can just
778 // return null if we don't find the char.
779 Str = Str.substr(0, LenC->getZExtValue());
780
Benjamin Kramer7857d722015-03-21 21:09:33 +0000781 // If the char is variable but the input str and length are not we can turn
782 // this memchr call into a simple bit field test. Of course this only works
783 // when the return value is only checked against null.
784 //
785 // It would be really nice to reuse switch lowering here but we can't change
786 // the CFG at this point.
787 //
Fangrui Songf2609672019-03-12 10:31:52 +0000788 // memchr("\r\n", C, 2) != nullptr -> (1 << C & ((1 << '\r') | (1 << '\n')))
789 // != 0
Benjamin Kramer7857d722015-03-21 21:09:33 +0000790 // after bounds check.
791 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000792 unsigned char Max =
793 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
794 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000795
796 // Make sure the bit field we're about to create fits in a register on the
797 // target.
798 // FIXME: On a 64 bit architecture this prevents us from using the
799 // interesting range of alpha ascii chars. We could do better by emitting
800 // two bitfields or shifting the range by 64 if no lower chars are used.
801 if (!DL.fitsInLegalInteger(Max + 1))
802 return nullptr;
803
804 // For the bit field use a power-of-2 type with at least 8 bits to avoid
805 // creating unnecessary illegal types.
806 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
807
808 // Now build the bit field.
809 APInt Bitfield(Width, 0);
810 for (char C : Str)
811 Bitfield.setBit((unsigned char)C);
812 Value *BitfieldC = B.getInt(Bitfield);
813
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000814 // Adjust width of "C" to the bitfield width, then mask off the high bits.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000815 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
Eli Friedmand4e7a0d2019-01-09 23:39:26 +0000816 C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
817
818 // First check that the bit field access is within bounds.
Benjamin Kramer7857d722015-03-21 21:09:33 +0000819 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
820 "memchr.bounds");
821
822 // Create code that checks if the given bit is set in the field.
823 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
824 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
825
826 // Finally merge both checks and cast to pointer type. The inttoptr
827 // implicitly zexts the i1 to intptr type.
828 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
829 }
830
831 // Check if all arguments are constants. If so, we can constant fold.
832 if (!CharC)
833 return nullptr;
834
Benjamin Kramer691363e2015-03-21 15:36:21 +0000835 // Compute the offset.
836 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
837 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
838 return Constant::getNullValue(CI->getType());
839
840 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000841 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000842}
843
Clement Courbet8e16d732019-03-08 09:07:45 +0000844static Value *optimizeMemCmpConstantSize(CallInst *CI, Value *LHS, Value *RHS,
845 uint64_t Len, IRBuilder<> &B,
846 const DataLayout &DL) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 if (Len == 0) // memcmp(s1,s2,0) -> 0
848 return Constant::getNullValue(CI->getType());
849
850 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
851 if (Len == 1) {
James Y Knight14359ef2019-02-01 20:44:24 +0000852 Value *LHSV =
853 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(LHS, B), "lhsc"),
854 CI->getType(), "lhsv");
855 Value *RHSV =
856 B.CreateZExt(B.CreateLoad(B.getInt8Ty(), castToCStr(RHS, B), "rhsc"),
857 CI->getType(), "rhsv");
Chris Bienemanad070d02014-09-17 20:55:46 +0000858 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000859 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000860
Chad Rosierdc655322015-08-28 18:30:18 +0000861 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000862 // TODO: The case where both inputs are constants does not need to be limited
863 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000864 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000865 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
866 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
867
Sanjay Patel82ec8722017-08-21 19:13:14 +0000868 // First, see if we can fold either argument to a constant.
869 Value *LHSV = nullptr;
870 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
871 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
872 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
873 }
874 Value *RHSV = nullptr;
875 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
876 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
877 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
878 }
Chad Rosierdc655322015-08-28 18:30:18 +0000879
Sanjay Patel82ec8722017-08-21 19:13:14 +0000880 // Don't generate unaligned loads. If either source is constant data,
881 // alignment doesn't matter for that source because there is no load.
882 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
883 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
884 if (!LHSV) {
885 Type *LHSPtrTy =
886 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +0000887 LHSV = B.CreateLoad(IntType, B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +0000888 }
889 if (!RHSV) {
890 Type *RHSPtrTy =
891 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
James Y Knight14359ef2019-02-01 20:44:24 +0000892 RHSV = B.CreateLoad(IntType, B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
Sanjay Patel82ec8722017-08-21 19:13:14 +0000893 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000894 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000895 }
Chad Rosierdc655322015-08-28 18:30:18 +0000896 }
897
Sanjay Patel82ec8722017-08-21 19:13:14 +0000898 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
899 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000900 StringRef LHSStr, RHSStr;
901 if (getConstantStringInfo(LHS, LHSStr) &&
902 getConstantStringInfo(RHS, RHSStr)) {
903 // Make sure we're not reading out-of-bounds memory.
904 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000905 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000906 // Fold the memcmp and normalize the result. This way we get consistent
907 // results across multiple platforms.
908 uint64_t Ret = 0;
909 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
910 if (Cmp < 0)
911 Ret = -1;
912 else if (Cmp > 0)
913 Ret = 1;
914 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000915 }
Clement Courbet8e16d732019-03-08 09:07:45 +0000916 return nullptr;
917}
918
919Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
920 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
921 Value *Size = CI->getArgOperand(2);
922
923 if (LHS == RHS) // memcmp(s,s,x) -> 0
924 return Constant::getNullValue(CI->getType());
925
926 // Handle constant lengths.
927 if (ConstantInt *LenC = dyn_cast<ConstantInt>(Size))
928 if (Value *Res = optimizeMemCmpConstantSize(CI, LHS, RHS,
929 LenC->getZExtValue(), B, DL))
930 return Res;
931
932 // memcmp(x, y, Len) == 0 -> bcmp(x, y, Len) == 0
933 // `bcmp` can be more efficient than memcmp because it only has to know that
Fangrui Songf2609672019-03-12 10:31:52 +0000934 // there is a difference, not where it is.
Clement Courbet8e16d732019-03-08 09:07:45 +0000935 if (isOnlyUsedInZeroEqualityComparison(CI) && TLI->has(LibFunc_bcmp)) {
936 return emitBCmp(LHS, RHS, Size, B, DL, TLI);
937 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000938
Chris Bienemanad070d02014-09-17 20:55:46 +0000939 return nullptr;
940}
Meador Inge9a6a1902012-10-31 00:20:56 +0000941
Chris Bienemanad070d02014-09-17 20:55:46 +0000942Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000943 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
944 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
945 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000946 return CI->getArgOperand(0);
947}
Meador Inge05a625a2012-10-31 14:58:26 +0000948
Chris Bienemanad070d02014-09-17 20:55:46 +0000949Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000950 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
951 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
952 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000953 return CI->getArgOperand(0);
954}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000955
Sanjay Patel980b2802016-01-26 16:17:24 +0000956/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
Amara Emerson54f60252018-10-11 14:51:11 +0000957Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000958 // This has to be a memset of zeros (bzero).
959 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
960 if (!FillValue || FillValue->getZExtValue() != 0)
961 return nullptr;
962
963 // TODO: We should handle the case where the malloc has more than one use.
964 // This is necessary to optimize common patterns such as when the result of
965 // the malloc is checked against null or when a memset intrinsic is used in
966 // place of a memset library call.
967 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
968 if (!Malloc || !Malloc->hasOneUse())
969 return nullptr;
970
971 // Is the inner call really malloc()?
972 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000973 if (!InnerCallee)
974 return nullptr;
975
David L. Jonesd21529f2017-01-23 23:16:46 +0000976 LibFunc Func;
Amara Emerson54f60252018-10-11 14:51:11 +0000977 if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000978 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000979 return nullptr;
980
Sanjay Patel980b2802016-01-26 16:17:24 +0000981 // The memset must cover the same number of bytes that are malloc'd.
982 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
983 return nullptr;
984
985 // Replace the malloc with a calloc. We need the data layout to know what the
Fangrui Songf78650a2018-07-30 19:41:25 +0000986 // actual size of a 'size_t' parameter is.
Sanjay Patel980b2802016-01-26 16:17:24 +0000987 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
988 const DataLayout &DL = Malloc->getModule()->getDataLayout();
989 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
990 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
991 Malloc->getArgOperand(0), Malloc->getAttributes(),
Amara Emerson54f60252018-10-11 14:51:11 +0000992 B, *TLI);
Sanjay Patel980b2802016-01-26 16:17:24 +0000993 if (!Calloc)
994 return nullptr;
995
996 Malloc->replaceAllUsesWith(Calloc);
Amara Emerson54f60252018-10-11 14:51:11 +0000997 eraseFromParent(Malloc);
Sanjay Patel980b2802016-01-26 16:17:24 +0000998
999 return Calloc;
1000}
1001
Chris Bienemanad070d02014-09-17 20:55:46 +00001002Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Amara Emerson54f60252018-10-11 14:51:11 +00001003 if (auto *Calloc = foldMallocMemset(CI, B))
Sanjay Patel980b2802016-01-26 16:17:24 +00001004 return Calloc;
1005
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001006 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +00001007 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1008 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1009 return CI->getArgOperand(0);
1010}
Meador Inged4825782012-11-11 06:49:03 +00001011
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00001012Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
1013 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
1014 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
1015
1016 return nullptr;
1017}
1018
Meador Inge193e0352012-11-13 04:16:17 +00001019//===----------------------------------------------------------------------===//
1020// Math Library Optimizations
1021//===----------------------------------------------------------------------===//
1022
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001023// Replace a libcall \p CI with a call to intrinsic \p IID
1024static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
1025 // Propagate fast-math flags from the existing call to the new call.
1026 IRBuilder<>::FastMathFlagGuard Guard(B);
1027 B.setFastMathFlags(CI->getFastMathFlags());
1028
1029 Module *M = CI->getModule();
1030 Value *V = CI->getArgOperand(0);
1031 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
1032 CallInst *NewCall = B.CreateCall(F, V);
1033 NewCall->takeName(CI);
1034 return NewCall;
1035}
1036
Matthias Braund34e4d22014-12-03 21:46:33 +00001037/// Return a variant of Val with float type.
1038/// Currently this works in two cases: If Val is an FPExtension of a float
1039/// value to something bigger, simply return the operand.
1040/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1041/// loss of precision do so.
1042static Value *valueHasFloatPrecision(Value *Val) {
1043 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1044 Value *Op = Cast->getOperand(0);
1045 if (Op->getType()->isFloatTy())
1046 return Op;
1047 }
1048 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1049 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001050 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001051 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001052 &losesInfo);
1053 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001054 return ConstantFP::get(Const->getContext(), F);
1055 }
1056 return nullptr;
1057}
1058
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001059/// Shrink double -> float functions.
1060static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001061 bool isBinary, bool isPrecise = false) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001062 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +00001063 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001064
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001065 // If not all the uses of the function are converted to float, then bail out.
1066 // This matters if the precision of the result is more important than the
1067 // precision of the arguments.
1068 if (isPrecise)
Chris Bienemanad070d02014-09-17 20:55:46 +00001069 for (User *U : CI->users()) {
1070 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1071 if (!Cast || !Cast->getType()->isFloatTy())
1072 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001073 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001074
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001075 // If this is something like 'g((double) float)', convert to 'gf(float)'.
1076 Value *V[2];
1077 V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
1078 V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
1079 if (!V[0] || (isBinary && !V[1]))
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 return nullptr;
Fangrui Songf78650a2018-07-30 19:41:25 +00001081
Andrew Ng1606fc02017-04-25 12:36:14 +00001082 // If call isn't an intrinsic, check that it isn't within a function with the
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001083 // same name as the float version of this call, otherwise the result is an
1084 // infinite loop. For example, from MinGW-w64:
Andrew Ng1606fc02017-04-25 12:36:14 +00001085 //
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001086 // float expf(float val) { return (float) exp((double) val); }
1087 Function *CalleeFn = CI->getCalledFunction();
1088 StringRef CalleeNm = CalleeFn->getName();
1089 AttributeList CalleeAt = CalleeFn->getAttributes();
1090 if (CalleeFn && !CalleeFn->isIntrinsic()) {
1091 const Function *Fn = CI->getFunction();
1092 StringRef FnName = Fn->getName();
1093 if (FnName.back() == 'f' &&
1094 FnName.size() == (CalleeNm.size() + 1) &&
1095 FnName.startswith(CalleeNm))
Andrew Ng1606fc02017-04-25 12:36:14 +00001096 return nullptr;
1097 }
1098
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001099 // Propagate the math semantics from the current function to the new function.
Sanjay Patelaa231142015-12-31 21:52:31 +00001100 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001101 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +00001102
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001103 // g((double) float) -> (double) gf(float)
1104 Value *R;
1105 if (CalleeFn->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001106 Module *M = CI->getModule();
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001107 Intrinsic::ID IID = CalleeFn->getIntrinsicID();
1108 Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1109 R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
Sanjay Patel848309d2014-10-23 21:52:45 +00001110 }
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001111 else
1112 R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
1113 : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
Sanjay Patel848309d2014-10-23 21:52:45 +00001114
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001115 return B.CreateFPExt(R, B.getDoubleTy());
Chris Bienemanad070d02014-09-17 20:55:46 +00001116}
Meador Inge193e0352012-11-13 04:16:17 +00001117
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001118/// Shrink double -> float for unary functions.
1119static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001120 bool isPrecise = false) {
1121 return optimizeDoubleFP(CI, B, false, isPrecise);
Matt Arsenault954a6242017-01-23 23:55:08 +00001122}
1123
Evandro Menezes5aa217a2018-08-03 17:50:16 +00001124/// Shrink double -> float for binary functions.
1125static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001126 bool isPrecise = false) {
1127 return optimizeDoubleFP(CI, B, true, isPrecise);
Chris Bienemanad070d02014-09-17 20:55:46 +00001128}
1129
Hal Finkel2ff24732017-12-16 01:26:25 +00001130// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1131Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1132 if (!CI->isFast())
1133 return nullptr;
1134
1135 // Propagate fast-math flags from the existing call to new instructions.
1136 IRBuilder<>::FastMathFlagGuard Guard(B);
1137 B.setFastMathFlags(CI->getFastMathFlags());
1138
1139 Value *Real, *Imag;
1140 if (CI->getNumArgOperands() == 1) {
1141 Value *Op = CI->getArgOperand(0);
1142 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1143 Real = B.CreateExtractValue(Op, 0, "real");
1144 Imag = B.CreateExtractValue(Op, 1, "imag");
1145 } else {
1146 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1147 Real = CI->getArgOperand(0);
1148 Imag = CI->getArgOperand(1);
1149 }
1150
1151 Value *RealReal = B.CreateFMul(Real, Real);
1152 Value *ImagImag = B.CreateFMul(Imag, Imag);
1153
1154 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1155 CI->getType());
1156 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1157}
1158
Sanjay Patele45a83d2018-08-13 19:24:41 +00001159static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
1160 IRBuilder<> &B) {
Sanjay Patel15bff182018-08-13 21:49:19 +00001161 if (!isa<FPMathOperator>(Call))
1162 return nullptr;
Clement Courbet8e16d732019-03-08 09:07:45 +00001163
Sanjay Patel15bff182018-08-13 21:49:19 +00001164 IRBuilder<>::FastMathFlagGuard Guard(B);
1165 B.setFastMathFlags(Call->getFastMathFlags());
Clement Courbet8e16d732019-03-08 09:07:45 +00001166
Sanjay Patele45a83d2018-08-13 19:24:41 +00001167 // TODO: Can this be shared to also handle LLVM intrinsics?
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001168 Value *X;
Sanjay Patele45a83d2018-08-13 19:24:41 +00001169 switch (Func) {
1170 case LibFunc_sin:
1171 case LibFunc_sinf:
1172 case LibFunc_sinl:
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001173 case LibFunc_tan:
1174 case LibFunc_tanf:
1175 case LibFunc_tanl:
Sanjay Patele45a83d2018-08-13 19:24:41 +00001176 // sin(-X) --> -sin(X)
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001177 // tan(-X) --> -tan(X)
Sanjay Patele45a83d2018-08-13 19:24:41 +00001178 if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
Sanjay Patel8ba631d2018-08-16 22:46:20 +00001179 return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
Sanjay Patele45a83d2018-08-13 19:24:41 +00001180 break;
1181 case LibFunc_cos:
1182 case LibFunc_cosf:
1183 case LibFunc_cosl:
1184 // cos(-X) --> cos(X)
1185 if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
1186 return B.CreateCall(Call->getCalledFunction(), X, "cos");
1187 break;
1188 default:
1189 break;
1190 }
Sanjay Patelce4ddbe2018-08-13 17:40:49 +00001191 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001192}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001193
Weiming Zhao82130722015-12-04 22:00:47 +00001194static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1195 // Multiplications calculated using Addition Chains.
1196 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1197
1198 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1199
1200 if (InnerChain[Exp])
1201 return InnerChain[Exp];
1202
1203 static const unsigned AddChain[33][2] = {
1204 {0, 0}, // Unused.
1205 {0, 0}, // Unused (base case = pow1).
1206 {1, 1}, // Unused (pre-computed).
1207 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1208 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1209 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1210 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1211 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1212 };
1213
1214 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1215 getPow(InnerChain, AddChain[Exp][1], B));
1216 return InnerChain[Exp];
1217}
1218
Evandro Menezes4b390102018-08-17 17:59:53 +00001219/// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001220/// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x).
Evandro Menezes4b390102018-08-17 17:59:53 +00001221Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
1222 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1223 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1224 Module *Mod = Pow->getModule();
1225 Type *Ty = Pow->getType();
Evandro Menezes2123ea72018-08-30 19:04:51 +00001226 bool Ignored;
Evandro Menezes4b390102018-08-17 17:59:53 +00001227
1228 // Evaluate special cases related to a nested function as the base.
1229
1230 // pow(exp(x), y) -> exp(x * y)
1231 // pow(exp2(x), y) -> exp2(x * y)
Evandro Menezes253991c2018-08-27 22:11:15 +00001232 // If exp{,2}() is used only once, it is better to fold two transcendental
1233 // math functions into one. If used again, exp{,2}() would still have to be
1234 // called with the original argument, then keep both original transcendental
1235 // functions. However, this transformation is only safe with fully relaxed
1236 // math semantics, since, besides rounding differences, it changes overflow
1237 // and underflow behavior quite dramatically. For example:
Evandro Menezes4b390102018-08-17 17:59:53 +00001238 // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
1239 // Whereas:
1240 // exp(1000 * 0.001) = exp(1)
1241 // TODO: Loosen the requirement for fully relaxed math semantics.
1242 // TODO: Handle exp10() when more targets have it available.
1243 CallInst *BaseFn = dyn_cast<CallInst>(Base);
Evandro Menezes253991c2018-08-27 22:11:15 +00001244 if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
Evandro Menezes4b390102018-08-17 17:59:53 +00001245 LibFunc LibFn;
Evandro Menezes253991c2018-08-27 22:11:15 +00001246
Evandro Menezes4b390102018-08-17 17:59:53 +00001247 Function *CalleeFn = BaseFn->getCalledFunction();
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001248 if (CalleeFn &&
1249 TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
1250 StringRef ExpName;
1251 Intrinsic::ID ID;
Evandro Menezes253991c2018-08-27 22:11:15 +00001252 Value *ExpFn;
Mikael Holmene3605d02018-10-18 06:27:53 +00001253 LibFunc LibFnFloat;
1254 LibFunc LibFnDouble;
1255 LibFunc LibFnLongDouble;
Evandro Menezes253991c2018-08-27 22:11:15 +00001256
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001257 switch (LibFn) {
1258 default:
1259 return nullptr;
1260 case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
Evandro Menezes164ea102018-10-19 20:57:45 +00001261 ExpName = TLI->getName(LibFunc_exp);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001262 ID = Intrinsic::exp;
Mikael Holmene3605d02018-10-18 06:27:53 +00001263 LibFnFloat = LibFunc_expf;
1264 LibFnDouble = LibFunc_exp;
1265 LibFnLongDouble = LibFunc_expl;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001266 break;
1267 case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
Evandro Menezes164ea102018-10-19 20:57:45 +00001268 ExpName = TLI->getName(LibFunc_exp2);
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001269 ID = Intrinsic::exp2;
Mikael Holmene3605d02018-10-18 06:27:53 +00001270 LibFnFloat = LibFunc_exp2f;
1271 LibFnDouble = LibFunc_exp2;
1272 LibFnLongDouble = LibFunc_exp2l;
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001273 break;
1274 }
1275
Evandro Menezes253991c2018-08-27 22:11:15 +00001276 // Create new exp{,2}() with the product as its argument.
Evandro Menezes4b390102018-08-17 17:59:53 +00001277 Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
Evandro Menezes22e0bdf2018-08-29 17:59:48 +00001278 ExpFn = BaseFn->doesNotAccessMemory()
1279 ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
1280 FMul, ExpName)
Mikael Holmene3605d02018-10-18 06:27:53 +00001281 : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
1282 LibFnLongDouble, B,
1283 BaseFn->getAttributes());
Evandro Menezes253991c2018-08-27 22:11:15 +00001284
1285 // Since the new exp{,2}() is different from the original one, dead code
1286 // elimination cannot be trusted to remove it, since it may have side
1287 // effects (e.g., errno). When the only consumer for the original
1288 // exp{,2}() is pow(), then it has to be explicitly erased.
1289 BaseFn->replaceAllUsesWith(ExpFn);
Amara Emerson54f60252018-10-11 14:51:11 +00001290 eraseFromParent(BaseFn);
Evandro Menezes253991c2018-08-27 22:11:15 +00001291
1292 return ExpFn;
Evandro Menezes4b390102018-08-17 17:59:53 +00001293 }
1294 }
1295
1296 // Evaluate special cases related to a constant base.
1297
Evandro Menezes2123ea72018-08-30 19:04:51 +00001298 const APFloat *BaseF;
1299 if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
1300 return nullptr;
1301
1302 // pow(2.0 ** n, x) -> exp2(n * x)
1303 if (hasUnaryFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
1304 APFloat BaseR = APFloat(1.0);
1305 BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
1306 BaseR = BaseR / *BaseF;
1307 bool IsInteger = BaseF->isInteger(),
1308 IsReciprocal = BaseR.isInteger();
1309 const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
1310 APSInt NI(64, false);
1311 if ((IsInteger || IsReciprocal) &&
1312 !NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) &&
1313 NI > 1 && NI.isPowerOf2()) {
1314 double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
1315 Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
1316 if (Pow->doesNotAccessMemory())
1317 return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
1318 FMul, "exp2");
1319 else
Mikael Holmene3605d02018-10-18 06:27:53 +00001320 return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
1321 LibFunc_exp2l, B, Attrs);
Evandro Menezes2123ea72018-08-30 19:04:51 +00001322 }
Evandro Menezes4b390102018-08-17 17:59:53 +00001323 }
1324
1325 // pow(10.0, x) -> exp10(x)
1326 // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
1327 if (match(Base, m_SpecificFP(10.0)) &&
1328 hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
Mikael Holmene3605d02018-10-18 06:27:53 +00001329 return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
1330 LibFunc_exp10l, B, Attrs);
Evandro Menezes4b390102018-08-17 17:59:53 +00001331
1332 return nullptr;
1333}
1334
Florian Hahncc9dc592018-09-03 17:37:39 +00001335static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
1336 Module *M, IRBuilder<> &B,
1337 const TargetLibraryInfo *TLI) {
1338 // If errno is never set, then use the intrinsic for sqrt().
1339 if (NoErrno) {
1340 Function *SqrtFn =
1341 Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
1342 return B.CreateCall(SqrtFn, V, "sqrt");
1343 }
1344
1345 // Otherwise, use the libcall for sqrt().
1346 if (hasUnaryFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1347 LibFunc_sqrtl))
1348 // TODO: We also should check that the target can in fact lower the sqrt()
1349 // libcall. We currently have no way to ask this question, so we ask if
1350 // the target has a sqrt() libcall, which is not exactly the same.
Mikael Holmene3605d02018-10-18 06:27:53 +00001351 return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
1352 LibFunc_sqrtl, B, Attrs);
Florian Hahncc9dc592018-09-03 17:37:39 +00001353
1354 return nullptr;
1355}
1356
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001357/// Use square root in place of pow(x, +/-0.5).
1358Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
Evandro Menezesa7d48282018-07-30 16:20:04 +00001359 Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001360 AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
1361 Module *Mod = Pow->getModule();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001362 Type *Ty = Pow->getType();
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001363
Evandro Menezesa7d48282018-07-30 16:20:04 +00001364 const APFloat *ExpoF;
1365 if (!match(Expo, m_APFloat(ExpoF)) ||
1366 (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
1367 return nullptr;
1368
Florian Hahncc9dc592018-09-03 17:37:39 +00001369 Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
1370 if (!Sqrt)
Evandro Menezesa7d48282018-07-30 16:20:04 +00001371 return nullptr;
1372
Evandro Menezesc05c7e12018-08-16 15:58:08 +00001373 // Handle signed zero base by expanding to fabs(sqrt(x)).
1374 if (!Pow->hasNoSignedZeros()) {
1375 Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
1376 Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
1377 }
1378
1379 // Handle non finite base by expanding to
1380 // (x == -infinity ? +infinity : sqrt(x)).
1381 if (!Pow->hasNoInfs()) {
1382 Value *PosInf = ConstantFP::getInfinity(Ty),
1383 *NegInf = ConstantFP::getInfinity(Ty, true);
1384 Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
1385 Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
1386 }
1387
Evandro Menezes61e4e402018-07-31 22:11:02 +00001388 // If the exponent is negative, then get the reciprocal.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001389 if (ExpoF->isNegative())
1390 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001391
1392 return Sqrt;
1393}
1394
Evandro Menezesa7d48282018-07-30 16:20:04 +00001395Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
1396 Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
1397 Function *Callee = Pow->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001398 StringRef Name = Callee->getName();
Evandro Menezesa7d48282018-07-30 16:20:04 +00001399 Type *Ty = Pow->getType();
1400 Value *Shrunk = nullptr;
1401 bool Ignored;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001402
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001403 // Bail out if simplifying libcalls to pow() is disabled.
1404 if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
1405 return nullptr;
1406
Evandro Menezes61e4e402018-07-31 22:11:02 +00001407 // Propagate the math semantics from the call to any created instructions.
Evandro Menezesa7d48282018-07-30 16:20:04 +00001408 IRBuilder<>::FastMathFlagGuard Guard(B);
1409 B.setFastMathFlags(Pow->getFastMathFlags());
1410
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001411 // Shrink pow() to powf() if the arguments are single precision,
1412 // unless the result is expected to be double precision.
1413 if (UnsafeFPShrink &&
1414 Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
1415 Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
1416
Evandro Menezesa7d48282018-07-30 16:20:04 +00001417 // Evaluate special cases related to the base.
Davide Italiano27da1312016-08-07 20:27:03 +00001418
1419 // pow(1.0, x) -> 1.0
Evandro Menezes84e74362018-08-02 15:43:57 +00001420 if (match(Base, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001421 return Base;
1422
Evandro Menezes4b390102018-08-17 17:59:53 +00001423 if (Value *Exp = replacePowWithExp(Pow, B))
1424 return Exp;
Davide Italianoc8a79132015-11-03 20:32:23 +00001425
Evandro Menezesa7d48282018-07-30 16:20:04 +00001426 // Evaluate special cases related to the exponent.
1427
Evandro Menezesa7d48282018-07-30 16:20:04 +00001428 // pow(x, -1.0) -> 1.0 / x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001429 if (match(Expo, m_SpecificFP(-1.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001430 return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
1431
1432 // pow(x, 0.0) -> 1.0
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001433 if (match(Expo, m_SpecificFP(0.0)))
1434 return ConstantFP::get(Ty, 1.0);
Evandro Menezesa7d48282018-07-30 16:20:04 +00001435
1436 // pow(x, 1.0) -> x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001437 if (match(Expo, m_FPOne()))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001438 return Base;
1439
1440 // pow(x, 2.0) -> x * x
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001441 if (match(Expo, m_SpecificFP(2.0)))
Evandro Menezesa7d48282018-07-30 16:20:04 +00001442 return B.CreateFMul(Base, Base, "square");
Chris Bienemanad070d02014-09-17 20:55:46 +00001443
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001444 if (Value *Sqrt = replacePowWithSqrt(Pow, B))
1445 return Sqrt;
1446
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001447 // pow(x, n) -> x * x * x * ...
1448 const APFloat *ExpoF;
1449 if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
1450 // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
Florian Hahncc9dc592018-09-03 17:37:39 +00001451 // If the exponent is an integer+0.5 we generate a call to sqrt and an
1452 // additional fmul.
1453 // TODO: This whole transformation should be backend specific (e.g. some
1454 // backends might prefer libcalls or the limit for the exponent might
1455 // be different) and it should also consider optimizing for size.
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001456 APFloat LimF(ExpoF->getSemantics(), 33.0),
1457 ExpoA(abs(*ExpoF));
Florian Hahncc9dc592018-09-03 17:37:39 +00001458 if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
1459 // This transformation applies to integer or integer+0.5 exponents only.
1460 // For integer+0.5, we create a sqrt(Base) call.
1461 Value *Sqrt = nullptr;
1462 if (!ExpoA.isInteger()) {
1463 APFloat Expo2 = ExpoA;
1464 // To check if ExpoA is an integer + 0.5, we add it to itself. If there
1465 // is no floating point exception and the result is an integer, then
1466 // ExpoA == integer + 0.5
1467 if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
1468 return nullptr;
1469
1470 if (!Expo2.isInteger())
1471 return nullptr;
1472
1473 Sqrt =
1474 getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
1475 Pow->doesNotAccessMemory(), Pow->getModule(), B, TLI);
1476 }
1477
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001478 // We will memoize intermediate products of the Addition Chain.
1479 Value *InnerChain[33] = {nullptr};
1480 InnerChain[1] = Base;
1481 InnerChain[2] = B.CreateFMul(Base, Base, "square");
Weiming Zhao82130722015-12-04 22:00:47 +00001482
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001483 // We cannot readily convert a non-double type (like float) to a double.
1484 // So we first convert it to something which could be converted to double.
1485 ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
1486 Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
Weiming Zhao82130722015-12-04 22:00:47 +00001487
Florian Hahncc9dc592018-09-03 17:37:39 +00001488 // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
1489 if (Sqrt)
1490 FMul = B.CreateFMul(FMul, Sqrt);
1491
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001492 // If the exponent is negative, then get the reciprocal.
1493 if (ExpoF->isNegative())
1494 FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
Evandro Menezes61e4e402018-07-31 22:11:02 +00001495
Evandro Menezes5ecd6c12018-08-13 16:12:37 +00001496 return FMul;
1497 }
Weiming Zhao82130722015-12-04 22:00:47 +00001498 }
1499
Evandro Menezes6e137cb2018-08-06 19:40:17 +00001500 return Shrunk;
Chris Bienemanad070d02014-09-17 20:55:46 +00001501}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001502
Chris Bienemanad070d02014-09-17 20:55:46 +00001503Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1504 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001505 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001506 StringRef Name = Callee->getName();
1507 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001508 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001509
Chris Bienemanad070d02014-09-17 20:55:46 +00001510 Value *Op = CI->getArgOperand(0);
1511 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1512 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001513 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001514 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001515 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001516 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001517 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001518
1519 if (TLI->has(LdExp)) {
1520 Value *LdExpArg = nullptr;
1521 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1522 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1523 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1524 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1525 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1526 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1527 }
1528
1529 if (LdExpArg) {
1530 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1531 if (!Op->getType()->isFloatTy())
1532 One = ConstantExpr::getFPExtend(One, Op->getType());
1533
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001534 Module *M = CI->getModule();
James Y Knight13680222019-02-01 02:28:03 +00001535 FunctionCallee NewCallee = M->getOrInsertFunction(
1536 TLI->getName(LdExp), Op->getType(), Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001537 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001538 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1539 CI->setCallingConv(F->getCallingConv());
1540
1541 return CI;
1542 }
1543 }
1544 return Ret;
1545}
1546
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001547Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001548 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001549 // If we can shrink the call to a float function rather than a double
1550 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001551 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001552 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1553 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001554 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001555
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001556 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001557 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001558 if (CI->isFast()) {
1559 // If the call is 'fast', then anything we create here will also be 'fast'.
1560 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001561 } else {
1562 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001563 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001564 return nullptr;
1565 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1566 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001567 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001568 // might be impractical."
1569 FMF.setNoSignedZeros();
1570 FMF.setNoNaNs();
1571 }
Sanjay Patela2528152016-01-12 18:03:37 +00001572 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001573
1574 // We have a relaxed floating-point environment. We can ignore NaN-handling
1575 // and transform to a compare and select. We do not have to consider errno or
1576 // exceptions, because fmin/fmax do not have those.
1577 Value *Op0 = CI->getArgOperand(0);
1578 Value *Op1 = CI->getArgOperand(1);
1579 Value *Cmp = Callee->getName().startswith("fmin") ?
1580 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1581 return B.CreateSelect(Cmp, Op0, Op1);
1582}
1583
Davide Italianob8b71332015-11-29 20:58:04 +00001584Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1585 Function *Callee = CI->getCalledFunction();
1586 Value *Ret = nullptr;
1587 StringRef Name = Callee->getName();
1588 if (UnsafeFPShrink && hasFloatVersion(Name))
1589 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001590
Sanjay Patel629c4112017-11-06 16:27:15 +00001591 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001592 return Ret;
1593 Value *Op1 = CI->getArgOperand(0);
1594 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001595
Sanjay Patel629c4112017-11-06 16:27:15 +00001596 // The earlier call must also be 'fast' in order to do these transforms.
1597 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001598 return Ret;
1599
1600 // log(pow(x,y)) -> y*log(x)
1601 // This is only applicable to log, log2, log10.
1602 if (Name != "log" && Name != "log2" && Name != "log10")
1603 return Ret;
1604
1605 IRBuilder<>::FastMathFlagGuard Guard(B);
1606 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001607 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001608 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001609
David L. Jonesd21529f2017-01-23 23:16:46 +00001610 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001611 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001612 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001613 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001614 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001615 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001616 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001617
1618 // log(exp2(y)) -> y*log(2)
1619 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001620 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001621 return B.CreateFMul(
1622 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001623 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001624 Callee->getName(), B, Callee->getAttributes()),
1625 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001626 return Ret;
1627}
1628
Sanjay Patelc699a612014-10-16 18:48:17 +00001629Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1630 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001631 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001632 // TODO: Once we have a way (other than checking for the existince of the
1633 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1634 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001635 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001636 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001637 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001638
Sanjay Patel629c4112017-11-06 16:27:15 +00001639 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001640 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001641
Sanjay Patelc2d64612016-01-06 20:52:21 +00001642 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001643 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001644 return Ret;
1645
1646 // We're looking for a repeated factor in a multiplication tree,
1647 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001648 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001649 Value *Op0 = I->getOperand(0);
1650 Value *Op1 = I->getOperand(1);
1651 Value *RepeatOp = nullptr;
1652 Value *OtherOp = nullptr;
1653 if (Op0 == Op1) {
1654 // Simple match: the operands of the multiply are identical.
1655 RepeatOp = Op0;
1656 } else {
1657 // Look for a more complicated pattern: one of the operands is itself
1658 // a multiply, so search for a common factor in that multiply.
1659 // Note: We don't bother looking any deeper than this first level or for
1660 // variations of this pattern because instcombine's visitFMUL and/or the
1661 // reassociation pass should give us this form.
1662 Value *OtherMul0, *OtherMul1;
1663 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1664 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001665 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001666 // Matched: sqrt((x * x) * z)
1667 RepeatOp = OtherMul0;
1668 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001669 }
1670 }
1671 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001672 if (!RepeatOp)
1673 return Ret;
1674
1675 // Fast math flags for any created instructions should match the sqrt
1676 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001677 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001678 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001679
Sanjay Patelc2d64612016-01-06 20:52:21 +00001680 // If we found a repeated factor, hoist it out of the square root and
1681 // replace it with the fabs of that factor.
1682 Module *M = Callee->getParent();
1683 Type *ArgType = I->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001684 Function *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00001685 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1686 if (OtherOp) {
1687 // If we found a non-repeated factor, we still need to get its square
1688 // root. We then multiply that by the value that was simplified out
1689 // of the square root calculation.
James Y Knight7976eb52019-02-01 20:43:25 +00001690 Function *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
Sanjay Patelc2d64612016-01-06 20:52:21 +00001691 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1692 return B.CreateFMul(FabsCall, SqrtCall);
1693 }
1694 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001695}
1696
Sanjay Patelcddcd722016-01-06 19:23:35 +00001697// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001698Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1699 Function *Callee = CI->getCalledFunction();
1700 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001701 StringRef Name = Callee->getName();
1702 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001703 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001704
Davide Italiano51507d22015-11-04 23:36:56 +00001705 Value *Op1 = CI->getArgOperand(0);
1706 auto *OpC = dyn_cast<CallInst>(Op1);
1707 if (!OpC)
1708 return Ret;
1709
Sanjay Patel629c4112017-11-06 16:27:15 +00001710 // Both calls must be 'fast' in order to remove them.
1711 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001712 return Ret;
1713
Davide Italiano51507d22015-11-04 23:36:56 +00001714 // tan(atan(x)) -> x
1715 // tanf(atanf(x)) -> x
1716 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001717 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001718 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001719 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001720 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1721 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1722 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001723 Ret = OpC->getArgOperand(0);
1724 return Ret;
1725}
1726
Sanjay Patel57747212016-01-21 23:38:43 +00001727static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001728 // We can only hope to do anything useful if we can ignore things like errno
1729 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001730 // We already checked the prototype.
1731 return CI->hasFnAttr(Attribute::NoUnwind) &&
1732 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001733}
1734
Chris Bienemanad070d02014-09-17 20:55:46 +00001735static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1736 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001737 Value *&SinCos) {
1738 Type *ArgTy = Arg->getType();
1739 Type *ResTy;
1740 StringRef Name;
1741
1742 Triple T(OrigCallee->getParent()->getTargetTriple());
1743 if (UseFloat) {
1744 Name = "__sincospif_stret";
1745
1746 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1747 // x86_64 can't use {float, float} since that would be returned in both
1748 // xmm0 and xmm1, which isn't what a real struct would do.
1749 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001750 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1751 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001752 } else {
1753 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001754 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001755 }
1756
1757 Module *M = OrigCallee->getParent();
James Y Knight13680222019-02-01 02:28:03 +00001758 FunctionCallee Callee =
1759 M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001760
1761 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1762 // If the argument is an instruction, it must dominate all uses so put our
1763 // sincos call there.
1764 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1765 } else {
1766 // Otherwise (e.g. for a constant) the beginning of the function is as
1767 // good a place as any.
1768 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1769 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1770 }
1771
1772 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1773
1774 if (SinCos->getType()->isStructTy()) {
1775 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1776 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1777 } else {
1778 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1779 "sinpi");
1780 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1781 "cospi");
1782 }
1783}
Chris Bienemanad070d02014-09-17 20:55:46 +00001784
1785Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001786 // Make sure the prototype is as expected, otherwise the rest of the
1787 // function is probably invalid and likely to abort.
1788 if (!isTrigLibCall(CI))
1789 return nullptr;
1790
1791 Value *Arg = CI->getArgOperand(0);
1792 SmallVector<CallInst *, 1> SinCalls;
1793 SmallVector<CallInst *, 1> CosCalls;
1794 SmallVector<CallInst *, 1> SinCosCalls;
1795
1796 bool IsFloat = Arg->getType()->isFloatTy();
1797
1798 // Look for all compatible sinpi, cospi and sincospi calls with the same
1799 // argument. If there are enough (in some sense) we can make the
1800 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001801 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001802 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001803 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001804
1805 // It's only worthwhile if both sinpi and cospi are actually used.
1806 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1807 return nullptr;
1808
1809 Value *Sin, *Cos, *SinCos;
1810 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1811
Davide Italianof024a562016-12-16 02:28:38 +00001812 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1813 Value *Res) {
1814 for (CallInst *C : Calls)
1815 replaceAllUsesWith(C, Res);
1816 };
1817
Chris Bienemanad070d02014-09-17 20:55:46 +00001818 replaceTrigInsts(SinCalls, Sin);
1819 replaceTrigInsts(CosCalls, Cos);
1820 replaceTrigInsts(SinCosCalls, SinCos);
1821
1822 return nullptr;
1823}
1824
David Majnemerabae6b52016-03-19 04:53:02 +00001825void LibCallSimplifier::classifyArgUse(
1826 Value *Val, Function *F, bool IsFloat,
1827 SmallVectorImpl<CallInst *> &SinCalls,
1828 SmallVectorImpl<CallInst *> &CosCalls,
1829 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001830 CallInst *CI = dyn_cast<CallInst>(Val);
1831
1832 if (!CI)
1833 return;
1834
David Majnemerabae6b52016-03-19 04:53:02 +00001835 // Don't consider calls in other functions.
1836 if (CI->getFunction() != F)
1837 return;
1838
Chris Bienemanad070d02014-09-17 20:55:46 +00001839 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001840 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001841 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001842 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001843 return;
1844
1845 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001846 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001847 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001848 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001849 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001850 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001851 SinCosCalls.push_back(CI);
1852 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001853 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001854 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001855 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001856 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001857 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001858 SinCosCalls.push_back(CI);
1859 }
1860}
1861
Meador Inge7415f842012-11-25 20:45:27 +00001862//===----------------------------------------------------------------------===//
1863// Integer Library Call Optimizations
1864//===----------------------------------------------------------------------===//
1865
Chris Bienemanad070d02014-09-17 20:55:46 +00001866Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001867 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001868 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001869 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001870 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1871 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001872 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1874 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001875
Chris Bienemanad070d02014-09-17 20:55:46 +00001876 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1877 return B.CreateSelect(Cond, V, B.getInt32(0));
1878}
Meador Ingea0b6d872012-11-26 00:24:07 +00001879
Davide Italiano85ad36b2016-12-15 23:45:11 +00001880Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1881 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1882 Value *Op = CI->getArgOperand(0);
1883 Type *ArgType = Op->getType();
James Y Knight7976eb52019-02-01 20:43:25 +00001884 Function *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1885 Intrinsic::ctlz, ArgType);
Davide Italiano85ad36b2016-12-15 23:45:11 +00001886 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1887 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1888 V);
1889 return B.CreateIntCast(V, CI->getType(), false);
1890}
1891
Chris Bienemanad070d02014-09-17 20:55:46 +00001892Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel4b969352018-05-22 23:29:40 +00001893 // abs(x) -> x <s 0 ? -x : x
1894 // The negation has 'nsw' because abs of INT_MIN is undefined.
1895 Value *X = CI->getArgOperand(0);
1896 Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
1897 Value *NegX = B.CreateNSWNeg(X, "neg");
1898 return B.CreateSelect(IsNeg, NegX, X);
Chris Bienemanad070d02014-09-17 20:55:46 +00001899}
Meador Inge9a59ab62012-11-26 02:31:59 +00001900
Chris Bienemanad070d02014-09-17 20:55:46 +00001901Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001902 // isdigit(c) -> (c-'0') <u 10
1903 Value *Op = CI->getArgOperand(0);
1904 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1905 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1906 return B.CreateZExt(Op, CI->getType());
1907}
Meador Ingea62a39e2012-11-26 03:10:07 +00001908
Chris Bienemanad070d02014-09-17 20:55:46 +00001909Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001910 // isascii(c) -> c <u 128
1911 Value *Op = CI->getArgOperand(0);
1912 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1913 return B.CreateZExt(Op, CI->getType());
1914}
1915
1916Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001917 // toascii(c) -> c & 0x7f
1918 return B.CreateAnd(CI->getArgOperand(0),
1919 ConstantInt::get(CI->getType(), 0x7F));
1920}
Meador Inge604937d2012-11-26 03:38:52 +00001921
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001922Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1923 StringRef Str;
1924 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1925 return nullptr;
1926
1927 return convertStrToNumber(CI, Str, 10);
1928}
1929
1930Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1931 StringRef Str;
1932 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1933 return nullptr;
1934
1935 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1936 return nullptr;
1937
1938 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1939 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1940 }
1941
1942 return nullptr;
1943}
1944
Meador Inge08ca1152012-11-26 20:37:20 +00001945//===----------------------------------------------------------------------===//
1946// Formatting and IO Library Call Optimizations
1947//===----------------------------------------------------------------------===//
1948
Chris Bienemanad070d02014-09-17 20:55:46 +00001949static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001950
Chris Bienemanad070d02014-09-17 20:55:46 +00001951Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1952 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001953 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001954 // Error reporting calls should be cold, mark them as such.
1955 // This applies even to non-builtin calls: it is only a hint and applies to
1956 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001957
Chris Bienemanad070d02014-09-17 20:55:46 +00001958 // This heuristic was suggested in:
1959 // Improving Static Branch Prediction in a Compiler
1960 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1961 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001962 if (!CI->hasFnAttr(Attribute::Cold) &&
1963 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001964 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001965 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001966
Chris Bienemanad070d02014-09-17 20:55:46 +00001967 return nullptr;
1968}
1969
1970static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001971 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001972 return false;
1973
1974 if (StreamArg < 0)
1975 return true;
1976
1977 // These functions might be considered cold, but only if their stream
1978 // argument is stderr.
1979
1980 if (StreamArg >= (int)CI->getNumArgOperands())
1981 return false;
1982 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1983 if (!LI)
1984 return false;
1985 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1986 if (!GV || !GV->isDeclaration())
1987 return false;
1988 return GV->getName() == "stderr";
1989}
1990
1991Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1992 // Check for a fixed format string.
1993 StringRef FormatStr;
1994 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001995 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001996
Chris Bienemanad070d02014-09-17 20:55:46 +00001997 // Empty format string -> noop.
1998 if (FormatStr.empty()) // Tolerate printf's declared void.
1999 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00002000
Chris Bienemanad070d02014-09-17 20:55:46 +00002001 // Do not do any of the following transformations if the printf return value
2002 // is used, in general the printf return value is not compatible with either
2003 // putchar() or puts().
2004 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00002005 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00002006
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00002007 // printf("x") -> putchar('x'), even for "%" and "%%".
2008 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00002009 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00002010
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002011 // printf("%s", "a") --> putchar('a')
2012 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
2013 StringRef ChrStr;
2014 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
2015 return nullptr;
2016 if (ChrStr.size() != 1)
2017 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00002018 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00002019 }
2020
Chris Bienemanad070d02014-09-17 20:55:46 +00002021 // printf("foo\n") --> puts("foo")
2022 if (FormatStr[FormatStr.size() - 1] == '\n' &&
2023 FormatStr.find('%') == StringRef::npos) { // No format characters.
2024 // Create a string literal with no \n on it. We expect the constant merge
2025 // pass to be run after this pass, to merge duplicate strings.
2026 FormatStr = FormatStr.drop_back();
2027 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00002028 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002029 }
Meador Inge08ca1152012-11-26 20:37:20 +00002030
Chris Bienemanad070d02014-09-17 20:55:46 +00002031 // Optimize specific format strings.
2032 // printf("%c", chr) --> putchar(chr)
2033 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002034 CI->getArgOperand(1)->getType()->isIntegerTy())
2035 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002036
2037 // printf("%s\n", str) --> puts(str)
2038 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00002039 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00002040 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002041 return nullptr;
2042}
2043
2044Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
2045
2046 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002048 if (Value *V = optimizePrintFString(CI, B)) {
2049 return V;
2050 }
2051
2052 // printf(format, ...) -> iprintf(format, ...) if no floating point
2053 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002054 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002055 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002056 FunctionCallee IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00002057 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00002058 CallInst *New = cast<CallInst>(CI->clone());
2059 New->setCalledFunction(IPrintFFn);
2060 B.Insert(New);
2061 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00002062 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002063
2064 // printf(format, ...) -> __small_printf(format, ...) if no 128-bit floating point
2065 // arguments.
2066 if (TLI->has(LibFunc_small_printf) && !callHasFP128Argument(CI)) {
2067 Module *M = B.GetInsertBlock()->getParent()->getParent();
2068 auto SmallPrintFFn =
2069 M->getOrInsertFunction(TLI->getName(LibFunc_small_printf),
2070 FT, Callee->getAttributes());
2071 CallInst *New = cast<CallInst>(CI->clone());
2072 New->setCalledFunction(SmallPrintFFn);
2073 B.Insert(New);
2074 return New;
2075 }
2076
Chris Bienemanad070d02014-09-17 20:55:46 +00002077 return nullptr;
2078}
Meador Inge08ca1152012-11-26 20:37:20 +00002079
Chris Bienemanad070d02014-09-17 20:55:46 +00002080Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
2081 // Check for a fixed format string.
2082 StringRef FormatStr;
2083 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00002084 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00002085
Chris Bienemanad070d02014-09-17 20:55:46 +00002086 // If we just have a format string (nothing else crazy) transform it.
2087 if (CI->getNumArgOperands() == 2) {
2088 // Make sure there's no % in the constant array. We could try to handle
2089 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002090 if (FormatStr.find('%') != StringRef::npos)
2091 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002092
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002093 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
2094 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002095 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002096 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00002097 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00002098 }
Meador Ingef8e72502012-11-29 15:45:43 +00002099
Chris Bienemanad070d02014-09-17 20:55:46 +00002100 // The remaining optimizations require the format string to be "%s" or "%c"
2101 // and have an extra operand.
2102 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2103 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00002104 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00002105
Chris Bienemanad070d02014-09-17 20:55:46 +00002106 // Decode the second character of the format string.
2107 if (FormatStr[1] == 'c') {
2108 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2109 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2110 return nullptr;
2111 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00002112 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00002113 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00002114 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00002115 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00002116
Chris Bienemanad070d02014-09-17 20:55:46 +00002117 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00002118 }
2119
Chris Bienemanad070d02014-09-17 20:55:46 +00002120 if (FormatStr[1] == 's') {
Fangrui Songf2609672019-03-12 10:31:52 +00002121 // sprintf(dest, "%s", str) -> llvm.memcpy(align 1 dest, align 1 str,
2122 // strlen(str)+1)
Chris Bienemanad070d02014-09-17 20:55:46 +00002123 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2124 return nullptr;
2125
Sanjay Pateld3112a52016-01-19 19:46:10 +00002126 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002127 if (!Len)
2128 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00002129 Value *IncLen =
2130 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002131 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00002132
2133 // The sprintf result is the unincremented number of bytes in the string.
2134 return B.CreateIntCast(Len, CI->getType(), false);
2135 }
2136 return nullptr;
2137}
2138
2139Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
2140 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002141 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002142 if (Value *V = optimizeSPrintFString(CI, B)) {
2143 return V;
2144 }
2145
2146 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
2147 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002148 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002149 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002150 FunctionCallee SIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002151 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
2152 CallInst *New = cast<CallInst>(CI->clone());
2153 New->setCalledFunction(SIPrintFFn);
2154 B.Insert(New);
2155 return New;
2156 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002157
2158 // sprintf(str, format, ...) -> __small_sprintf(str, format, ...) if no 128-bit
2159 // floating point arguments.
2160 if (TLI->has(LibFunc_small_sprintf) && !callHasFP128Argument(CI)) {
2161 Module *M = B.GetInsertBlock()->getParent()->getParent();
2162 auto SmallSPrintFFn =
2163 M->getOrInsertFunction(TLI->getName(LibFunc_small_sprintf),
2164 FT, Callee->getAttributes());
2165 CallInst *New = cast<CallInst>(CI->clone());
2166 New->setCalledFunction(SmallSPrintFFn);
2167 B.Insert(New);
2168 return New;
2169 }
2170
Chris Bienemanad070d02014-09-17 20:55:46 +00002171 return nullptr;
2172}
2173
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002174Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
2175 // Check for a fixed format string.
2176 StringRef FormatStr;
2177 if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
2178 return nullptr;
2179
2180 // Check for size
2181 ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2182 if (!Size)
2183 return nullptr;
2184
2185 uint64_t N = Size->getZExtValue();
2186
2187 // If we just have a format string (nothing else crazy) transform it.
2188 if (CI->getNumArgOperands() == 3) {
2189 // Make sure there's no % in the constant array. We could try to handle
2190 // %% -> % in the future if we cared.
David Bolvansky5430b7372018-05-31 16:39:27 +00002191 if (FormatStr.find('%') != StringRef::npos)
2192 return nullptr; // we found a format specifier, bail out.
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002193
2194 if (N == 0)
2195 return ConstantInt::get(CI->getType(), FormatStr.size());
2196 else if (N < FormatStr.size() + 1)
2197 return nullptr;
2198
Fangrui Songf2609672019-03-12 10:31:52 +00002199 // snprintf(dst, size, fmt) -> llvm.memcpy(align 1 dst, align 1 fmt,
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002200 // strlen(fmt)+1)
2201 B.CreateMemCpy(
2202 CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
2203 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
2204 FormatStr.size() + 1)); // Copy the null byte.
2205 return ConstantInt::get(CI->getType(), FormatStr.size());
2206 }
2207
2208 // The remaining optimizations require the format string to be "%s" or "%c"
2209 // and have an extra operand.
2210 if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
2211 CI->getNumArgOperands() == 4) {
2212
2213 // Decode the second character of the format string.
2214 if (FormatStr[1] == 'c') {
2215 if (N == 0)
2216 return ConstantInt::get(CI->getType(), 1);
2217 else if (N == 1)
2218 return nullptr;
2219
2220 // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
2221 if (!CI->getArgOperand(3)->getType()->isIntegerTy())
2222 return nullptr;
2223 Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
2224 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
2225 B.CreateStore(V, Ptr);
2226 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
2227 B.CreateStore(B.getInt8(0), Ptr);
2228
2229 return ConstantInt::get(CI->getType(), 1);
2230 }
2231
2232 if (FormatStr[1] == 's') {
2233 // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
2234 StringRef Str;
2235 if (!getConstantStringInfo(CI->getArgOperand(3), Str))
2236 return nullptr;
2237
2238 if (N == 0)
2239 return ConstantInt::get(CI->getType(), Str.size());
2240 else if (N < Str.size() + 1)
2241 return nullptr;
2242
2243 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
2244 ConstantInt::get(CI->getType(), Str.size() + 1));
2245
2246 // The snprintf result is the unincremented number of bytes in the string.
2247 return ConstantInt::get(CI->getType(), Str.size());
2248 }
2249 }
2250 return nullptr;
2251}
2252
2253Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
2254 if (Value *V = optimizeSnPrintFString(CI, B)) {
2255 return V;
2256 }
2257
2258 return nullptr;
2259}
2260
Chris Bienemanad070d02014-09-17 20:55:46 +00002261Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
2262 optimizeErrorReporting(CI, B, 0);
2263
2264 // All the optimizations depend on the format string.
2265 StringRef FormatStr;
2266 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
2267 return nullptr;
2268
2269 // Do not do any of the following transformations if the fprintf return
2270 // value is used, in general the fprintf return value is not compatible
2271 // with fwrite(), fputc() or fputs().
2272 if (!CI->use_empty())
2273 return nullptr;
2274
2275 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
2276 if (CI->getNumArgOperands() == 2) {
David Bolvansky5430b7372018-05-31 16:39:27 +00002277 // Could handle %% -> % if we cared.
2278 if (FormatStr.find('%') != StringRef::npos)
2279 return nullptr; // We found a format specifier.
Chris Bienemanad070d02014-09-17 20:55:46 +00002280
Sanjay Pateld3112a52016-01-19 19:46:10 +00002281 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002282 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002283 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00002284 CI->getArgOperand(0), B, DL, TLI);
2285 }
2286
2287 // The remaining optimizations require the format string to be "%s" or "%c"
2288 // and have an extra operand.
2289 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
2290 CI->getNumArgOperands() < 3)
2291 return nullptr;
2292
2293 // Decode the second character of the format string.
2294 if (FormatStr[1] == 'c') {
2295 // fprintf(F, "%c", chr) --> fputc(chr, F)
2296 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
2297 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002298 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002299 }
2300
2301 if (FormatStr[1] == 's') {
2302 // fprintf(F, "%s", str) --> fputs(str, F)
2303 if (!CI->getArgOperand(2)->getType()->isPointerTy())
2304 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00002305 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002306 }
2307 return nullptr;
2308}
2309
2310Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
2311 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00002312 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00002313 if (Value *V = optimizeFPrintFString(CI, B)) {
2314 return V;
2315 }
2316
2317 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
2318 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00002319 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002320 Module *M = B.GetInsertBlock()->getParent()->getParent();
James Y Knight13680222019-02-01 02:28:03 +00002321 FunctionCallee FIPrintFFn =
Chris Bienemanad070d02014-09-17 20:55:46 +00002322 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
2323 CallInst *New = cast<CallInst>(CI->clone());
2324 New->setCalledFunction(FIPrintFFn);
2325 B.Insert(New);
2326 return New;
2327 }
Alon Zakaib4f99912019-04-03 01:08:35 +00002328
2329 // fprintf(stream, format, ...) -> __small_fprintf(stream, format, ...) if no
2330 // 128-bit floating point arguments.
2331 if (TLI->has(LibFunc_small_fprintf) && !callHasFP128Argument(CI)) {
2332 Module *M = B.GetInsertBlock()->getParent()->getParent();
2333 auto SmallFPrintFFn =
2334 M->getOrInsertFunction(TLI->getName(LibFunc_small_fprintf),
2335 FT, Callee->getAttributes());
2336 CallInst *New = cast<CallInst>(CI->clone());
2337 New->setCalledFunction(SmallFPrintFFn);
2338 B.Insert(New);
2339 return New;
2340 }
2341
Chris Bienemanad070d02014-09-17 20:55:46 +00002342 return nullptr;
2343}
2344
2345Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
2346 optimizeErrorReporting(CI, B, 3);
2347
Chris Bienemanad070d02014-09-17 20:55:46 +00002348 // Get the element size and count.
2349 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2350 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
David Bolvanskyca22d422018-05-16 11:39:52 +00002351 if (SizeC && CountC) {
2352 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +00002353
David Bolvanskyca22d422018-05-16 11:39:52 +00002354 // If this is writing zero records, remove the call (it's a noop).
2355 if (Bytes == 0)
2356 return ConstantInt::get(CI->getType(), 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002357
David Bolvanskyca22d422018-05-16 11:39:52 +00002358 // If this is writing one byte, turn it into fputc.
2359 // This optimisation is only valid, if the return value is unused.
2360 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
James Y Knight14359ef2019-02-01 20:44:24 +00002361 Value *Char = B.CreateLoad(B.getInt8Ty(),
2362 castToCStr(CI->getArgOperand(0), B), "char");
David Bolvanskyca22d422018-05-16 11:39:52 +00002363 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
2364 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2365 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002366 }
2367
David Bolvanskyca22d422018-05-16 11:39:52 +00002368 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2369 return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2370 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2371 TLI);
2372
Chris Bienemanad070d02014-09-17 20:55:46 +00002373 return nullptr;
2374}
2375
2376Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2377 optimizeErrorReporting(CI, B, 1);
2378
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002379 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2380 // requires more arguments and thus extra MOVs are required.
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002381 bool OptForSize = CI->getFunction()->hasOptSize() ||
2382 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
2383 if (OptForSize)
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002384 return nullptr;
2385
David Bolvanskyca22d422018-05-16 11:39:52 +00002386 // Check if has any use
2387 if (!CI->use_empty()) {
2388 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2389 return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2390 TLI);
2391 else
2392 // We can't optimize if return value is used.
2393 return nullptr;
2394 }
Chris Bienemanad070d02014-09-17 20:55:46 +00002395
Fangrui Songf2609672019-03-12 10:31:52 +00002396 // fputs(s,F) --> fwrite(s,strlen(s),1,F)
David Bolvansky1f343fa2018-05-22 20:27:36 +00002397 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Bienemanad070d02014-09-17 20:55:46 +00002398 if (!Len)
2399 return nullptr;
2400
2401 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002402 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002403 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002404 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002405 CI->getArgOperand(1), B, DL, TLI);
2406}
2407
David Bolvanskyca22d422018-05-16 11:39:52 +00002408Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
2409 optimizeErrorReporting(CI, B, 1);
2410
2411 if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
2412 return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
2413 TLI);
2414
2415 return nullptr;
2416}
2417
2418Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
2419 if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
2420 return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
2421
2422 return nullptr;
2423}
2424
2425Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
2426 if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
2427 return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2428 CI->getArgOperand(2), B, TLI);
2429
2430 return nullptr;
2431}
2432
2433Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
2434 if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
2435 return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
2436 CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
2437 TLI);
2438
2439 return nullptr;
2440}
2441
Chris Bienemanad070d02014-09-17 20:55:46 +00002442Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002443 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00002444 return nullptr;
2445
Fangrui Songb1dfbeb2019-03-12 14:20:22 +00002446 // Check for a constant string.
2447 // puts("") -> putchar('\n')
2448 StringRef Str;
2449 if (getConstantStringInfo(CI->getArgOperand(0), Str) && Str.empty())
2450 return emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002451
2452 return nullptr;
2453}
2454
2455bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002456 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002457 SmallString<20> FloatFuncName = FuncName;
2458 FloatFuncName += 'f';
2459 if (TLI->getLibFunc(FloatFuncName, Func))
2460 return TLI->has(Func);
2461 return false;
2462}
Meador Inge7fb2f732012-10-13 16:45:32 +00002463
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002464Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2465 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002466 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002467 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002468 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002469 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002470 // Make sure we never change the calling convention.
2471 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002472 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002473 "Optimizing string/memory libcall would change the calling convention");
2474 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002475 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002476 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002477 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002478 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002479 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002480 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002481 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002482 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002483 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002484 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002486 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002487 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002488 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002489 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002490 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002491 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002492 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002493 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002494 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002495 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002496 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002497 case LibFunc_strtol:
2498 case LibFunc_strtod:
2499 case LibFunc_strtof:
2500 case LibFunc_strtoul:
2501 case LibFunc_strtoll:
2502 case LibFunc_strtold:
2503 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002504 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002505 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002506 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002507 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002508 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002509 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002510 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002511 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002512 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002513 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002514 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002515 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002516 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002517 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002518 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002519 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002520 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002521 case LibFunc_realloc:
2522 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002523 case LibFunc_wcslen:
2524 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002525 default:
2526 break;
2527 }
2528 }
2529 return nullptr;
2530}
2531
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002532Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2533 LibFunc Func,
2534 IRBuilder<> &Builder) {
2535 // Don't optimize calls that require strict floating point semantics.
2536 if (CI->isStrictFP())
2537 return nullptr;
2538
Sanjay Patele45a83d2018-08-13 19:24:41 +00002539 if (Value *V = optimizeTrigReflections(CI, Func, Builder))
2540 return V;
2541
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002542 switch (Func) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002543 case LibFunc_sinpif:
2544 case LibFunc_sinpi:
2545 case LibFunc_cospif:
2546 case LibFunc_cospi:
2547 return optimizeSinCosPi(CI, Builder);
2548 case LibFunc_powf:
2549 case LibFunc_pow:
2550 case LibFunc_powl:
2551 return optimizePow(CI, Builder);
2552 case LibFunc_exp2l:
2553 case LibFunc_exp2:
2554 case LibFunc_exp2f:
2555 return optimizeExp2(CI, Builder);
2556 case LibFunc_fabsf:
2557 case LibFunc_fabs:
2558 case LibFunc_fabsl:
2559 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2560 case LibFunc_sqrtf:
2561 case LibFunc_sqrt:
2562 case LibFunc_sqrtl:
2563 return optimizeSqrt(CI, Builder);
2564 case LibFunc_log:
2565 case LibFunc_log10:
2566 case LibFunc_log1p:
2567 case LibFunc_log2:
2568 case LibFunc_logb:
2569 return optimizeLog(CI, Builder);
2570 case LibFunc_tan:
2571 case LibFunc_tanf:
2572 case LibFunc_tanl:
2573 return optimizeTan(CI, Builder);
2574 case LibFunc_ceil:
2575 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2576 case LibFunc_floor:
2577 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2578 case LibFunc_round:
2579 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2580 case LibFunc_nearbyint:
2581 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2582 case LibFunc_rint:
2583 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2584 case LibFunc_trunc:
2585 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2586 case LibFunc_acos:
2587 case LibFunc_acosh:
2588 case LibFunc_asin:
2589 case LibFunc_asinh:
2590 case LibFunc_atan:
2591 case LibFunc_atanh:
2592 case LibFunc_cbrt:
2593 case LibFunc_cosh:
2594 case LibFunc_exp:
2595 case LibFunc_exp10:
2596 case LibFunc_expm1:
Sanjay Patele45a83d2018-08-13 19:24:41 +00002597 case LibFunc_cos:
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002598 case LibFunc_sin:
2599 case LibFunc_sinh:
2600 case LibFunc_tanh:
2601 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2602 return optimizeUnaryDoubleFP(CI, Builder, true);
2603 return nullptr;
2604 case LibFunc_copysign:
2605 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2606 return optimizeBinaryDoubleFP(CI, Builder);
2607 return nullptr;
2608 case LibFunc_fminf:
2609 case LibFunc_fmin:
2610 case LibFunc_fminl:
2611 case LibFunc_fmaxf:
2612 case LibFunc_fmax:
2613 case LibFunc_fmaxl:
2614 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002615 case LibFunc_cabs:
2616 case LibFunc_cabsf:
2617 case LibFunc_cabsl:
2618 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002619 default:
2620 return nullptr;
2621 }
2622}
2623
Chris Bienemanad070d02014-09-17 20:55:46 +00002624Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002625 // TODO: Split out the code below that operates on FP calls so that
2626 // we can all non-FP calls with the StrictFP attribute to be
2627 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002628 if (CI->isNoBuiltin())
2629 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002630
David L. Jonesd21529f2017-01-23 23:16:46 +00002631 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002632 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002633
2634 SmallVector<OperandBundleDef, 2> OpBundles;
2635 CI->getOperandBundlesAsDefs(OpBundles);
2636 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002637 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002638
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002639 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002640 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002641 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002642 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2643 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002644 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002645 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002646
Sanjay Patel848309d2014-10-23 21:52:45 +00002647 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002648 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002649 if (!isCallingConvC)
2650 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002651 // The FP intrinsics have corresponding constrained versions so we don't
2652 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002653 switch (II->getIntrinsicID()) {
2654 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002655 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002656 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002657 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002658 case Intrinsic::log:
2659 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002660 case Intrinsic::sqrt:
2661 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002662 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002663 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002664 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002665 }
2666 }
2667
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002668 // Also try to simplify calls to fortified library functions.
2669 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2670 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002671 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002672 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2673 // Use an IR Builder from SimplifiedCI if available instead of CI
2674 // to guarantee we reach all uses we might replace later on.
2675 IRBuilder<> TmpBuilder(SimplifiedCI);
2676 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002677 // If we were able to further simplify, remove the now redundant call.
2678 SimplifiedCI->replaceAllUsesWith(V);
Amara Emerson54f60252018-10-11 14:51:11 +00002679 eraseFromParent(SimplifiedCI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002680 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002681 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002682 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002683 return SimplifiedFortifiedCI;
2684 }
2685
Meador Inge20255ef2013-03-12 00:08:29 +00002686 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002687 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002688 // We never change the calling convention.
2689 if (!ignoreCallingConv(Func) && !isCallingConvC)
2690 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002691 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2692 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002693 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2694 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002695 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002696 case LibFunc_ffs:
2697 case LibFunc_ffsl:
2698 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002699 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002700 case LibFunc_fls:
2701 case LibFunc_flsl:
2702 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002703 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002704 case LibFunc_abs:
2705 case LibFunc_labs:
2706 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002707 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002708 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002709 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002710 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002711 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002712 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002713 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002714 case LibFunc_atoi:
2715 case LibFunc_atol:
2716 case LibFunc_atoll:
2717 return optimizeAtoi(CI, Builder);
2718 case LibFunc_strtol:
2719 case LibFunc_strtoll:
2720 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002721 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002722 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002723 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002724 return optimizeSPrintF(CI, Builder);
David Bolvanskycd93c4e2018-05-11 17:50:49 +00002725 case LibFunc_snprintf:
2726 return optimizeSnPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002727 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002728 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002729 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002730 return optimizeFWrite(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002731 case LibFunc_fread:
2732 return optimizeFRead(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002733 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002734 return optimizeFPuts(CI, Builder);
David Bolvanskyca22d422018-05-16 11:39:52 +00002735 case LibFunc_fgets:
2736 return optimizeFGets(CI, Builder);
2737 case LibFunc_fputc:
2738 return optimizeFPutc(CI, Builder);
2739 case LibFunc_fgetc:
2740 return optimizeFGetc(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002741 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002742 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002743 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002744 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002745 case LibFunc_vfprintf:
2746 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002747 return optimizeErrorReporting(CI, Builder, 0);
Chris Bienemanad070d02014-09-17 20:55:46 +00002748 default:
2749 return nullptr;
2750 }
Meador Inge20255ef2013-03-12 00:08:29 +00002751 }
Craig Topperf40110f2014-04-25 05:29:35 +00002752 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002753}
2754
Chandler Carruth92803822015-01-21 02:11:59 +00002755LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002756 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002757 OptimizationRemarkEmitter &ORE,
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002758 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
Amara Emerson54f60252018-10-11 14:51:11 +00002759 function_ref<void(Instruction *, Value *)> Replacer,
2760 function_ref<void(Instruction *)> Eraser)
Hiroshi Yamauchi09e539f2019-04-15 16:49:00 +00002761 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE), BFI(BFI), PSI(PSI),
Amara Emerson54f60252018-10-11 14:51:11 +00002762 UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002763
2764void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2765 // Indirect through the replacer used in this instance.
2766 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002767}
2768
Amara Emerson54f60252018-10-11 14:51:11 +00002769void LibCallSimplifier::eraseFromParent(Instruction *I) {
2770 Eraser(I);
2771}
2772
Meador Ingedfb08a22013-06-20 19:48:07 +00002773// TODO:
2774// Additional cases that we need to add to this file:
2775//
2776// cbrt:
2777// * cbrt(expN(X)) -> expN(x/3)
2778// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002779// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002780//
2781// exp, expf, expl:
2782// * exp(log(x)) -> x
2783//
2784// log, logf, logl:
2785// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002786// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002787// * log(exp10(y)) -> y*log(10)
2788// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002789//
Meador Ingedfb08a22013-06-20 19:48:07 +00002790// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002791// * pow(sqrt(x),y) -> pow(x,y*0.5)
2792// * pow(pow(x,y),z)-> pow(x,y*z)
2793//
Meador Ingedfb08a22013-06-20 19:48:07 +00002794// signbit:
2795// * signbit(cnst) -> cnst'
2796// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2797//
2798// sqrt, sqrtf, sqrtl:
2799// * sqrt(expN(x)) -> expN(x*0.5)
2800// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2801// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2802//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002803
2804//===----------------------------------------------------------------------===//
2805// Fortified Library Call Optimizations
2806//===----------------------------------------------------------------------===//
2807
2808bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2809 unsigned ObjSizeOp,
2810 unsigned SizeOp,
2811 bool isString) {
2812 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2813 return true;
2814 if (ConstantInt *ObjSizeCI =
2815 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002816 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002817 return true;
2818 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2819 if (OnlyLowerUnknownSize)
2820 return false;
2821 if (isString) {
David Bolvansky1f343fa2018-05-22 20:27:36 +00002822 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002823 // If the length is 0 we don't know how long it is and so we can't
2824 // remove the check.
2825 if (Len == 0)
2826 return false;
2827 return ObjSizeCI->getZExtValue() >= Len;
2828 }
2829 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2830 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2831 }
2832 return false;
2833}
2834
Sanjay Pateld707db92015-12-31 16:10:49 +00002835Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2836 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002837 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002838 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2839 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002840 return CI->getArgOperand(0);
2841 }
2842 return nullptr;
2843}
2844
Sanjay Pateld707db92015-12-31 16:10:49 +00002845Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2846 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002847 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002848 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2849 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002850 return CI->getArgOperand(0);
2851 }
2852 return nullptr;
2853}
2854
Sanjay Pateld707db92015-12-31 16:10:49 +00002855Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2856 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002857 // TODO: Try foldMallocMemset() here.
2858
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002859 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2860 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2861 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2862 return CI->getArgOperand(0);
2863 }
2864 return nullptr;
2865}
2866
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002867Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2868 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002869 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002870 Function *Callee = CI->getCalledFunction();
2871 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002872 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002873 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2874 *ObjSize = CI->getArgOperand(2);
2875
2876 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002877 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002878 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002879 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002880 }
2881
2882 // If a) we don't have any length information, or b) we know this will
2883 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2884 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2885 // TODO: It might be nice to get a maximum length out of the possible
2886 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002887 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002888 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002889
David Blaikie65fab6d2015-04-03 21:32:06 +00002890 if (OnlyLowerUnknownSize)
2891 return nullptr;
2892
2893 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
David Bolvansky1f343fa2018-05-22 20:27:36 +00002894 uint64_t Len = GetStringLength(Src);
David Blaikie65fab6d2015-04-03 21:32:06 +00002895 if (Len == 0)
2896 return nullptr;
2897
2898 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2899 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002900 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002901 // If the function was an __stpcpy_chk, and we were able to fold it into
2902 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002903 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002904 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2905 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002906}
2907
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002908Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2909 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002910 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002911 Function *Callee = CI->getCalledFunction();
2912 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002913 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002914 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002915 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002916 return Ret;
2917 }
2918 return nullptr;
2919}
2920
2921Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002922 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2923 // Some clang users checked for _chk libcall availability using:
2924 // __has_builtin(__builtin___memcpy_chk)
2925 // When compiling with -fno-builtin, this is always true.
2926 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2927 // end up with fortified libcalls, which isn't acceptable in a freestanding
2928 // environment which only provides their non-fortified counterparts.
2929 //
2930 // Until we change clang and/or teach external users to check for availability
2931 // differently, disregard the "nobuiltin" attribute and TLI::has.
2932 //
2933 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002934
David L. Jonesd21529f2017-01-23 23:16:46 +00002935 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002936 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002937
2938 SmallVector<OperandBundleDef, 2> OpBundles;
2939 CI->getOperandBundlesAsDefs(OpBundles);
2940 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002941 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002942
Ahmed Bougachad765a822016-04-27 19:04:35 +00002943 // First, check that this is a known library functions and that the prototype
2944 // is correct.
2945 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002946 return nullptr;
2947
2948 // We never change the calling convention.
2949 if (!ignoreCallingConv(Func) && !isCallingConvC)
2950 return nullptr;
2951
2952 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002953 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002954 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002955 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002956 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002957 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002958 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002959 case LibFunc_stpcpy_chk:
2960 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002961 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002962 case LibFunc_stpncpy_chk:
2963 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002964 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002965 default:
2966 break;
2967 }
2968 return nullptr;
2969}
2970
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002971FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2972 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
Sanjay Patel4b969352018-05-22 23:29:40 +00002973 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}