blob: ce804aef7da271c860a029a902374ab30c4ff619 [file] [log] [blame]
Meador Ingedf796f82012-10-13 16:45:24 +00001//===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Craig Topper2915bc02018-03-01 20:05:09 +000010// This file implements the library calls simplifier. It does not implement
11// any pass, but can't be used by other passes to do simplifications.
Meador Ingedf796f82012-10-13 16:45:24 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000016#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000017#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000018#include "llvm/ADT/Triple.h"
Sanjay Patel82ec8722017-08-21 19:13:14 +000019#include "llvm/Analysis/ConstantFolding.h"
Adam Nemet0965da22017-10-09 23:19:02 +000020#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000022#include "llvm/Analysis/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Function.h"
26#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000027#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000031#include "llvm/IR/PatternMatch.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000033#include "llvm/Support/KnownBits.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
35
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000040 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
41 cl::init(false),
42 cl::desc("Enable unsafe double to float "
43 "shrinking for math lib calls"));
44
45
Meador Ingedf796f82012-10-13 16:45:24 +000046//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000047// Helper Functions
48//===----------------------------------------------------------------------===//
49
David L. Jonesd21529f2017-01-23 23:16:46 +000050static bool ignoreCallingConv(LibFunc Func) {
51 return Func == LibFunc_abs || Func == LibFunc_labs ||
52 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000053}
54
Sam Parker214f7bf2016-09-13 12:10:14 +000055static bool isCallingConvCCompatible(CallInst *CI) {
56 switch(CI->getCallingConv()) {
57 default:
58 return false;
59 case llvm::CallingConv::C:
60 return true;
61 case llvm::CallingConv::ARM_APCS:
62 case llvm::CallingConv::ARM_AAPCS:
63 case llvm::CallingConv::ARM_AAPCS_VFP: {
64
65 // The iOS ABI diverges from the standard in some cases, so for now don't
66 // try to simplify those calls.
67 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
68 return false;
69
70 auto *FuncTy = CI->getFunctionType();
71
72 if (!FuncTy->getReturnType()->isPointerTy() &&
73 !FuncTy->getReturnType()->isIntegerTy() &&
74 !FuncTy->getReturnType()->isVoidTy())
75 return false;
76
77 for (auto Param : FuncTy->params()) {
78 if (!Param->isPointerTy() && !Param->isIntegerTy())
79 return false;
80 }
81 return true;
82 }
83 }
84 return false;
85}
86
Sanjay Pateld707db92015-12-31 16:10:49 +000087/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000088static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000089 for (User *U : V->users()) {
90 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000091 if (IC->isEquality() && IC->getOperand(1) == With)
92 continue;
93 // Unknown instruction.
94 return false;
95 }
96 return true;
97}
98
Meador Inge08ca1152012-11-26 20:37:20 +000099static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000100 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000101 return OI->getType()->isFloatingPointTy();
102 });
Meador Inge08ca1152012-11-26 20:37:20 +0000103}
104
David Bolvanskycb8ca5f32018-04-25 18:58:53 +0000105static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
106 if (Base < 2 || Base > 36)
107 // handle special zero base
108 if (Base != 0)
109 return nullptr;
110
111 char *End;
112 std::string nptr = Str.str();
113 errno = 0;
114 long long int Result = strtoll(nptr.c_str(), &End, Base);
115 if (errno)
116 return nullptr;
117
118 // if we assume all possible target locales are ASCII supersets,
119 // then if strtoll successfully parses a number on the host,
120 // it will also successfully parse the same way on the target
121 if (*End != '\0')
122 return nullptr;
123
124 if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
125 return nullptr;
126
127 return ConstantInt::get(CI->getType(), Result);
128}
129
Meador Inged589ac62012-10-31 03:33:06 +0000130//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000131// String and Memory Library Call Optimizations
132//===----------------------------------------------------------------------===//
133
Chris Bienemanad070d02014-09-17 20:55:46 +0000134Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000135 // Extract some information from the instruction
136 Value *Dst = CI->getArgOperand(0);
137 Value *Src = CI->getArgOperand(1);
138
139 // See if we can get the length of the input string.
140 uint64_t Len = GetStringLength(Src);
141 if (Len == 0)
142 return nullptr;
143 --Len; // Unbias length.
144
145 // Handle the simple, do-nothing case: strcat(x, "") -> x
146 if (Len == 0)
147 return Dst;
148
Chris Bienemanad070d02014-09-17 20:55:46 +0000149 return emitStrLenMemCpy(Src, Dst, Len, B);
150}
151
152Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
153 IRBuilder<> &B) {
154 // We need to find the end of the destination string. That's where the
155 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000156 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000157 if (!DstLen)
158 return nullptr;
159
160 // Now that we have the destination's length, we must index into the
161 // destination's pointer to get the actual memcpy destination (end of
162 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000163 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000164
165 // We have enough information to now generate the memcpy call to do the
166 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000167 B.CreateMemCpy(CpyDst, 1, Src, 1,
168 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000169 return Dst;
170}
171
172Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000173 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000174 Value *Dst = CI->getArgOperand(0);
175 Value *Src = CI->getArgOperand(1);
176 uint64_t Len;
177
Sanjay Pateld707db92015-12-31 16:10:49 +0000178 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000179 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
180 Len = LengthArg->getZExtValue();
181 else
182 return nullptr;
183
184 // See if we can get the length of the input string.
185 uint64_t SrcLen = GetStringLength(Src);
186 if (SrcLen == 0)
187 return nullptr;
188 --SrcLen; // Unbias length.
189
190 // Handle the simple, do-nothing cases:
191 // strncat(x, "", c) -> x
192 // strncat(x, c, 0) -> x
193 if (SrcLen == 0 || Len == 0)
194 return Dst;
195
Sanjay Pateld707db92015-12-31 16:10:49 +0000196 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000197 if (Len < SrcLen)
198 return nullptr;
199
200 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000201 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000202 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
203}
204
205Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
206 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000208 Value *SrcStr = CI->getArgOperand(0);
209
210 // If the second operand is non-constant, see if we can compute the length
211 // of the input string and turn this into memchr.
212 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
213 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000214 uint64_t Len = GetStringLength(SrcStr);
215 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
216 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000217
Sanjay Pateld3112a52016-01-19 19:46:10 +0000218 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000219 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
220 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000221 }
222
Chris Bienemanad070d02014-09-17 20:55:46 +0000223 // Otherwise, the character is a constant, see if the first argument is
224 // a string literal. If so, we can constant fold.
225 StringRef Str;
226 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000227 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000228 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000229 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000230 return nullptr;
231 }
232
233 // Compute the offset, make sure to handle the case when we're searching for
234 // zero (a weird way to spell strlen).
235 size_t I = (0xFF & CharC->getSExtValue()) == 0
236 ? Str.size()
237 : Str.find(CharC->getSExtValue());
238 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
239 return Constant::getNullValue(CI->getType());
240
241 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000242 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000243}
244
245Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000246 Value *SrcStr = CI->getArgOperand(0);
247 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
248
249 // Cannot fold anything if we're not looking for a constant.
250 if (!CharC)
251 return nullptr;
252
253 StringRef Str;
254 if (!getConstantStringInfo(SrcStr, Str)) {
255 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000256 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000257 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000258 return nullptr;
259 }
260
261 // Compute the offset.
262 size_t I = (0xFF & CharC->getSExtValue()) == 0
263 ? Str.size()
264 : Str.rfind(CharC->getSExtValue());
265 if (I == StringRef::npos) // Didn't find the char. Return null.
266 return Constant::getNullValue(CI->getType());
267
268 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000269 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000270}
271
272Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000273 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
274 if (Str1P == Str2P) // strcmp(x,x) -> 0
275 return ConstantInt::get(CI->getType(), 0);
276
277 StringRef Str1, Str2;
278 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
279 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
280
281 // strcmp(x, y) -> cnst (if both x and y are constant strings)
282 if (HasStr1 && HasStr2)
283 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
284
285 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
286 return B.CreateNeg(
287 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
288
289 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
290 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
291
292 // strcmp(P, "x") -> memcmp(P, "x", 2)
293 uint64_t Len1 = GetStringLength(Str1P);
294 uint64_t Len2 = GetStringLength(Str2P);
295 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000296 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000298 std::min(Len1, Len2)),
299 B, DL, TLI);
300 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000301
Chris Bienemanad070d02014-09-17 20:55:46 +0000302 return nullptr;
303}
304
305Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000306 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
307 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
308 return ConstantInt::get(CI->getType(), 0);
309
310 // Get the length argument if it is constant.
311 uint64_t Length;
312 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
313 Length = LengthArg->getZExtValue();
314 else
315 return nullptr;
316
317 if (Length == 0) // strncmp(x,y,0) -> 0
318 return ConstantInt::get(CI->getType(), 0);
319
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000320 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000321 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000322
323 StringRef Str1, Str2;
324 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
325 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
326
327 // strncmp(x, y) -> cnst (if both x and y are constant strings)
328 if (HasStr1 && HasStr2) {
329 StringRef SubStr1 = Str1.substr(0, Length);
330 StringRef SubStr2 = Str2.substr(0, Length);
331 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
332 }
333
334 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
335 return B.CreateNeg(
336 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
337
338 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
339 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
340
341 return nullptr;
342}
343
344Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000345 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
346 if (Dst == Src) // strcpy(x,x) -> x
347 return Src;
348
Chris Bienemanad070d02014-09-17 20:55:46 +0000349 // See if we can get the length of the input string.
350 uint64_t Len = GetStringLength(Src);
351 if (Len == 0)
352 return nullptr;
353
354 // We have enough information to now generate the memcpy call to do the
355 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000356 B.CreateMemCpy(Dst, 1, Src, 1,
357 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
Chris Bienemanad070d02014-09-17 20:55:46 +0000358 return Dst;
359}
360
361Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
362 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000363 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
364 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000365 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000366 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000367 }
368
369 // See if we can get the length of the input string.
370 uint64_t Len = GetStringLength(Src);
371 if (Len == 0)
372 return nullptr;
373
Davide Italianob7487e62015-11-02 23:07:14 +0000374 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000375 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000376 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
377 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000378
379 // We have enough information to now generate the memcpy call to do the
380 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000381 B.CreateMemCpy(Dst, 1, Src, 1, LenV);
Chris Bienemanad070d02014-09-17 20:55:46 +0000382 return DstEnd;
383}
384
385Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
386 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000387 Value *Dst = CI->getArgOperand(0);
388 Value *Src = CI->getArgOperand(1);
389 Value *LenOp = CI->getArgOperand(2);
390
391 // See if we can get the length of the input string.
392 uint64_t SrcLen = GetStringLength(Src);
393 if (SrcLen == 0)
394 return nullptr;
395 --SrcLen;
396
397 if (SrcLen == 0) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000398 // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
Chris Bienemanad070d02014-09-17 20:55:46 +0000399 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000400 return Dst;
401 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000402
Chris Bienemanad070d02014-09-17 20:55:46 +0000403 uint64_t Len;
404 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
405 Len = LengthArg->getZExtValue();
406 else
407 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000408
Chris Bienemanad070d02014-09-17 20:55:46 +0000409 if (Len == 0)
410 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000411
Chris Bienemanad070d02014-09-17 20:55:46 +0000412 // Let strncpy handle the zero padding
413 if (Len > SrcLen + 1)
414 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000415
Davide Italianob7487e62015-11-02 23:07:14 +0000416 Type *PT = Callee->getFunctionType()->getParamType(0);
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000417 // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
418 B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
Meador Inge7fb2f732012-10-13 16:45:32 +0000419
Chris Bienemanad070d02014-09-17 20:55:46 +0000420 return Dst;
421}
Meador Inge7fb2f732012-10-13 16:45:32 +0000422
Matthias Braun50ec0b52017-05-19 22:37:09 +0000423Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
424 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000425 Value *Src = CI->getArgOperand(0);
426
427 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000428 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000429 return ConstantInt::get(CI->getType(), Len - 1);
430
David L Kreitzer752c1442016-04-13 14:31:06 +0000431 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000432 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000433 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000434 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000435 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000436 // subtraction. This will make the optimization more complex, and it's not
437 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000438 // very uncommon.
439 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000440 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000441 return nullptr;
442
Matthias Braun50ec0b52017-05-19 22:37:09 +0000443 ConstantDataArraySlice Slice;
444 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
445 uint64_t NullTermIdx;
446 if (Slice.Array == nullptr) {
447 NullTermIdx = 0;
448 } else {
449 NullTermIdx = ~((uint64_t)0);
450 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
451 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
452 NullTermIdx = I;
453 break;
454 }
455 }
456 // If the string does not have '\0', leave it to strlen to compute
457 // its length.
458 if (NullTermIdx == ~((uint64_t)0))
459 return nullptr;
460 }
461
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000463 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000464 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000465 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000466 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
467
Matthias Braun50ec0b52017-05-19 22:37:09 +0000468 // KnownZero's bits are flipped, so zeros in KnownZero now represent
469 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000470 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000471 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000472 // unsigned-less-than NullTermIdx.
473 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000474 // If Offset is not provably in the range [0, NullTermIdx], we can still
475 // optimize if we can prove that the program has undefined behavior when
476 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000477 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000478 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000479 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000480 NullTermIdx == ArrSize - 1)) {
481 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
482 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000483 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000484 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000485 }
486
487 return nullptr;
488 }
489
Chris Bienemanad070d02014-09-17 20:55:46 +0000490 // strlen(x?"foo":"bars") --> x ? 3 : 4
491 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000492 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
493 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000494 if (LenTrue && LenFalse) {
Vivek Pandya95906582017-10-11 17:12:59 +0000495 ORE.emit([&]() {
496 return OptimizationRemark("instcombine", "simplify-libcalls", CI)
497 << "folded strlen(select) to select of constants";
498 });
Chris Bienemanad070d02014-09-17 20:55:46 +0000499 return B.CreateSelect(SI->getCondition(),
500 ConstantInt::get(CI->getType(), LenTrue - 1),
501 ConstantInt::get(CI->getType(), LenFalse - 1));
502 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000503 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 // strlen(x) != 0 --> *x != 0
506 // strlen(x) == 0 --> *x == 0
507 if (isOnlyUsedInZeroEqualityComparison(CI))
508 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000509
Chris Bienemanad070d02014-09-17 20:55:46 +0000510 return nullptr;
511}
Meador Inge17418502012-10-13 16:45:37 +0000512
Matthias Braun50ec0b52017-05-19 22:37:09 +0000513Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
514 return optimizeStringLength(CI, B, 8);
515}
516
517Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
518 Module &M = *CI->getParent()->getParent()->getParent();
519 unsigned WCharSize = TLI->getWCharSize(M) * 8;
Matthias Brauncc603ee2017-09-26 02:36:57 +0000520 // We cannot perform this optimization without wchar_size metadata.
521 if (WCharSize == 0)
522 return nullptr;
Matthias Braun50ec0b52017-05-19 22:37:09 +0000523
524 return optimizeStringLength(CI, B, WCharSize);
525}
526
Chris Bienemanad070d02014-09-17 20:55:46 +0000527Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000528 StringRef S1, S2;
529 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
530 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000531
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000532 // strpbrk(s, "") -> nullptr
533 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000534 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
535 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000536
Chris Bienemanad070d02014-09-17 20:55:46 +0000537 // Constant folding.
538 if (HasS1 && HasS2) {
539 size_t I = S1.find_first_of(S2);
540 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000541 return Constant::getNullValue(CI->getType());
542
Sanjay Pateld707db92015-12-31 16:10:49 +0000543 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
544 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000545 }
Meador Inge17418502012-10-13 16:45:37 +0000546
Chris Bienemanad070d02014-09-17 20:55:46 +0000547 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000548 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000549 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000550
551 return nullptr;
552}
553
554Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000555 Value *EndPtr = CI->getArgOperand(1);
556 if (isa<ConstantPointerNull>(EndPtr)) {
557 // With a null EndPtr, this function won't capture the main argument.
558 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000559 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000560 }
561
562 return nullptr;
563}
564
565Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000566 StringRef S1, S2;
567 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
568 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
569
570 // strspn(s, "") -> 0
571 // strspn("", s) -> 0
572 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
573 return Constant::getNullValue(CI->getType());
574
575 // Constant folding.
576 if (HasS1 && HasS2) {
577 size_t Pos = S1.find_first_not_of(S2);
578 if (Pos == StringRef::npos)
579 Pos = S1.size();
580 return ConstantInt::get(CI->getType(), Pos);
581 }
582
583 return nullptr;
584}
585
586Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000587 StringRef S1, S2;
588 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
589 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
590
591 // strcspn("", s) -> 0
592 if (HasS1 && S1.empty())
593 return Constant::getNullValue(CI->getType());
594
595 // Constant folding.
596 if (HasS1 && HasS2) {
597 size_t Pos = S1.find_first_of(S2);
598 if (Pos == StringRef::npos)
599 Pos = S1.size();
600 return ConstantInt::get(CI->getType(), Pos);
601 }
602
603 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000605 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000606
607 return nullptr;
608}
609
610Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000611 // fold strstr(x, x) -> x.
612 if (CI->getArgOperand(0) == CI->getArgOperand(1))
613 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
614
615 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000616 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000617 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000618 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000619 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000620 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000621 StrLen, B, DL, TLI);
622 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000623 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000624 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
625 ICmpInst *Old = cast<ICmpInst>(*UI++);
626 Value *Cmp =
627 B.CreateICmp(Old->getPredicate(), StrNCmp,
628 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
629 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000630 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000631 return CI;
632 }
Meador Inge17418502012-10-13 16:45:37 +0000633
Chris Bienemanad070d02014-09-17 20:55:46 +0000634 // See if either input string is a constant string.
635 StringRef SearchStr, ToFindStr;
636 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
637 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
638
639 // fold strstr(x, "") -> x.
640 if (HasStr2 && ToFindStr.empty())
641 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
642
643 // If both strings are known, constant fold it.
644 if (HasStr1 && HasStr2) {
645 size_t Offset = SearchStr.find(ToFindStr);
646
647 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000648 return Constant::getNullValue(CI->getType());
649
Chris Bienemanad070d02014-09-17 20:55:46 +0000650 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000651 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000652 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
653 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000654 }
Meador Inge17418502012-10-13 16:45:37 +0000655
Chris Bienemanad070d02014-09-17 20:55:46 +0000656 // fold strstr(x, "y") -> strchr(x, 'y').
657 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000658 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000659 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
660 }
661 return nullptr;
662}
Meador Inge40b6fac2012-10-15 03:47:37 +0000663
Benjamin Kramer691363e2015-03-21 15:36:21 +0000664Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000665 Value *SrcStr = CI->getArgOperand(0);
666 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
667 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
668
669 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000670 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000671 return Constant::getNullValue(CI->getType());
672
Benjamin Kramer7857d722015-03-21 21:09:33 +0000673 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000674 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000675 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000676 return nullptr;
677
678 // Truncate the string to LenC. If Str is smaller than LenC we will still only
679 // scan the string, as reading past the end of it is undefined and we can just
680 // return null if we don't find the char.
681 Str = Str.substr(0, LenC->getZExtValue());
682
Benjamin Kramer7857d722015-03-21 21:09:33 +0000683 // If the char is variable but the input str and length are not we can turn
684 // this memchr call into a simple bit field test. Of course this only works
685 // when the return value is only checked against null.
686 //
687 // It would be really nice to reuse switch lowering here but we can't change
688 // the CFG at this point.
689 //
690 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
691 // after bounds check.
692 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000693 unsigned char Max =
694 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
695 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000696
697 // Make sure the bit field we're about to create fits in a register on the
698 // target.
699 // FIXME: On a 64 bit architecture this prevents us from using the
700 // interesting range of alpha ascii chars. We could do better by emitting
701 // two bitfields or shifting the range by 64 if no lower chars are used.
702 if (!DL.fitsInLegalInteger(Max + 1))
703 return nullptr;
704
705 // For the bit field use a power-of-2 type with at least 8 bits to avoid
706 // creating unnecessary illegal types.
707 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
708
709 // Now build the bit field.
710 APInt Bitfield(Width, 0);
711 for (char C : Str)
712 Bitfield.setBit((unsigned char)C);
713 Value *BitfieldC = B.getInt(Bitfield);
714
715 // First check that the bit field access is within bounds.
716 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
717 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
718 "memchr.bounds");
719
720 // Create code that checks if the given bit is set in the field.
721 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
722 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
723
724 // Finally merge both checks and cast to pointer type. The inttoptr
725 // implicitly zexts the i1 to intptr type.
726 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
727 }
728
729 // Check if all arguments are constants. If so, we can constant fold.
730 if (!CharC)
731 return nullptr;
732
Benjamin Kramer691363e2015-03-21 15:36:21 +0000733 // Compute the offset.
734 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
735 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
736 return Constant::getNullValue(CI->getType());
737
738 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000739 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000740}
741
Chris Bienemanad070d02014-09-17 20:55:46 +0000742Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000744
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 if (LHS == RHS) // memcmp(s,s,x) -> 0
746 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000747
Chris Bienemanad070d02014-09-17 20:55:46 +0000748 // Make sure we have a constant length.
749 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
750 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000751 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000752
Sanjay Patel70db4242017-06-09 14:22:03 +0000753 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000754 if (Len == 0) // memcmp(s1,s2,0) -> 0
755 return Constant::getNullValue(CI->getType());
756
757 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
758 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000759 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000760 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000761 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000762 CI->getType(), "rhsv");
763 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000764 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000765
Chad Rosierdc655322015-08-28 18:30:18 +0000766 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
Sanjay Patel82ec8722017-08-21 19:13:14 +0000767 // TODO: The case where both inputs are constants does not need to be limited
768 // to legal integers or equality comparison. See block below this.
Chad Rosierdc655322015-08-28 18:30:18 +0000769 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Chad Rosierdc655322015-08-28 18:30:18 +0000770 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
771 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
772
Sanjay Patel82ec8722017-08-21 19:13:14 +0000773 // First, see if we can fold either argument to a constant.
774 Value *LHSV = nullptr;
775 if (auto *LHSC = dyn_cast<Constant>(LHS)) {
776 LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
777 LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
778 }
779 Value *RHSV = nullptr;
780 if (auto *RHSC = dyn_cast<Constant>(RHS)) {
781 RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
782 RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
783 }
Chad Rosierdc655322015-08-28 18:30:18 +0000784
Sanjay Patel82ec8722017-08-21 19:13:14 +0000785 // Don't generate unaligned loads. If either source is constant data,
786 // alignment doesn't matter for that source because there is no load.
787 if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
788 (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
789 if (!LHSV) {
790 Type *LHSPtrTy =
791 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
792 LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
793 }
794 if (!RHSV) {
795 Type *RHSPtrTy =
796 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
797 RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
798 }
Sanjay Patel7756edf2017-08-21 13:55:49 +0000799 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000800 }
Chad Rosierdc655322015-08-28 18:30:18 +0000801 }
802
Sanjay Patel82ec8722017-08-21 19:13:14 +0000803 // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
804 // TODO: This is limited to i8 arrays.
Chris Bienemanad070d02014-09-17 20:55:46 +0000805 StringRef LHSStr, RHSStr;
806 if (getConstantStringInfo(LHS, LHSStr) &&
807 getConstantStringInfo(RHS, RHSStr)) {
808 // Make sure we're not reading out-of-bounds memory.
809 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000810 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000811 // Fold the memcmp and normalize the result. This way we get consistent
812 // results across multiple platforms.
813 uint64_t Ret = 0;
814 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
815 if (Cmp < 0)
816 Ret = -1;
817 else if (Cmp > 0)
818 Ret = 1;
819 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000820 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000821
Chris Bienemanad070d02014-09-17 20:55:46 +0000822 return nullptr;
823}
Meador Inge9a6a1902012-10-31 00:20:56 +0000824
Chris Bienemanad070d02014-09-17 20:55:46 +0000825Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000826 // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
827 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
828 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000829 return CI->getArgOperand(0);
830}
Meador Inge05a625a2012-10-31 14:58:26 +0000831
Chris Bienemanad070d02014-09-17 20:55:46 +0000832Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000833 // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
834 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
835 CI->getArgOperand(2));
Chris Bienemanad070d02014-09-17 20:55:46 +0000836 return CI->getArgOperand(0);
837}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000838
Sanjay Patel980b2802016-01-26 16:17:24 +0000839/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
840static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
841 const TargetLibraryInfo &TLI) {
842 // This has to be a memset of zeros (bzero).
843 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
844 if (!FillValue || FillValue->getZExtValue() != 0)
845 return nullptr;
846
847 // TODO: We should handle the case where the malloc has more than one use.
848 // This is necessary to optimize common patterns such as when the result of
849 // the malloc is checked against null or when a memset intrinsic is used in
850 // place of a memset library call.
851 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
852 if (!Malloc || !Malloc->hasOneUse())
853 return nullptr;
854
855 // Is the inner call really malloc()?
856 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000857 if (!InnerCallee)
858 return nullptr;
859
David L. Jonesd21529f2017-01-23 23:16:46 +0000860 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000861 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000862 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000863 return nullptr;
864
Sanjay Patel980b2802016-01-26 16:17:24 +0000865 // The memset must cover the same number of bytes that are malloc'd.
866 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
867 return nullptr;
868
869 // Replace the malloc with a calloc. We need the data layout to know what the
870 // actual size of a 'size_t' parameter is.
871 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
872 const DataLayout &DL = Malloc->getModule()->getDataLayout();
873 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
874 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
875 Malloc->getArgOperand(0), Malloc->getAttributes(),
876 B, TLI);
877 if (!Calloc)
878 return nullptr;
879
880 Malloc->replaceAllUsesWith(Calloc);
881 Malloc->eraseFromParent();
882
883 return Calloc;
884}
885
Chris Bienemanad070d02014-09-17 20:55:46 +0000886Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000887 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
888 return Calloc;
889
Daniel Neilson8acd8b02018-02-05 21:23:22 +0000890 // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
Chris Bienemanad070d02014-09-17 20:55:46 +0000891 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
892 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
893 return CI->getArgOperand(0);
894}
Meador Inged4825782012-11-11 06:49:03 +0000895
Sanjay Patelb2ab3f22018-04-18 14:21:31 +0000896Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
897 if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
898 return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
899
900 return nullptr;
901}
902
Meador Inge193e0352012-11-13 04:16:17 +0000903//===----------------------------------------------------------------------===//
904// Math Library Optimizations
905//===----------------------------------------------------------------------===//
906
Matthias Braund34e4d22014-12-03 21:46:33 +0000907/// Return a variant of Val with float type.
908/// Currently this works in two cases: If Val is an FPExtension of a float
909/// value to something bigger, simply return the operand.
910/// If Val is a ConstantFP but can be converted to a float ConstantFP without
911/// loss of precision do so.
912static Value *valueHasFloatPrecision(Value *Val) {
913 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
914 Value *Op = Cast->getOperand(0);
915 if (Op->getType()->isFloatTy())
916 return Op;
917 }
918 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
919 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000920 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000921 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000922 &losesInfo);
923 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000924 return ConstantFP::get(Const->getContext(), F);
925 }
926 return nullptr;
927}
928
Sanjay Patel4e971da2016-01-21 18:01:57 +0000929/// Shrink double -> float for unary functions like 'floor'.
930static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
931 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000932 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000933 // We know this libcall has a valid prototype, but we don't know which.
934 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000935 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000936
Chris Bienemanad070d02014-09-17 20:55:46 +0000937 if (CheckRetType) {
938 // Check if all the uses for function like 'sin' are converted to float.
939 for (User *U : CI->users()) {
940 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
941 if (!Cast || !Cast->getType()->isFloatTy())
942 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000943 }
Meador Inge193e0352012-11-13 04:16:17 +0000944 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000945
946 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000947 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
948 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000949 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000950
Andrew Ng1606fc02017-04-25 12:36:14 +0000951 // If call isn't an intrinsic, check that it isn't within a function with the
952 // same name as the float version of this call.
953 //
954 // e.g. inline float expf(float val) { return (float) exp((double) val); }
955 //
956 // A similar such definition exists in the MinGW-w64 math.h header file which
957 // when compiled with -O2 -ffast-math causes the generation of infinite loops
958 // where expf is called.
959 if (!Callee->isIntrinsic()) {
960 const Function *F = CI->getFunction();
961 StringRef FName = F->getName();
962 StringRef CalleeName = Callee->getName();
963 if ((FName.size() == (CalleeName.size() + 1)) &&
964 (FName.back() == 'f') &&
965 FName.startswith(CalleeName))
966 return nullptr;
967 }
968
Sanjay Patelaa231142015-12-31 21:52:31 +0000969 // Propagate fast-math flags from the existing call to the new call.
970 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000971 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000972
973 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000974 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000975 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000976 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000977 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
978 V = B.CreateCall(F, V);
979 } else {
980 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000981 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000982 }
983
Chris Bienemanad070d02014-09-17 20:55:46 +0000984 return B.CreateFPExt(V, B.getDoubleTy());
985}
Meador Inge193e0352012-11-13 04:16:17 +0000986
Matt Arsenault954a6242017-01-23 23:55:08 +0000987// Replace a libcall \p CI with a call to intrinsic \p IID
988static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
989 // Propagate fast-math flags from the existing call to the new call.
990 IRBuilder<>::FastMathFlagGuard Guard(B);
991 B.setFastMathFlags(CI->getFastMathFlags());
992
993 Module *M = CI->getModule();
994 Value *V = CI->getArgOperand(0);
995 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
996 CallInst *NewCall = B.CreateCall(F, V);
997 NewCall->takeName(CI);
998 return NewCall;
999}
1000
Sanjay Patel4e971da2016-01-21 18:01:57 +00001001/// Shrink double -> float for binary functions like 'fmin/fmax'.
1002static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001003 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +00001004 // We know this libcall has a valid prototype, but we don't know which.
1005 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001006 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001007
Chris Bienemanad070d02014-09-17 20:55:46 +00001008 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001009 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1010 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1011 if (V1 == nullptr)
1012 return nullptr;
1013 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1014 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001015 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001016
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001017 // Propagate fast-math flags from the existing call to the new call.
1018 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001019 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001020
Chris Bienemanad070d02014-09-17 20:55:46 +00001021 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001022 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001023 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001024 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001025 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001026 return B.CreateFPExt(V, B.getDoubleTy());
1027}
1028
Hal Finkel2ff24732017-12-16 01:26:25 +00001029// cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
1030Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
1031 if (!CI->isFast())
1032 return nullptr;
1033
1034 // Propagate fast-math flags from the existing call to new instructions.
1035 IRBuilder<>::FastMathFlagGuard Guard(B);
1036 B.setFastMathFlags(CI->getFastMathFlags());
1037
1038 Value *Real, *Imag;
1039 if (CI->getNumArgOperands() == 1) {
1040 Value *Op = CI->getArgOperand(0);
1041 assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
1042 Real = B.CreateExtractValue(Op, 0, "real");
1043 Imag = B.CreateExtractValue(Op, 1, "imag");
1044 } else {
1045 assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
1046 Real = CI->getArgOperand(0);
1047 Imag = CI->getArgOperand(1);
1048 }
1049
1050 Value *RealReal = B.CreateFMul(Real, Real);
1051 Value *ImagImag = B.CreateFMul(Imag, Imag);
1052
1053 Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
1054 CI->getType());
1055 return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
1056}
1057
Chris Bienemanad070d02014-09-17 20:55:46 +00001058Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1059 Function *Callee = CI->getCalledFunction();
1060 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001061 StringRef Name = Callee->getName();
1062 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001063 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001064
Chris Bienemanad070d02014-09-17 20:55:46 +00001065 // cos(-x) -> cos(x)
1066 Value *Op1 = CI->getArgOperand(0);
1067 if (BinaryOperator::isFNeg(Op1)) {
1068 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1069 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1070 }
1071 return Ret;
1072}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001073
Weiming Zhao82130722015-12-04 22:00:47 +00001074static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1075 // Multiplications calculated using Addition Chains.
1076 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1077
1078 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1079
1080 if (InnerChain[Exp])
1081 return InnerChain[Exp];
1082
1083 static const unsigned AddChain[33][2] = {
1084 {0, 0}, // Unused.
1085 {0, 0}, // Unused (base case = pow1).
1086 {1, 1}, // Unused (pre-computed).
1087 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1088 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1089 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1090 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1091 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1092 };
1093
1094 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1095 getPow(InnerChain, AddChain[Exp][1], B));
1096 return InnerChain[Exp];
1097}
1098
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001099/// Use square root in place of pow(x, +/-0.5).
1100Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
1101 // TODO: There is some subset of 'fast' under which these transforms should
1102 // be allowed.
1103 if (!Pow->isFast())
1104 return nullptr;
1105
Sanjay Patel9771a962017-11-19 16:42:27 +00001106 const APFloat *Arg1C;
1107 if (!match(Pow->getArgOperand(1), m_APFloat(Arg1C)))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001108 return nullptr;
Sanjay Patel9771a962017-11-19 16:42:27 +00001109 if (!Arg1C->isExactlyValue(0.5) && !Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001110 return nullptr;
1111
1112 // Fast-math flags from the pow() are propagated to all replacement ops.
1113 IRBuilder<>::FastMathFlagGuard Guard(B);
1114 B.setFastMathFlags(Pow->getFastMathFlags());
1115 Type *Ty = Pow->getType();
1116 Value *Sqrt;
1117 if (Pow->hasFnAttr(Attribute::ReadNone)) {
1118 // We know that errno is never set, so replace with an intrinsic:
1119 // pow(x, 0.5) --> llvm.sqrt(x)
1120 // llvm.pow(x, 0.5) --> llvm.sqrt(x)
1121 auto *F = Intrinsic::getDeclaration(Pow->getModule(), Intrinsic::sqrt, Ty);
1122 Sqrt = B.CreateCall(F, Pow->getArgOperand(0));
1123 } else if (hasUnaryFloatFn(TLI, Ty, LibFunc_sqrt, LibFunc_sqrtf,
1124 LibFunc_sqrtl)) {
1125 // Errno could be set, so we must use a sqrt libcall.
1126 // TODO: We also should check that the target can in fact lower the sqrt
1127 // libcall. We currently have no way to ask this question, so we ask
1128 // whether the target has a sqrt libcall which is not exactly the same.
1129 Sqrt = emitUnaryFloatFnCall(Pow->getArgOperand(0),
1130 TLI->getName(LibFunc_sqrt), B,
1131 Pow->getCalledFunction()->getAttributes());
1132 } else {
1133 // We can't replace with an intrinsic or a libcall.
1134 return nullptr;
1135 }
1136
1137 // If this is pow(x, -0.5), get the reciprocal.
Sanjay Patel9771a962017-11-19 16:42:27 +00001138 if (Arg1C->isExactlyValue(-0.5))
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001139 Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt);
1140
1141 return Sqrt;
1142}
1143
Chris Bienemanad070d02014-09-17 20:55:46 +00001144Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1145 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001146 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001147 StringRef Name = Callee->getName();
1148 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001149 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001150
Chris Bienemanad070d02014-09-17 20:55:46 +00001151 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001152
1153 // pow(1.0, x) -> 1.0
1154 if (match(Op1, m_SpecificFP(1.0)))
1155 return Op1;
1156 // pow(2.0, x) -> llvm.exp2(x)
1157 if (match(Op1, m_SpecificFP(2.0))) {
1158 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1159 CI->getType());
1160 return B.CreateCall(Exp2, Op2, "exp2");
1161 }
1162
1163 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1164 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001165 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001166 // pow(10.0, x) -> exp10(x)
1167 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001168 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1169 LibFunc_exp10l))
1170 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001171 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001172 }
1173
Sanjay Patel6002e782016-01-12 17:30:37 +00001174 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001175 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001176 // We enable these only with fast-math. Besides rounding differences, the
1177 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001178 // Example: x = 1000, y = 0.001.
1179 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001180 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patel629c4112017-11-06 16:27:15 +00001181 if (OpC && OpC->isFast() && CI->isFast()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001182 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001183 Function *OpCCallee = OpC->getCalledFunction();
1184 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001185 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001186 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001187 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001188 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001189 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001190 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001191 }
1192 }
1193
Sanjay Patel9771a962017-11-19 16:42:27 +00001194 if (Value *Sqrt = replacePowWithSqrt(CI, B))
1195 return Sqrt;
1196
Chris Bienemanad070d02014-09-17 20:55:46 +00001197 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1198 if (!Op2C)
1199 return Ret;
1200
1201 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1202 return ConstantFP::get(CI->getType(), 1.0);
1203
Sanjay Patelfbd3e662017-11-19 16:13:14 +00001204 // FIXME: Correct the transforms and pull this into replacePowWithSqrt().
Chris Bienemanad070d02014-09-17 20:55:46 +00001205 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001206 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1207 LibFunc_sqrtl)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001208 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1209 // This is faster than calling pow, and still handles negative zero
1210 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001211 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1212 Value *Inf = ConstantFP::getInfinity(CI->getType());
1213 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001214
1215 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1216 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001217 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001218
1219 Module *M = Callee->getParent();
1220 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1221 CI->getType());
1222 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1223
Chris Bienemanad070d02014-09-17 20:55:46 +00001224 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1225 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1226 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001227 }
1228
Sanjay Patelb23e1482017-12-10 17:25:54 +00001229 // Propagate fast-math-flags from the call to any created instructions.
1230 IRBuilder<>::FastMathFlagGuard Guard(B);
1231 B.setFastMathFlags(CI->getFastMathFlags());
1232 // pow(x, 1.0) --> x
1233 if (Op2C->isExactlyValue(1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001234 return Op1;
Sanjay Patelb23e1482017-12-10 17:25:54 +00001235 // pow(x, 2.0) --> x * x
1236 if (Op2C->isExactlyValue(2.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001237 return B.CreateFMul(Op1, Op1, "pow2");
Sanjay Patelb23e1482017-12-10 17:25:54 +00001238 // pow(x, -1.0) --> 1.0 / x
1239 if (Op2C->isExactlyValue(-1.0))
Chris Bienemanad070d02014-09-17 20:55:46 +00001240 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001241
1242 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel629c4112017-11-06 16:27:15 +00001243 if (CI->isFast()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001244 APFloat V = abs(Op2C->getValueAPF());
1245 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1246 // This transformation applies to integer exponents only.
1247 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1248 !V.isInteger())
1249 return nullptr;
1250
1251 // We will memoize intermediate products of the Addition Chain.
1252 Value *InnerChain[33] = {nullptr};
1253 InnerChain[1] = Op1;
1254 InnerChain[2] = B.CreateFMul(Op1, Op1);
1255
1256 // We cannot readily convert a non-double type (like float) to a double.
1257 // So we first convert V to something which could be converted to double.
Sanjay Patelb23e1482017-12-10 17:25:54 +00001258 bool Ignored;
1259 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001260
Weiming Zhao82130722015-12-04 22:00:47 +00001261 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1262 // For negative exponents simply compute the reciprocal.
1263 if (Op2C->isNegative())
1264 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1265 return FMul;
1266 }
1267
Chris Bienemanad070d02014-09-17 20:55:46 +00001268 return nullptr;
1269}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001270
Chris Bienemanad070d02014-09-17 20:55:46 +00001271Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1272 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001273 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001274 StringRef Name = Callee->getName();
1275 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001276 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001277
Chris Bienemanad070d02014-09-17 20:55:46 +00001278 Value *Op = CI->getArgOperand(0);
1279 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1280 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001281 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001282 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001283 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001284 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001285 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001286
1287 if (TLI->has(LdExp)) {
1288 Value *LdExpArg = nullptr;
1289 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1290 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1291 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1292 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1293 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1294 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1295 }
1296
1297 if (LdExpArg) {
1298 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1299 if (!Op->getType()->isFloatTy())
1300 One = ConstantExpr::getFPExtend(One, Op->getType());
1301
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001302 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001303 Value *NewCallee =
1304 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001305 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001306 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001307 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1308 CI->setCallingConv(F->getCallingConv());
1309
1310 return CI;
1311 }
1312 }
1313 return Ret;
1314}
1315
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001316Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001317 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001318 // If we can shrink the call to a float function rather than a double
1319 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001320 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001321 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1322 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001323 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001324
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001325 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001326 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001327 if (CI->isFast()) {
1328 // If the call is 'fast', then anything we create here will also be 'fast'.
1329 FMF.setFast();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001330 } else {
1331 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001332 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001333 return nullptr;
1334 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1335 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001336 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001337 // might be impractical."
1338 FMF.setNoSignedZeros();
1339 FMF.setNoNaNs();
1340 }
Sanjay Patela2528152016-01-12 18:03:37 +00001341 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001342
1343 // We have a relaxed floating-point environment. We can ignore NaN-handling
1344 // and transform to a compare and select. We do not have to consider errno or
1345 // exceptions, because fmin/fmax do not have those.
1346 Value *Op0 = CI->getArgOperand(0);
1347 Value *Op1 = CI->getArgOperand(1);
1348 Value *Cmp = Callee->getName().startswith("fmin") ?
1349 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1350 return B.CreateSelect(Cmp, Op0, Op1);
1351}
1352
Davide Italianob8b71332015-11-29 20:58:04 +00001353Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1354 Function *Callee = CI->getCalledFunction();
1355 Value *Ret = nullptr;
1356 StringRef Name = Callee->getName();
1357 if (UnsafeFPShrink && hasFloatVersion(Name))
1358 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001359
Sanjay Patel629c4112017-11-06 16:27:15 +00001360 if (!CI->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001361 return Ret;
1362 Value *Op1 = CI->getArgOperand(0);
1363 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001364
Sanjay Patel629c4112017-11-06 16:27:15 +00001365 // The earlier call must also be 'fast' in order to do these transforms.
1366 if (!OpC || !OpC->isFast())
Davide Italianob8b71332015-11-29 20:58:04 +00001367 return Ret;
1368
1369 // log(pow(x,y)) -> y*log(x)
1370 // This is only applicable to log, log2, log10.
1371 if (Name != "log" && Name != "log2" && Name != "log10")
1372 return Ret;
1373
1374 IRBuilder<>::FastMathFlagGuard Guard(B);
1375 FastMathFlags FMF;
Sanjay Patel629c4112017-11-06 16:27:15 +00001376 FMF.setFast();
Sanjay Patela2528152016-01-12 18:03:37 +00001377 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001378
David L. Jonesd21529f2017-01-23 23:16:46 +00001379 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001380 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001381 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001382 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001383 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001384 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001385 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001386
1387 // log(exp2(y)) -> y*log(2)
1388 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001389 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001390 return B.CreateFMul(
1391 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001392 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001393 Callee->getName(), B, Callee->getAttributes()),
1394 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001395 return Ret;
1396}
1397
Sanjay Patelc699a612014-10-16 18:48:17 +00001398Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1399 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001400 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001401 // TODO: Once we have a way (other than checking for the existince of the
1402 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1403 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001404 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001405 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001406 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001407
Sanjay Patel629c4112017-11-06 16:27:15 +00001408 if (!CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00001409 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001410
Sanjay Patelc2d64612016-01-06 20:52:21 +00001411 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
Sanjay Patel629c4112017-11-06 16:27:15 +00001412 if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
Sanjay Patelc2d64612016-01-06 20:52:21 +00001413 return Ret;
1414
1415 // We're looking for a repeated factor in a multiplication tree,
1416 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001417 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001418 Value *Op0 = I->getOperand(0);
1419 Value *Op1 = I->getOperand(1);
1420 Value *RepeatOp = nullptr;
1421 Value *OtherOp = nullptr;
1422 if (Op0 == Op1) {
1423 // Simple match: the operands of the multiply are identical.
1424 RepeatOp = Op0;
1425 } else {
1426 // Look for a more complicated pattern: one of the operands is itself
1427 // a multiply, so search for a common factor in that multiply.
1428 // Note: We don't bother looking any deeper than this first level or for
1429 // variations of this pattern because instcombine's visitFMUL and/or the
1430 // reassociation pass should give us this form.
1431 Value *OtherMul0, *OtherMul1;
1432 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1433 // Pattern: sqrt((x * y) * z)
Sanjay Patel629c4112017-11-06 16:27:15 +00001434 if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001435 // Matched: sqrt((x * x) * z)
1436 RepeatOp = OtherMul0;
1437 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001438 }
1439 }
1440 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001441 if (!RepeatOp)
1442 return Ret;
1443
1444 // Fast math flags for any created instructions should match the sqrt
1445 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001446 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001447 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001448
Sanjay Patelc2d64612016-01-06 20:52:21 +00001449 // If we found a repeated factor, hoist it out of the square root and
1450 // replace it with the fabs of that factor.
1451 Module *M = Callee->getParent();
1452 Type *ArgType = I->getType();
1453 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1454 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1455 if (OtherOp) {
1456 // If we found a non-repeated factor, we still need to get its square
1457 // root. We then multiply that by the value that was simplified out
1458 // of the square root calculation.
1459 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1460 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1461 return B.CreateFMul(FabsCall, SqrtCall);
1462 }
1463 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001464}
1465
Sanjay Patelcddcd722016-01-06 19:23:35 +00001466// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001467Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1468 Function *Callee = CI->getCalledFunction();
1469 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001470 StringRef Name = Callee->getName();
1471 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001472 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001473
Davide Italiano51507d22015-11-04 23:36:56 +00001474 Value *Op1 = CI->getArgOperand(0);
1475 auto *OpC = dyn_cast<CallInst>(Op1);
1476 if (!OpC)
1477 return Ret;
1478
Sanjay Patel629c4112017-11-06 16:27:15 +00001479 // Both calls must be 'fast' in order to remove them.
1480 if (!CI->isFast() || !OpC->isFast())
Sanjay Patelcddcd722016-01-06 19:23:35 +00001481 return Ret;
1482
Davide Italiano51507d22015-11-04 23:36:56 +00001483 // tan(atan(x)) -> x
1484 // tanf(atanf(x)) -> x
1485 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001486 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001487 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001488 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001489 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1490 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1491 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001492 Ret = OpC->getArgOperand(0);
1493 return Ret;
1494}
1495
Sanjay Patel57747212016-01-21 23:38:43 +00001496static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001497 // We can only hope to do anything useful if we can ignore things like errno
1498 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001499 // We already checked the prototype.
1500 return CI->hasFnAttr(Attribute::NoUnwind) &&
1501 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001502}
1503
Chris Bienemanad070d02014-09-17 20:55:46 +00001504static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1505 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001506 Value *&SinCos) {
1507 Type *ArgTy = Arg->getType();
1508 Type *ResTy;
1509 StringRef Name;
1510
1511 Triple T(OrigCallee->getParent()->getTargetTriple());
1512 if (UseFloat) {
1513 Name = "__sincospif_stret";
1514
1515 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1516 // x86_64 can't use {float, float} since that would be returned in both
1517 // xmm0 and xmm1, which isn't what a real struct would do.
1518 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001519 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1520 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001521 } else {
1522 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001523 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001524 }
1525
1526 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001527 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001528 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001529
1530 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1531 // If the argument is an instruction, it must dominate all uses so put our
1532 // sincos call there.
1533 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1534 } else {
1535 // Otherwise (e.g. for a constant) the beginning of the function is as
1536 // good a place as any.
1537 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1538 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1539 }
1540
1541 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1542
1543 if (SinCos->getType()->isStructTy()) {
1544 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1545 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1546 } else {
1547 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1548 "sinpi");
1549 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1550 "cospi");
1551 }
1552}
Chris Bienemanad070d02014-09-17 20:55:46 +00001553
1554Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 // Make sure the prototype is as expected, otherwise the rest of the
1556 // function is probably invalid and likely to abort.
1557 if (!isTrigLibCall(CI))
1558 return nullptr;
1559
1560 Value *Arg = CI->getArgOperand(0);
1561 SmallVector<CallInst *, 1> SinCalls;
1562 SmallVector<CallInst *, 1> CosCalls;
1563 SmallVector<CallInst *, 1> SinCosCalls;
1564
1565 bool IsFloat = Arg->getType()->isFloatTy();
1566
1567 // Look for all compatible sinpi, cospi and sincospi calls with the same
1568 // argument. If there are enough (in some sense) we can make the
1569 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001570 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001572 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001573
1574 // It's only worthwhile if both sinpi and cospi are actually used.
1575 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1576 return nullptr;
1577
1578 Value *Sin, *Cos, *SinCos;
1579 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1580
Davide Italianof024a562016-12-16 02:28:38 +00001581 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1582 Value *Res) {
1583 for (CallInst *C : Calls)
1584 replaceAllUsesWith(C, Res);
1585 };
1586
Chris Bienemanad070d02014-09-17 20:55:46 +00001587 replaceTrigInsts(SinCalls, Sin);
1588 replaceTrigInsts(CosCalls, Cos);
1589 replaceTrigInsts(SinCosCalls, SinCos);
1590
1591 return nullptr;
1592}
1593
David Majnemerabae6b52016-03-19 04:53:02 +00001594void LibCallSimplifier::classifyArgUse(
1595 Value *Val, Function *F, bool IsFloat,
1596 SmallVectorImpl<CallInst *> &SinCalls,
1597 SmallVectorImpl<CallInst *> &CosCalls,
1598 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001599 CallInst *CI = dyn_cast<CallInst>(Val);
1600
1601 if (!CI)
1602 return;
1603
David Majnemerabae6b52016-03-19 04:53:02 +00001604 // Don't consider calls in other functions.
1605 if (CI->getFunction() != F)
1606 return;
1607
Chris Bienemanad070d02014-09-17 20:55:46 +00001608 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001609 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001610 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001611 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001612 return;
1613
1614 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001615 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001616 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001617 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001619 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001620 SinCosCalls.push_back(CI);
1621 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001622 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001623 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001624 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001625 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001626 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001627 SinCosCalls.push_back(CI);
1628 }
1629}
1630
Meador Inge7415f842012-11-25 20:45:27 +00001631//===----------------------------------------------------------------------===//
1632// Integer Library Call Optimizations
1633//===----------------------------------------------------------------------===//
1634
Chris Bienemanad070d02014-09-17 20:55:46 +00001635Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001637 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001638 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001639 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1640 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001641 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001642 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1643 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001644
Chris Bienemanad070d02014-09-17 20:55:46 +00001645 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1646 return B.CreateSelect(Cond, V, B.getInt32(0));
1647}
Meador Ingea0b6d872012-11-26 00:24:07 +00001648
Davide Italiano85ad36b2016-12-15 23:45:11 +00001649Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1650 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1651 Value *Op = CI->getArgOperand(0);
1652 Type *ArgType = Op->getType();
1653 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1654 Intrinsic::ctlz, ArgType);
1655 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1656 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1657 V);
1658 return B.CreateIntCast(V, CI->getType(), false);
1659}
1660
Chris Bienemanad070d02014-09-17 20:55:46 +00001661Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001662 // abs(x) -> x >s -1 ? x : -x
1663 Value *Op = CI->getArgOperand(0);
1664 Value *Pos =
1665 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1666 Value *Neg = B.CreateNeg(Op, "neg");
1667 return B.CreateSelect(Pos, Op, Neg);
1668}
Meador Inge9a59ab62012-11-26 02:31:59 +00001669
Chris Bienemanad070d02014-09-17 20:55:46 +00001670Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001671 // isdigit(c) -> (c-'0') <u 10
1672 Value *Op = CI->getArgOperand(0);
1673 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1674 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1675 return B.CreateZExt(Op, CI->getType());
1676}
Meador Ingea62a39e2012-11-26 03:10:07 +00001677
Chris Bienemanad070d02014-09-17 20:55:46 +00001678Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 // isascii(c) -> c <u 128
1680 Value *Op = CI->getArgOperand(0);
1681 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1682 return B.CreateZExt(Op, CI->getType());
1683}
1684
1685Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001686 // toascii(c) -> c & 0x7f
1687 return B.CreateAnd(CI->getArgOperand(0),
1688 ConstantInt::get(CI->getType(), 0x7F));
1689}
Meador Inge604937d2012-11-26 03:38:52 +00001690
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00001691Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
1692 StringRef Str;
1693 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1694 return nullptr;
1695
1696 return convertStrToNumber(CI, Str, 10);
1697}
1698
1699Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
1700 StringRef Str;
1701 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1702 return nullptr;
1703
1704 if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
1705 return nullptr;
1706
1707 if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
1708 return convertStrToNumber(CI, Str, CInt->getSExtValue());
1709 }
1710
1711 return nullptr;
1712}
1713
Meador Inge08ca1152012-11-26 20:37:20 +00001714//===----------------------------------------------------------------------===//
1715// Formatting and IO Library Call Optimizations
1716//===----------------------------------------------------------------------===//
1717
Chris Bienemanad070d02014-09-17 20:55:46 +00001718static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001719
Chris Bienemanad070d02014-09-17 20:55:46 +00001720Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1721 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001722 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001723 // Error reporting calls should be cold, mark them as such.
1724 // This applies even to non-builtin calls: it is only a hint and applies to
1725 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001726
Chris Bienemanad070d02014-09-17 20:55:46 +00001727 // This heuristic was suggested in:
1728 // Improving Static Branch Prediction in a Compiler
1729 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1730 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001731 if (!CI->hasFnAttr(Attribute::Cold) &&
1732 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001733 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001735
Chris Bienemanad070d02014-09-17 20:55:46 +00001736 return nullptr;
1737}
1738
1739static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001740 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001741 return false;
1742
1743 if (StreamArg < 0)
1744 return true;
1745
1746 // These functions might be considered cold, but only if their stream
1747 // argument is stderr.
1748
1749 if (StreamArg >= (int)CI->getNumArgOperands())
1750 return false;
1751 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1752 if (!LI)
1753 return false;
1754 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1755 if (!GV || !GV->isDeclaration())
1756 return false;
1757 return GV->getName() == "stderr";
1758}
1759
1760Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1761 // Check for a fixed format string.
1762 StringRef FormatStr;
1763 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001764 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001765
Chris Bienemanad070d02014-09-17 20:55:46 +00001766 // Empty format string -> noop.
1767 if (FormatStr.empty()) // Tolerate printf's declared void.
1768 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001769
Chris Bienemanad070d02014-09-17 20:55:46 +00001770 // Do not do any of the following transformations if the printf return value
1771 // is used, in general the printf return value is not compatible with either
1772 // putchar() or puts().
1773 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001774 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001775
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001776 // printf("x") -> putchar('x'), even for "%" and "%%".
1777 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001778 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001779
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001780 // printf("%s", "a") --> putchar('a')
1781 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1782 StringRef ChrStr;
1783 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1784 return nullptr;
1785 if (ChrStr.size() != 1)
1786 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001787 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001788 }
1789
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 // printf("foo\n") --> puts("foo")
1791 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1792 FormatStr.find('%') == StringRef::npos) { // No format characters.
1793 // Create a string literal with no \n on it. We expect the constant merge
1794 // pass to be run after this pass, to merge duplicate strings.
1795 FormatStr = FormatStr.drop_back();
1796 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001797 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001798 }
Meador Inge08ca1152012-11-26 20:37:20 +00001799
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 // Optimize specific format strings.
1801 // printf("%c", chr) --> putchar(chr)
1802 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001803 CI->getArgOperand(1)->getType()->isIntegerTy())
1804 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001805
1806 // printf("%s\n", str) --> puts(str)
1807 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001808 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001809 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001810 return nullptr;
1811}
1812
1813Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1814
1815 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001816 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001817 if (Value *V = optimizePrintFString(CI, B)) {
1818 return V;
1819 }
1820
1821 // printf(format, ...) -> iprintf(format, ...) if no floating point
1822 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001823 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001824 Module *M = B.GetInsertBlock()->getParent()->getParent();
1825 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001826 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001827 CallInst *New = cast<CallInst>(CI->clone());
1828 New->setCalledFunction(IPrintFFn);
1829 B.Insert(New);
1830 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001831 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001832 return nullptr;
1833}
Meador Inge08ca1152012-11-26 20:37:20 +00001834
Chris Bienemanad070d02014-09-17 20:55:46 +00001835Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1836 // Check for a fixed format string.
1837 StringRef FormatStr;
1838 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001839 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001840
Chris Bienemanad070d02014-09-17 20:55:46 +00001841 // If we just have a format string (nothing else crazy) transform it.
1842 if (CI->getNumArgOperands() == 2) {
1843 // Make sure there's no % in the constant array. We could try to handle
1844 // %% -> % in the future if we cared.
1845 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1846 if (FormatStr[i] == '%')
1847 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001848
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001849 // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
1850 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001851 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001852 FormatStr.size() + 1)); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001853 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001854 }
Meador Ingef8e72502012-11-29 15:45:43 +00001855
Chris Bienemanad070d02014-09-17 20:55:46 +00001856 // The remaining optimizations require the format string to be "%s" or "%c"
1857 // and have an extra operand.
1858 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1859 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001860 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001861
Chris Bienemanad070d02014-09-17 20:55:46 +00001862 // Decode the second character of the format string.
1863 if (FormatStr[1] == 'c') {
1864 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1865 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1866 return nullptr;
1867 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001868 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001869 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001870 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001871 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001872
Chris Bienemanad070d02014-09-17 20:55:46 +00001873 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001874 }
1875
Chris Bienemanad070d02014-09-17 20:55:46 +00001876 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001877 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1878 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1879 return nullptr;
1880
Sanjay Pateld3112a52016-01-19 19:46:10 +00001881 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001882 if (!Len)
1883 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001884 Value *IncLen =
1885 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Daniel Neilson8acd8b02018-02-05 21:23:22 +00001886 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
Chris Bienemanad070d02014-09-17 20:55:46 +00001887
1888 // The sprintf result is the unincremented number of bytes in the string.
1889 return B.CreateIntCast(Len, CI->getType(), false);
1890 }
1891 return nullptr;
1892}
1893
1894Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1895 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001896 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001897 if (Value *V = optimizeSPrintFString(CI, B)) {
1898 return V;
1899 }
1900
1901 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1902 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001903 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001904 Module *M = B.GetInsertBlock()->getParent()->getParent();
1905 Constant *SIPrintFFn =
1906 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1907 CallInst *New = cast<CallInst>(CI->clone());
1908 New->setCalledFunction(SIPrintFFn);
1909 B.Insert(New);
1910 return New;
1911 }
1912 return nullptr;
1913}
1914
1915Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1916 optimizeErrorReporting(CI, B, 0);
1917
1918 // All the optimizations depend on the format string.
1919 StringRef FormatStr;
1920 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1921 return nullptr;
1922
1923 // Do not do any of the following transformations if the fprintf return
1924 // value is used, in general the fprintf return value is not compatible
1925 // with fwrite(), fputc() or fputs().
1926 if (!CI->use_empty())
1927 return nullptr;
1928
1929 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1930 if (CI->getNumArgOperands() == 2) {
1931 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1932 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1933 return nullptr; // We found a format specifier.
1934
Sanjay Pateld3112a52016-01-19 19:46:10 +00001935 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001936 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001937 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001938 CI->getArgOperand(0), B, DL, TLI);
1939 }
1940
1941 // The remaining optimizations require the format string to be "%s" or "%c"
1942 // and have an extra operand.
1943 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1944 CI->getNumArgOperands() < 3)
1945 return nullptr;
1946
1947 // Decode the second character of the format string.
1948 if (FormatStr[1] == 'c') {
1949 // fprintf(F, "%c", chr) --> fputc(chr, F)
1950 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1951 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001952 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001953 }
1954
1955 if (FormatStr[1] == 's') {
1956 // fprintf(F, "%s", str) --> fputs(str, F)
1957 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1958 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001959 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001960 }
1961 return nullptr;
1962}
1963
1964Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1965 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001966 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001967 if (Value *V = optimizeFPrintFString(CI, B)) {
1968 return V;
1969 }
1970
1971 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1972 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001973 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001974 Module *M = B.GetInsertBlock()->getParent()->getParent();
1975 Constant *FIPrintFFn =
1976 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1977 CallInst *New = cast<CallInst>(CI->clone());
1978 New->setCalledFunction(FIPrintFFn);
1979 B.Insert(New);
1980 return New;
1981 }
1982 return nullptr;
1983}
1984
1985Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1986 optimizeErrorReporting(CI, B, 3);
1987
Chris Bienemanad070d02014-09-17 20:55:46 +00001988 // Get the element size and count.
1989 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1990 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1991 if (!SizeC || !CountC)
1992 return nullptr;
1993 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1994
1995 // If this is writing zero records, remove the call (it's a noop).
1996 if (Bytes == 0)
1997 return ConstantInt::get(CI->getType(), 0);
1998
1999 // If this is writing one byte, turn it into fputc.
2000 // This optimisation is only valid, if the return value is unused.
2001 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00002002 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
2003 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002004 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
2005 }
2006
2007 return nullptr;
2008}
2009
2010Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
2011 optimizeErrorReporting(CI, B, 1);
2012
Sjoerd Meijer7435a912016-07-07 14:31:19 +00002013 // Don't rewrite fputs to fwrite when optimising for size because fwrite
2014 // requires more arguments and thus extra MOVs are required.
2015 if (CI->getParent()->getParent()->optForSize())
2016 return nullptr;
2017
Ahmed Bougachad765a822016-04-27 19:04:35 +00002018 // We can't optimize if return value is used.
2019 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00002020 return nullptr;
2021
2022 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
2023 uint64_t Len = GetStringLength(CI->getArgOperand(0));
2024 if (!Len)
2025 return nullptr;
2026
2027 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00002028 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00002029 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002030 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002031 CI->getArgOperand(1), B, DL, TLI);
2032}
2033
2034Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002035 // Check for a constant string.
2036 StringRef Str;
2037 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2038 return nullptr;
2039
2040 if (Str.empty() && CI->use_empty()) {
2041 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00002042 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002043 if (CI->use_empty() || !Res)
2044 return Res;
2045 return B.CreateIntCast(Res, CI->getType(), true);
2046 }
2047
2048 return nullptr;
2049}
2050
2051bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002052 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002053 SmallString<20> FloatFuncName = FuncName;
2054 FloatFuncName += 'f';
2055 if (TLI->getLibFunc(FloatFuncName, Func))
2056 return TLI->has(Func);
2057 return false;
2058}
Meador Inge7fb2f732012-10-13 16:45:32 +00002059
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002060Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2061 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002062 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002063 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002064 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002065 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002066 // Make sure we never change the calling convention.
2067 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00002068 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002069 "Optimizing string/memory libcall would change the calling convention");
2070 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002071 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002072 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002073 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002074 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002075 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002076 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002077 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002078 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002079 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002080 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002081 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002082 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002083 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002084 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002085 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002086 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002087 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002088 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002089 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002090 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002091 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002092 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002093 case LibFunc_strtol:
2094 case LibFunc_strtod:
2095 case LibFunc_strtof:
2096 case LibFunc_strtoul:
2097 case LibFunc_strtoll:
2098 case LibFunc_strtold:
2099 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002100 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002101 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002102 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002103 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002104 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002105 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002106 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002107 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002108 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002109 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002110 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002111 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002112 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002113 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002114 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002115 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002116 return optimizeMemSet(CI, Builder);
Sanjay Patelb2ab3f22018-04-18 14:21:31 +00002117 case LibFunc_realloc:
2118 return optimizeRealloc(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002119 case LibFunc_wcslen:
2120 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002121 default:
2122 break;
2123 }
2124 }
2125 return nullptr;
2126}
2127
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002128Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2129 LibFunc Func,
2130 IRBuilder<> &Builder) {
2131 // Don't optimize calls that require strict floating point semantics.
2132 if (CI->isStrictFP())
2133 return nullptr;
2134
2135 switch (Func) {
2136 case LibFunc_cosf:
2137 case LibFunc_cos:
2138 case LibFunc_cosl:
2139 return optimizeCos(CI, Builder);
2140 case LibFunc_sinpif:
2141 case LibFunc_sinpi:
2142 case LibFunc_cospif:
2143 case LibFunc_cospi:
2144 return optimizeSinCosPi(CI, Builder);
2145 case LibFunc_powf:
2146 case LibFunc_pow:
2147 case LibFunc_powl:
2148 return optimizePow(CI, Builder);
2149 case LibFunc_exp2l:
2150 case LibFunc_exp2:
2151 case LibFunc_exp2f:
2152 return optimizeExp2(CI, Builder);
2153 case LibFunc_fabsf:
2154 case LibFunc_fabs:
2155 case LibFunc_fabsl:
2156 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2157 case LibFunc_sqrtf:
2158 case LibFunc_sqrt:
2159 case LibFunc_sqrtl:
2160 return optimizeSqrt(CI, Builder);
2161 case LibFunc_log:
2162 case LibFunc_log10:
2163 case LibFunc_log1p:
2164 case LibFunc_log2:
2165 case LibFunc_logb:
2166 return optimizeLog(CI, Builder);
2167 case LibFunc_tan:
2168 case LibFunc_tanf:
2169 case LibFunc_tanl:
2170 return optimizeTan(CI, Builder);
2171 case LibFunc_ceil:
2172 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2173 case LibFunc_floor:
2174 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2175 case LibFunc_round:
2176 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2177 case LibFunc_nearbyint:
2178 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2179 case LibFunc_rint:
2180 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2181 case LibFunc_trunc:
2182 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2183 case LibFunc_acos:
2184 case LibFunc_acosh:
2185 case LibFunc_asin:
2186 case LibFunc_asinh:
2187 case LibFunc_atan:
2188 case LibFunc_atanh:
2189 case LibFunc_cbrt:
2190 case LibFunc_cosh:
2191 case LibFunc_exp:
2192 case LibFunc_exp10:
2193 case LibFunc_expm1:
2194 case LibFunc_sin:
2195 case LibFunc_sinh:
2196 case LibFunc_tanh:
2197 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2198 return optimizeUnaryDoubleFP(CI, Builder, true);
2199 return nullptr;
2200 case LibFunc_copysign:
2201 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2202 return optimizeBinaryDoubleFP(CI, Builder);
2203 return nullptr;
2204 case LibFunc_fminf:
2205 case LibFunc_fmin:
2206 case LibFunc_fminl:
2207 case LibFunc_fmaxf:
2208 case LibFunc_fmax:
2209 case LibFunc_fmaxl:
2210 return optimizeFMinFMax(CI, Builder);
Hal Finkel2ff24732017-12-16 01:26:25 +00002211 case LibFunc_cabs:
2212 case LibFunc_cabsf:
2213 case LibFunc_cabsl:
2214 return optimizeCAbs(CI, Builder);
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002215 default:
2216 return nullptr;
2217 }
2218}
2219
Chris Bienemanad070d02014-09-17 20:55:46 +00002220Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002221 // TODO: Split out the code below that operates on FP calls so that
2222 // we can all non-FP calls with the StrictFP attribute to be
2223 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002224 if (CI->isNoBuiltin())
2225 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002226
David L. Jonesd21529f2017-01-23 23:16:46 +00002227 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002228 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002229
2230 SmallVector<OperandBundleDef, 2> OpBundles;
2231 CI->getOperandBundlesAsDefs(OpBundles);
2232 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002233 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002234
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002235 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002236 // This can't be moved to optimizeFloatingPointLibCall() because it may be
Sanjay Patel629c4112017-11-06 16:27:15 +00002237 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002238 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2239 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Patel629c4112017-11-06 16:27:15 +00002240 else if (isa<FPMathOperator>(CI) && CI->isFast())
Davide Italianoa904e522015-10-29 02:58:44 +00002241 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002242
Sanjay Patel848309d2014-10-23 21:52:45 +00002243 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002244 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002245 if (!isCallingConvC)
2246 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002247 // The FP intrinsics have corresponding constrained versions so we don't
2248 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002249 switch (II->getIntrinsicID()) {
2250 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002251 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002252 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002253 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002254 case Intrinsic::log:
2255 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002256 case Intrinsic::sqrt:
2257 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002258 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002259 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002260 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002261 }
2262 }
2263
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002264 // Also try to simplify calls to fortified library functions.
2265 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2266 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002267 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002268 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2269 // Use an IR Builder from SimplifiedCI if available instead of CI
2270 // to guarantee we reach all uses we might replace later on.
2271 IRBuilder<> TmpBuilder(SimplifiedCI);
2272 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002273 // If we were able to further simplify, remove the now redundant call.
2274 SimplifiedCI->replaceAllUsesWith(V);
2275 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002276 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002277 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002278 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002279 return SimplifiedFortifiedCI;
2280 }
2281
Meador Inge20255ef2013-03-12 00:08:29 +00002282 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002283 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002284 // We never change the calling convention.
2285 if (!ignoreCallingConv(Func) && !isCallingConvC)
2286 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002287 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2288 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002289 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2290 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002291 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002292 case LibFunc_ffs:
2293 case LibFunc_ffsl:
2294 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002295 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002296 case LibFunc_fls:
2297 case LibFunc_flsl:
2298 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002299 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002300 case LibFunc_abs:
2301 case LibFunc_labs:
2302 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002303 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002304 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002305 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002306 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002307 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002308 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002309 return optimizeToAscii(CI, Builder);
David Bolvanskycb8ca5f32018-04-25 18:58:53 +00002310 case LibFunc_atoi:
2311 case LibFunc_atol:
2312 case LibFunc_atoll:
2313 return optimizeAtoi(CI, Builder);
2314 case LibFunc_strtol:
2315 case LibFunc_strtoll:
2316 return optimizeStrtol(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002317 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002318 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002319 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002320 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002321 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002322 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002323 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002324 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002325 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002326 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002327 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002328 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002329 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002330 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002331 case LibFunc_vfprintf:
2332 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002333 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002334 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002335 return optimizeErrorReporting(CI, Builder, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002336 default:
2337 return nullptr;
2338 }
Meador Inge20255ef2013-03-12 00:08:29 +00002339 }
Craig Topperf40110f2014-04-25 05:29:35 +00002340 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002341}
2342
Chandler Carruth92803822015-01-21 02:11:59 +00002343LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002344 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002345 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002346 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002347 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2348 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002349
2350void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2351 // Indirect through the replacer used in this instance.
2352 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002353}
2354
Meador Ingedfb08a22013-06-20 19:48:07 +00002355// TODO:
2356// Additional cases that we need to add to this file:
2357//
2358// cbrt:
2359// * cbrt(expN(X)) -> expN(x/3)
2360// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002361// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002362//
2363// exp, expf, expl:
2364// * exp(log(x)) -> x
2365//
2366// log, logf, logl:
2367// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002368// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002369// * log(exp10(y)) -> y*log(10)
2370// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002371//
Meador Ingedfb08a22013-06-20 19:48:07 +00002372// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002373// * pow(sqrt(x),y) -> pow(x,y*0.5)
2374// * pow(pow(x,y),z)-> pow(x,y*z)
2375//
Meador Ingedfb08a22013-06-20 19:48:07 +00002376// signbit:
2377// * signbit(cnst) -> cnst'
2378// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2379//
2380// sqrt, sqrtf, sqrtl:
2381// * sqrt(expN(x)) -> expN(x*0.5)
2382// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2383// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2384//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002385
2386//===----------------------------------------------------------------------===//
2387// Fortified Library Call Optimizations
2388//===----------------------------------------------------------------------===//
2389
2390bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2391 unsigned ObjSizeOp,
2392 unsigned SizeOp,
2393 bool isString) {
2394 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2395 return true;
2396 if (ConstantInt *ObjSizeCI =
2397 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002398 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002399 return true;
2400 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2401 if (OnlyLowerUnknownSize)
2402 return false;
2403 if (isString) {
2404 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2405 // If the length is 0 we don't know how long it is and so we can't
2406 // remove the check.
2407 if (Len == 0)
2408 return false;
2409 return ObjSizeCI->getZExtValue() >= Len;
2410 }
2411 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2412 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2413 }
2414 return false;
2415}
2416
Sanjay Pateld707db92015-12-31 16:10:49 +00002417Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2418 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002419 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002420 B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2421 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002422 return CI->getArgOperand(0);
2423 }
2424 return nullptr;
2425}
2426
Sanjay Pateld707db92015-12-31 16:10:49 +00002427Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2428 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002429 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Daniel Neilson8acd8b02018-02-05 21:23:22 +00002430 B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
2431 CI->getArgOperand(2));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002432 return CI->getArgOperand(0);
2433 }
2434 return nullptr;
2435}
2436
Sanjay Pateld707db92015-12-31 16:10:49 +00002437Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2438 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002439 // TODO: Try foldMallocMemset() here.
2440
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002441 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2442 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2443 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2444 return CI->getArgOperand(0);
2445 }
2446 return nullptr;
2447}
2448
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002449Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2450 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002451 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002452 Function *Callee = CI->getCalledFunction();
2453 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002454 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002455 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2456 *ObjSize = CI->getArgOperand(2);
2457
2458 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002459 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002460 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002461 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002462 }
2463
2464 // If a) we don't have any length information, or b) we know this will
2465 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2466 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2467 // TODO: It might be nice to get a maximum length out of the possible
2468 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002469 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002470 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002471
David Blaikie65fab6d2015-04-03 21:32:06 +00002472 if (OnlyLowerUnknownSize)
2473 return nullptr;
2474
2475 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2476 uint64_t Len = GetStringLength(Src);
2477 if (Len == 0)
2478 return nullptr;
2479
2480 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2481 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002482 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002483 // If the function was an __stpcpy_chk, and we were able to fold it into
2484 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002486 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2487 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002488}
2489
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002490Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2491 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002492 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002493 Function *Callee = CI->getCalledFunction();
2494 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002495 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002496 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002497 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002498 return Ret;
2499 }
2500 return nullptr;
2501}
2502
2503Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002504 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2505 // Some clang users checked for _chk libcall availability using:
2506 // __has_builtin(__builtin___memcpy_chk)
2507 // When compiling with -fno-builtin, this is always true.
2508 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2509 // end up with fortified libcalls, which isn't acceptable in a freestanding
2510 // environment which only provides their non-fortified counterparts.
2511 //
2512 // Until we change clang and/or teach external users to check for availability
2513 // differently, disregard the "nobuiltin" attribute and TLI::has.
2514 //
2515 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002516
David L. Jonesd21529f2017-01-23 23:16:46 +00002517 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002518 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002519
2520 SmallVector<OperandBundleDef, 2> OpBundles;
2521 CI->getOperandBundlesAsDefs(OpBundles);
2522 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002523 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002524
Ahmed Bougachad765a822016-04-27 19:04:35 +00002525 // First, check that this is a known library functions and that the prototype
2526 // is correct.
2527 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002528 return nullptr;
2529
2530 // We never change the calling convention.
2531 if (!ignoreCallingConv(Func) && !isCallingConvC)
2532 return nullptr;
2533
2534 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002535 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002536 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002537 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002538 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002539 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002540 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002541 case LibFunc_stpcpy_chk:
2542 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002543 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002544 case LibFunc_stpncpy_chk:
2545 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002546 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002547 default:
2548 break;
2549 }
2550 return nullptr;
2551}
2552
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002553FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2554 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2555 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}