blob: 8257dbcf8586efaeff34daa1d152f27e268ebc9e [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//
10// This is a utility pass used for testing the InstructionSimplify analysis.
11// The analysis is applied to every instruction, and if it simplifies then the
12// instruction is replaced by the simplification. If you are looking for a pass
13// that performs serious instruction folding, use the instcombine pass instead.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Meador Inge20255ef2013-03-12 00:08:29 +000018#include "llvm/ADT/SmallString.h"
Meador Ingedf796f82012-10-13 16:45:24 +000019#include "llvm/ADT/StringMap.h"
Bob Wilsond8d92d92013-11-03 06:48:38 +000020#include "llvm/ADT/Triple.h"
Adam Nemetea06e6e2017-07-26 19:03:18 +000021#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000022#include "llvm/Analysis/TargetLibraryInfo.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"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Sanjay Patela92fa442014-10-22 15:29:23 +000041 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
42 cl::init(false),
43 cl::desc("Enable unsafe double to float "
44 "shrinking for math lib calls"));
45
46
Meador Ingedf796f82012-10-13 16:45:24 +000047//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000048// Helper Functions
49//===----------------------------------------------------------------------===//
50
David L. Jonesd21529f2017-01-23 23:16:46 +000051static bool ignoreCallingConv(LibFunc Func) {
52 return Func == LibFunc_abs || Func == LibFunc_labs ||
53 Func == LibFunc_llabs || Func == LibFunc_strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000054}
55
Sam Parker214f7bf2016-09-13 12:10:14 +000056static bool isCallingConvCCompatible(CallInst *CI) {
57 switch(CI->getCallingConv()) {
58 default:
59 return false;
60 case llvm::CallingConv::C:
61 return true;
62 case llvm::CallingConv::ARM_APCS:
63 case llvm::CallingConv::ARM_AAPCS:
64 case llvm::CallingConv::ARM_AAPCS_VFP: {
65
66 // The iOS ABI diverges from the standard in some cases, so for now don't
67 // try to simplify those calls.
68 if (Triple(CI->getModule()->getTargetTriple()).isiOS())
69 return false;
70
71 auto *FuncTy = CI->getFunctionType();
72
73 if (!FuncTy->getReturnType()->isPointerTy() &&
74 !FuncTy->getReturnType()->isIntegerTy() &&
75 !FuncTy->getReturnType()->isVoidTy())
76 return false;
77
78 for (auto Param : FuncTy->params()) {
79 if (!Param->isPointerTy() && !Param->isIntegerTy())
80 return false;
81 }
82 return true;
83 }
84 }
85 return false;
86}
87
Sanjay Pateld707db92015-12-31 16:10:49 +000088/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000089static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000090 for (User *U : V->users()) {
91 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000092 if (IC->isEquality() && IC->getOperand(1) == With)
93 continue;
94 // Unknown instruction.
95 return false;
96 }
97 return true;
98}
99
Meador Inge08ca1152012-11-26 20:37:20 +0000100static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000101 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000102 return OI->getType()->isFloatingPointTy();
103 });
Meador Inge08ca1152012-11-26 20:37:20 +0000104}
105
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000106/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000107/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000108static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000109 LibFunc DoubleFn, LibFunc FloatFn,
110 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000111 switch (Ty->getTypeID()) {
112 case Type::FloatTyID:
113 return TLI->has(FloatFn);
114 case Type::DoubleTyID:
115 return TLI->has(DoubleFn);
116 default:
117 return TLI->has(LongDoubleFn);
118 }
119}
120
Meador Inged589ac62012-10-31 03:33:06 +0000121//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000122// String and Memory Library Call Optimizations
123//===----------------------------------------------------------------------===//
124
Chris Bienemanad070d02014-09-17 20:55:46 +0000125Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000126 // Extract some information from the instruction
127 Value *Dst = CI->getArgOperand(0);
128 Value *Src = CI->getArgOperand(1);
129
130 // See if we can get the length of the input string.
131 uint64_t Len = GetStringLength(Src);
132 if (Len == 0)
133 return nullptr;
134 --Len; // Unbias length.
135
136 // Handle the simple, do-nothing case: strcat(x, "") -> x
137 if (Len == 0)
138 return Dst;
139
Chris Bienemanad070d02014-09-17 20:55:46 +0000140 return emitStrLenMemCpy(Src, Dst, Len, B);
141}
142
143Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
144 IRBuilder<> &B) {
145 // We need to find the end of the destination string. That's where the
146 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000147 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000148 if (!DstLen)
149 return nullptr;
150
151 // Now that we have the destination's length, we must index into the
152 // destination's pointer to get the actual memcpy destination (end of
153 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000154 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000155
156 // We have enough information to now generate the memcpy call to do the
157 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158 B.CreateMemCpy(CpyDst, Src,
159 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000160 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000161 return Dst;
162}
163
164Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000165 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000166 Value *Dst = CI->getArgOperand(0);
167 Value *Src = CI->getArgOperand(1);
168 uint64_t Len;
169
Sanjay Pateld707db92015-12-31 16:10:49 +0000170 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000171 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
172 Len = LengthArg->getZExtValue();
173 else
174 return nullptr;
175
176 // See if we can get the length of the input string.
177 uint64_t SrcLen = GetStringLength(Src);
178 if (SrcLen == 0)
179 return nullptr;
180 --SrcLen; // Unbias length.
181
182 // Handle the simple, do-nothing cases:
183 // strncat(x, "", c) -> x
184 // strncat(x, c, 0) -> x
185 if (SrcLen == 0 || Len == 0)
186 return Dst;
187
Sanjay Pateld707db92015-12-31 16:10:49 +0000188 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000189 if (Len < SrcLen)
190 return nullptr;
191
192 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000193 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000194 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
195}
196
197Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
198 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000199 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 Value *SrcStr = CI->getArgOperand(0);
201
202 // If the second operand is non-constant, see if we can compute the length
203 // of the input string and turn this into memchr.
204 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
205 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000206 uint64_t Len = GetStringLength(SrcStr);
207 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
208 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000209
Sanjay Pateld3112a52016-01-19 19:46:10 +0000210 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000211 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
212 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000213 }
214
Chris Bienemanad070d02014-09-17 20:55:46 +0000215 // Otherwise, the character is a constant, see if the first argument is
216 // a string literal. If so, we can constant fold.
217 StringRef Str;
218 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000219 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000220 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000221 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000222 return nullptr;
223 }
224
225 // Compute the offset, make sure to handle the case when we're searching for
226 // zero (a weird way to spell strlen).
227 size_t I = (0xFF & CharC->getSExtValue()) == 0
228 ? Str.size()
229 : Str.find(CharC->getSExtValue());
230 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
231 return Constant::getNullValue(CI->getType());
232
233 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000234 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000235}
236
237Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000238 Value *SrcStr = CI->getArgOperand(0);
239 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
240
241 // Cannot fold anything if we're not looking for a constant.
242 if (!CharC)
243 return nullptr;
244
245 StringRef Str;
246 if (!getConstantStringInfo(SrcStr, Str)) {
247 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000249 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000250 return nullptr;
251 }
252
253 // Compute the offset.
254 size_t I = (0xFF & CharC->getSExtValue()) == 0
255 ? Str.size()
256 : Str.rfind(CharC->getSExtValue());
257 if (I == StringRef::npos) // Didn't find the char. Return null.
258 return Constant::getNullValue(CI->getType());
259
260 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000261 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000262}
263
264Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000265 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
266 if (Str1P == Str2P) // strcmp(x,x) -> 0
267 return ConstantInt::get(CI->getType(), 0);
268
269 StringRef Str1, Str2;
270 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
271 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
272
273 // strcmp(x, y) -> cnst (if both x and y are constant strings)
274 if (HasStr1 && HasStr2)
275 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
276
277 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
278 return B.CreateNeg(
279 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
280
281 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
282 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
283
284 // strcmp(P, "x") -> memcmp(P, "x", 2)
285 uint64_t Len1 = GetStringLength(Str1P);
286 uint64_t Len2 = GetStringLength(Str2P);
287 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000288 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000290 std::min(Len1, Len2)),
291 B, DL, TLI);
292 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000293
Chris Bienemanad070d02014-09-17 20:55:46 +0000294 return nullptr;
295}
296
297Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000298 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
299 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
300 return ConstantInt::get(CI->getType(), 0);
301
302 // Get the length argument if it is constant.
303 uint64_t Length;
304 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
305 Length = LengthArg->getZExtValue();
306 else
307 return nullptr;
308
309 if (Length == 0) // strncmp(x,y,0) -> 0
310 return ConstantInt::get(CI->getType(), 0);
311
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000313 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000314
315 StringRef Str1, Str2;
316 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
317 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
318
319 // strncmp(x, y) -> cnst (if both x and y are constant strings)
320 if (HasStr1 && HasStr2) {
321 StringRef SubStr1 = Str1.substr(0, Length);
322 StringRef SubStr2 = Str2.substr(0, Length);
323 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
324 }
325
326 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
327 return B.CreateNeg(
328 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
329
330 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
331 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
332
333 return nullptr;
334}
335
336Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000337 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
338 if (Dst == Src) // strcpy(x,x) -> x
339 return Src;
340
Chris Bienemanad070d02014-09-17 20:55:46 +0000341 // See if we can get the length of the input string.
342 uint64_t Len = GetStringLength(Src);
343 if (Len == 0)
344 return nullptr;
345
346 // We have enough information to now generate the memcpy call to do the
347 // copy for us. Make a memcpy to copy the nul byte with align = 1.
348 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000349 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000350 return Dst;
351}
352
353Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
354 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000355 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
356 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000357 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000358 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000359 }
360
361 // See if we can get the length of the input string.
362 uint64_t Len = GetStringLength(Src);
363 if (Len == 0)
364 return nullptr;
365
Davide Italianob7487e62015-11-02 23:07:14 +0000366 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000367 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000368 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
369 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000370
371 // We have enough information to now generate the memcpy call to do the
372 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000373 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000374 return DstEnd;
375}
376
377Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
378 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000379 Value *Dst = CI->getArgOperand(0);
380 Value *Src = CI->getArgOperand(1);
381 Value *LenOp = CI->getArgOperand(2);
382
383 // See if we can get the length of the input string.
384 uint64_t SrcLen = GetStringLength(Src);
385 if (SrcLen == 0)
386 return nullptr;
387 --SrcLen;
388
389 if (SrcLen == 0) {
390 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
391 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000392 return Dst;
393 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000394
Chris Bienemanad070d02014-09-17 20:55:46 +0000395 uint64_t Len;
396 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
397 Len = LengthArg->getZExtValue();
398 else
399 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000400
Chris Bienemanad070d02014-09-17 20:55:46 +0000401 if (Len == 0)
402 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000403
Chris Bienemanad070d02014-09-17 20:55:46 +0000404 // Let strncpy handle the zero padding
405 if (Len > SrcLen + 1)
406 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000407
Davide Italianob7487e62015-11-02 23:07:14 +0000408 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000409 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000410 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000411
Chris Bienemanad070d02014-09-17 20:55:46 +0000412 return Dst;
413}
Meador Inge7fb2f732012-10-13 16:45:32 +0000414
Matthias Braun50ec0b52017-05-19 22:37:09 +0000415Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
416 unsigned CharSize) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000417 Value *Src = CI->getArgOperand(0);
418
419 // Constant folding: strlen("xyz") -> 3
Matthias Braun50ec0b52017-05-19 22:37:09 +0000420 if (uint64_t Len = GetStringLength(Src, CharSize))
Chris Bienemanad070d02014-09-17 20:55:46 +0000421 return ConstantInt::get(CI->getType(), Len - 1);
422
David L Kreitzer752c1442016-04-13 14:31:06 +0000423 // If s is a constant pointer pointing to a string literal, we can fold
Matthias Braun50ec0b52017-05-19 22:37:09 +0000424 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
David L Kreitzer752c1442016-04-13 14:31:06 +0000425 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000426 // We only try to simplify strlen when the pointer s points to an array
David L Kreitzer752c1442016-04-13 14:31:06 +0000427 // of i8. Otherwise, we would need to scale the offset x before doing the
Matthias Braun50ec0b52017-05-19 22:37:09 +0000428 // subtraction. This will make the optimization more complex, and it's not
429 // very useful because calling strlen for a pointer of other types is
David L Kreitzer752c1442016-04-13 14:31:06 +0000430 // very uncommon.
431 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000432 if (!isGEPBasedOnPointerToString(GEP, CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +0000433 return nullptr;
434
Matthias Braun50ec0b52017-05-19 22:37:09 +0000435 ConstantDataArraySlice Slice;
436 if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
437 uint64_t NullTermIdx;
438 if (Slice.Array == nullptr) {
439 NullTermIdx = 0;
440 } else {
441 NullTermIdx = ~((uint64_t)0);
442 for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
443 if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
444 NullTermIdx = I;
445 break;
446 }
447 }
448 // If the string does not have '\0', leave it to strlen to compute
449 // its length.
450 if (NullTermIdx == ~((uint64_t)0))
451 return nullptr;
452 }
453
David L Kreitzer752c1442016-04-13 14:31:06 +0000454 Value *Offset = GEP->getOperand(2);
Craig Topper8205a1a2017-05-24 16:53:07 +0000455 KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +0000456 Known.Zero.flipAllBits();
Matthias Braun50ec0b52017-05-19 22:37:09 +0000457 uint64_t ArrSize =
David L Kreitzer752c1442016-04-13 14:31:06 +0000458 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
459
Matthias Braun50ec0b52017-05-19 22:37:09 +0000460 // KnownZero's bits are flipped, so zeros in KnownZero now represent
461 // bits known to be zeros in Offset, and ones in KnowZero represent
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 // bits unknown in Offset. Therefore, Offset is known to be in range
Matthias Braun50ec0b52017-05-19 22:37:09 +0000463 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
David L Kreitzer752c1442016-04-13 14:31:06 +0000464 // unsigned-less-than NullTermIdx.
465 //
Matthias Braun50ec0b52017-05-19 22:37:09 +0000466 // If Offset is not provably in the range [0, NullTermIdx], we can still
467 // optimize if we can prove that the program has undefined behavior when
468 // Offset is outside that range. That is the case when GEP->getOperand(0)
David L Kreitzer752c1442016-04-13 14:31:06 +0000469 // is a pointer to an object whose memory extent is NullTermIdx+1.
Matthias Braun50ec0b52017-05-19 22:37:09 +0000470 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000471 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
Matthias Braun50ec0b52017-05-19 22:37:09 +0000472 NullTermIdx == ArrSize - 1)) {
473 Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
474 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
David L Kreitzer752c1442016-04-13 14:31:06 +0000475 Offset);
Matthias Braun50ec0b52017-05-19 22:37:09 +0000476 }
David L Kreitzer752c1442016-04-13 14:31:06 +0000477 }
478
479 return nullptr;
480 }
481
Chris Bienemanad070d02014-09-17 20:55:46 +0000482 // strlen(x?"foo":"bars") --> x ? 3 : 4
483 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +0000484 uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
485 uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
Chris Bienemanad070d02014-09-17 20:55:46 +0000486 if (LenTrue && LenFalse) {
Adam Nemetea06e6e2017-07-26 19:03:18 +0000487 ORE.emit(OptimizationRemark("instcombine", "simplify-libcalls", CI)
488 << "folded strlen(select) to select of constants");
Chris Bienemanad070d02014-09-17 20:55:46 +0000489 return B.CreateSelect(SI->getCondition(),
490 ConstantInt::get(CI->getType(), LenTrue - 1),
491 ConstantInt::get(CI->getType(), LenFalse - 1));
492 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000493 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000494
Chris Bienemanad070d02014-09-17 20:55:46 +0000495 // strlen(x) != 0 --> *x != 0
496 // strlen(x) == 0 --> *x == 0
497 if (isOnlyUsedInZeroEqualityComparison(CI))
498 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000499
Chris Bienemanad070d02014-09-17 20:55:46 +0000500 return nullptr;
501}
Meador Inge17418502012-10-13 16:45:37 +0000502
Matthias Braun50ec0b52017-05-19 22:37:09 +0000503Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
504 return optimizeStringLength(CI, B, 8);
505}
506
507Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
508 Module &M = *CI->getParent()->getParent()->getParent();
509 unsigned WCharSize = TLI->getWCharSize(M) * 8;
510
511 return optimizeStringLength(CI, B, WCharSize);
512}
513
Chris Bienemanad070d02014-09-17 20:55:46 +0000514Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000515 StringRef S1, S2;
516 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
517 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000518
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000519 // strpbrk(s, "") -> nullptr
520 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000521 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
522 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000523
Chris Bienemanad070d02014-09-17 20:55:46 +0000524 // Constant folding.
525 if (HasS1 && HasS2) {
526 size_t I = S1.find_first_of(S2);
527 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000528 return Constant::getNullValue(CI->getType());
529
Sanjay Pateld707db92015-12-31 16:10:49 +0000530 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
531 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000532 }
Meador Inge17418502012-10-13 16:45:37 +0000533
Chris Bienemanad070d02014-09-17 20:55:46 +0000534 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000535 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000536 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000537
538 return nullptr;
539}
540
541Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000542 Value *EndPtr = CI->getArgOperand(1);
543 if (isa<ConstantPointerNull>(EndPtr)) {
544 // With a null EndPtr, this function won't capture the main argument.
545 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000546 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000547 }
548
549 return nullptr;
550}
551
552Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000553 StringRef S1, S2;
554 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
555 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
556
557 // strspn(s, "") -> 0
558 // strspn("", s) -> 0
559 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
560 return Constant::getNullValue(CI->getType());
561
562 // Constant folding.
563 if (HasS1 && HasS2) {
564 size_t Pos = S1.find_first_not_of(S2);
565 if (Pos == StringRef::npos)
566 Pos = S1.size();
567 return ConstantInt::get(CI->getType(), Pos);
568 }
569
570 return nullptr;
571}
572
573Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000574 StringRef S1, S2;
575 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
576 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
577
578 // strcspn("", s) -> 0
579 if (HasS1 && S1.empty())
580 return Constant::getNullValue(CI->getType());
581
582 // Constant folding.
583 if (HasS1 && HasS2) {
584 size_t Pos = S1.find_first_of(S2);
585 if (Pos == StringRef::npos)
586 Pos = S1.size();
587 return ConstantInt::get(CI->getType(), Pos);
588 }
589
590 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000591 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000592 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000593
594 return nullptr;
595}
596
597Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000598 // fold strstr(x, x) -> x.
599 if (CI->getArgOperand(0) == CI->getArgOperand(1))
600 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
601
602 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000603 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000604 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000605 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000606 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000607 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000608 StrLen, B, DL, TLI);
609 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000610 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000611 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
612 ICmpInst *Old = cast<ICmpInst>(*UI++);
613 Value *Cmp =
614 B.CreateICmp(Old->getPredicate(), StrNCmp,
615 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
616 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000617 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000618 return CI;
619 }
Meador Inge17418502012-10-13 16:45:37 +0000620
Chris Bienemanad070d02014-09-17 20:55:46 +0000621 // See if either input string is a constant string.
622 StringRef SearchStr, ToFindStr;
623 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
624 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
625
626 // fold strstr(x, "") -> x.
627 if (HasStr2 && ToFindStr.empty())
628 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
629
630 // If both strings are known, constant fold it.
631 if (HasStr1 && HasStr2) {
632 size_t Offset = SearchStr.find(ToFindStr);
633
634 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000635 return Constant::getNullValue(CI->getType());
636
Chris Bienemanad070d02014-09-17 20:55:46 +0000637 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000638 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000639 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
640 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000641 }
Meador Inge17418502012-10-13 16:45:37 +0000642
Chris Bienemanad070d02014-09-17 20:55:46 +0000643 // fold strstr(x, "y") -> strchr(x, 'y').
644 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000645 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000646 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
647 }
648 return nullptr;
649}
Meador Inge40b6fac2012-10-15 03:47:37 +0000650
Benjamin Kramer691363e2015-03-21 15:36:21 +0000651Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000652 Value *SrcStr = CI->getArgOperand(0);
653 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
654 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
655
656 // memchr(x, y, 0) -> null
Craig Topper79ab6432017-07-06 18:39:47 +0000657 if (LenC && LenC->isZero())
Benjamin Kramer691363e2015-03-21 15:36:21 +0000658 return Constant::getNullValue(CI->getType());
659
Benjamin Kramer7857d722015-03-21 21:09:33 +0000660 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000661 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000662 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000663 return nullptr;
664
665 // Truncate the string to LenC. If Str is smaller than LenC we will still only
666 // scan the string, as reading past the end of it is undefined and we can just
667 // return null if we don't find the char.
668 Str = Str.substr(0, LenC->getZExtValue());
669
Benjamin Kramer7857d722015-03-21 21:09:33 +0000670 // If the char is variable but the input str and length are not we can turn
671 // this memchr call into a simple bit field test. Of course this only works
672 // when the return value is only checked against null.
673 //
674 // It would be really nice to reuse switch lowering here but we can't change
675 // the CFG at this point.
676 //
677 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
678 // after bounds check.
679 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000680 unsigned char Max =
681 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
682 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000683
684 // Make sure the bit field we're about to create fits in a register on the
685 // target.
686 // FIXME: On a 64 bit architecture this prevents us from using the
687 // interesting range of alpha ascii chars. We could do better by emitting
688 // two bitfields or shifting the range by 64 if no lower chars are used.
689 if (!DL.fitsInLegalInteger(Max + 1))
690 return nullptr;
691
692 // For the bit field use a power-of-2 type with at least 8 bits to avoid
693 // creating unnecessary illegal types.
694 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
695
696 // Now build the bit field.
697 APInt Bitfield(Width, 0);
698 for (char C : Str)
699 Bitfield.setBit((unsigned char)C);
700 Value *BitfieldC = B.getInt(Bitfield);
701
702 // First check that the bit field access is within bounds.
703 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
704 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
705 "memchr.bounds");
706
707 // Create code that checks if the given bit is set in the field.
708 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
709 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
710
711 // Finally merge both checks and cast to pointer type. The inttoptr
712 // implicitly zexts the i1 to intptr type.
713 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
714 }
715
716 // Check if all arguments are constants. If so, we can constant fold.
717 if (!CharC)
718 return nullptr;
719
Benjamin Kramer691363e2015-03-21 15:36:21 +0000720 // Compute the offset.
721 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
722 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
723 return Constant::getNullValue(CI->getType());
724
725 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000726 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000727}
728
Chris Bienemanad070d02014-09-17 20:55:46 +0000729Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000730 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000731
Chris Bienemanad070d02014-09-17 20:55:46 +0000732 if (LHS == RHS) // memcmp(s,s,x) -> 0
733 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000734
Chris Bienemanad070d02014-09-17 20:55:46 +0000735 // Make sure we have a constant length.
736 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
737 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000738 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000739
Sanjay Patel70db4242017-06-09 14:22:03 +0000740 uint64_t Len = LenC->getZExtValue();
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 if (Len == 0) // memcmp(s1,s2,0) -> 0
742 return Constant::getNullValue(CI->getType());
743
744 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
745 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000746 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000747 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000748 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000749 CI->getType(), "rhsv");
750 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000751 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000752
Chad Rosierdc655322015-08-28 18:30:18 +0000753 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
754 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
Sanjay Patel707f7862017-08-21 15:16:25 +0000755
Chad Rosierdc655322015-08-28 18:30:18 +0000756 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
757 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
758
Sanjay Patel707f7862017-08-21 15:16:25 +0000759 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
760 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
Chad Rosierdc655322015-08-28 18:30:18 +0000761
762 Type *LHSPtrTy =
763 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
764 Type *RHSPtrTy =
765 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
Sanjay Patel7756edf2017-08-21 13:55:49 +0000766
Sanjay Patel707f7862017-08-21 15:16:25 +0000767 Value *LHSV =
768 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
769 Value *RHSV =
770 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
771
Sanjay Patel7756edf2017-08-21 13:55:49 +0000772 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
Sanjay Patel707f7862017-08-21 15:16:25 +0000773 }
Chad Rosierdc655322015-08-28 18:30:18 +0000774 }
775
Sanjay Patel707f7862017-08-21 15:16:25 +0000776 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Chris Bienemanad070d02014-09-17 20:55:46 +0000777 StringRef LHSStr, RHSStr;
778 if (getConstantStringInfo(LHS, LHSStr) &&
779 getConstantStringInfo(RHS, RHSStr)) {
780 // Make sure we're not reading out-of-bounds memory.
781 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000782 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000783 // Fold the memcmp and normalize the result. This way we get consistent
784 // results across multiple platforms.
785 uint64_t Ret = 0;
786 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
787 if (Cmp < 0)
788 Ret = -1;
789 else if (Cmp > 0)
790 Ret = 1;
791 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000792 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000793
Chris Bienemanad070d02014-09-17 20:55:46 +0000794 return nullptr;
795}
Meador Inge9a6a1902012-10-31 00:20:56 +0000796
Chris Bienemanad070d02014-09-17 20:55:46 +0000797Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000798 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
799 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000800 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000801 return CI->getArgOperand(0);
802}
Meador Inge05a625a2012-10-31 14:58:26 +0000803
Chris Bienemanad070d02014-09-17 20:55:46 +0000804Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000805 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
806 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000807 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000808 return CI->getArgOperand(0);
809}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000810
Sanjay Patel980b2802016-01-26 16:17:24 +0000811// TODO: Does this belong in BuildLibCalls or should all of those similar
812// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000813static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000814 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000815 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000816 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
817 return nullptr;
818
819 Module *M = B.GetInsertBlock()->getModule();
820 const DataLayout &DL = M->getDataLayout();
821 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
822 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000823 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000824 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
825
826 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
827 CI->setCallingConv(F->getCallingConv());
828
829 return CI;
830}
831
832/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
833static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
834 const TargetLibraryInfo &TLI) {
835 // This has to be a memset of zeros (bzero).
836 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
837 if (!FillValue || FillValue->getZExtValue() != 0)
838 return nullptr;
839
840 // TODO: We should handle the case where the malloc has more than one use.
841 // This is necessary to optimize common patterns such as when the result of
842 // the malloc is checked against null or when a memset intrinsic is used in
843 // place of a memset library call.
844 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
845 if (!Malloc || !Malloc->hasOneUse())
846 return nullptr;
847
848 // Is the inner call really malloc()?
849 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000850 if (!InnerCallee)
851 return nullptr;
852
David L. Jonesd21529f2017-01-23 23:16:46 +0000853 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000854 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000855 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000856 return nullptr;
857
Sanjay Patel980b2802016-01-26 16:17:24 +0000858 // The memset must cover the same number of bytes that are malloc'd.
859 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
860 return nullptr;
861
862 // Replace the malloc with a calloc. We need the data layout to know what the
863 // actual size of a 'size_t' parameter is.
864 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
865 const DataLayout &DL = Malloc->getModule()->getDataLayout();
866 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
867 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
868 Malloc->getArgOperand(0), Malloc->getAttributes(),
869 B, TLI);
870 if (!Calloc)
871 return nullptr;
872
873 Malloc->replaceAllUsesWith(Calloc);
874 Malloc->eraseFromParent();
875
876 return Calloc;
877}
878
Chris Bienemanad070d02014-09-17 20:55:46 +0000879Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000880 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
881 return Calloc;
882
Chris Bienemanad070d02014-09-17 20:55:46 +0000883 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
884 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
885 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
886 return CI->getArgOperand(0);
887}
Meador Inged4825782012-11-11 06:49:03 +0000888
Meador Inge193e0352012-11-13 04:16:17 +0000889//===----------------------------------------------------------------------===//
890// Math Library Optimizations
891//===----------------------------------------------------------------------===//
892
Matthias Braund34e4d22014-12-03 21:46:33 +0000893/// Return a variant of Val with float type.
894/// Currently this works in two cases: If Val is an FPExtension of a float
895/// value to something bigger, simply return the operand.
896/// If Val is a ConstantFP but can be converted to a float ConstantFP without
897/// loss of precision do so.
898static Value *valueHasFloatPrecision(Value *Val) {
899 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
900 Value *Op = Cast->getOperand(0);
901 if (Op->getType()->isFloatTy())
902 return Op;
903 }
904 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
905 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000906 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000907 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000908 &losesInfo);
909 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000910 return ConstantFP::get(Const->getContext(), F);
911 }
912 return nullptr;
913}
914
Sanjay Patel4e971da2016-01-21 18:01:57 +0000915/// Shrink double -> float for unary functions like 'floor'.
916static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
917 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000918 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000919 // We know this libcall has a valid prototype, but we don't know which.
920 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000921 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000922
Chris Bienemanad070d02014-09-17 20:55:46 +0000923 if (CheckRetType) {
924 // Check if all the uses for function like 'sin' are converted to float.
925 for (User *U : CI->users()) {
926 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
927 if (!Cast || !Cast->getType()->isFloatTy())
928 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000929 }
Meador Inge193e0352012-11-13 04:16:17 +0000930 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000931
932 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000933 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
934 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000935 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000936
Andrew Ng1606fc02017-04-25 12:36:14 +0000937 // If call isn't an intrinsic, check that it isn't within a function with the
938 // same name as the float version of this call.
939 //
940 // e.g. inline float expf(float val) { return (float) exp((double) val); }
941 //
942 // A similar such definition exists in the MinGW-w64 math.h header file which
943 // when compiled with -O2 -ffast-math causes the generation of infinite loops
944 // where expf is called.
945 if (!Callee->isIntrinsic()) {
946 const Function *F = CI->getFunction();
947 StringRef FName = F->getName();
948 StringRef CalleeName = Callee->getName();
949 if ((FName.size() == (CalleeName.size() + 1)) &&
950 (FName.back() == 'f') &&
951 FName.startswith(CalleeName))
952 return nullptr;
953 }
954
Sanjay Patelaa231142015-12-31 21:52:31 +0000955 // Propagate fast-math flags from the existing call to the new call.
956 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000957 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000958
959 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000960 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000961 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000962 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000963 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
964 V = B.CreateCall(F, V);
965 } else {
966 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000967 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000968 }
969
Chris Bienemanad070d02014-09-17 20:55:46 +0000970 return B.CreateFPExt(V, B.getDoubleTy());
971}
Meador Inge193e0352012-11-13 04:16:17 +0000972
Matt Arsenault954a6242017-01-23 23:55:08 +0000973// Replace a libcall \p CI with a call to intrinsic \p IID
974static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
975 // Propagate fast-math flags from the existing call to the new call.
976 IRBuilder<>::FastMathFlagGuard Guard(B);
977 B.setFastMathFlags(CI->getFastMathFlags());
978
979 Module *M = CI->getModule();
980 Value *V = CI->getArgOperand(0);
981 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
982 CallInst *NewCall = B.CreateCall(F, V);
983 NewCall->takeName(CI);
984 return NewCall;
985}
986
Sanjay Patel4e971da2016-01-21 18:01:57 +0000987/// Shrink double -> float for binary functions like 'fmin/fmax'.
988static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000989 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000990 // We know this libcall has a valid prototype, but we don't know which.
991 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000992 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000993
Chris Bienemanad070d02014-09-17 20:55:46 +0000994 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000995 // or fmin(1.0, (double)floatval), then we convert it to fminf.
996 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
997 if (V1 == nullptr)
998 return nullptr;
999 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1000 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001001 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001002
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001003 // Propagate fast-math flags from the existing call to the new call.
1004 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001005 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001006
Chris Bienemanad070d02014-09-17 20:55:46 +00001007 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001008 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001009 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001010 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001011 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001012 return B.CreateFPExt(V, B.getDoubleTy());
1013}
1014
1015Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1016 Function *Callee = CI->getCalledFunction();
1017 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001018 StringRef Name = Callee->getName();
1019 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001020 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001021
Chris Bienemanad070d02014-09-17 20:55:46 +00001022 // cos(-x) -> cos(x)
1023 Value *Op1 = CI->getArgOperand(0);
1024 if (BinaryOperator::isFNeg(Op1)) {
1025 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1026 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1027 }
1028 return Ret;
1029}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001030
Weiming Zhao82130722015-12-04 22:00:47 +00001031static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1032 // Multiplications calculated using Addition Chains.
1033 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1034
1035 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1036
1037 if (InnerChain[Exp])
1038 return InnerChain[Exp];
1039
1040 static const unsigned AddChain[33][2] = {
1041 {0, 0}, // Unused.
1042 {0, 0}, // Unused (base case = pow1).
1043 {1, 1}, // Unused (pre-computed).
1044 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1045 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1046 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1047 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1048 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1049 };
1050
1051 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1052 getPow(InnerChain, AddChain[Exp][1], B));
1053 return InnerChain[Exp];
1054}
1055
Chris Bienemanad070d02014-09-17 20:55:46 +00001056Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1057 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001058 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001059 StringRef Name = Callee->getName();
1060 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001061 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001062
Chris Bienemanad070d02014-09-17 20:55:46 +00001063 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001064
1065 // pow(1.0, x) -> 1.0
1066 if (match(Op1, m_SpecificFP(1.0)))
1067 return Op1;
1068 // pow(2.0, x) -> llvm.exp2(x)
1069 if (match(Op1, m_SpecificFP(2.0))) {
1070 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1071 CI->getType());
1072 return B.CreateCall(Exp2, Op2, "exp2");
1073 }
1074
1075 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1076 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001077 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001078 // pow(10.0, x) -> exp10(x)
1079 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001080 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1081 LibFunc_exp10l))
1082 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001083 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001084 }
1085
Sanjay Patel6002e782016-01-12 17:30:37 +00001086 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001087 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001088 // We enable these only with fast-math. Besides rounding differences, the
1089 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001090 // Example: x = 1000, y = 0.001.
1091 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001092 auto *OpC = dyn_cast<CallInst>(Op1);
1093 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001094 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001095 Function *OpCCallee = OpC->getCalledFunction();
1096 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001097 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001098 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001099 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001100 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001101 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001102 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001103 }
1104 }
1105
Chris Bienemanad070d02014-09-17 20:55:46 +00001106 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1107 if (!Op2C)
1108 return Ret;
1109
1110 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1111 return ConstantFP::get(CI->getType(), 1.0);
1112
Davide Italiano472684e2017-01-09 21:55:23 +00001113 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001114 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1115 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001116 // If -ffast-math:
1117 // pow(x, -0.5) -> 1.0 / sqrt(x)
1118 if (CI->hasUnsafeAlgebra()) {
1119 IRBuilder<>::FastMathFlagGuard Guard(B);
1120 B.setFastMathFlags(CI->getFastMathFlags());
1121
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001122 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1123 // intrinsic, so we match errno semantics. We also should check that the
1124 // target can in fact lower the sqrt intrinsic -- we currently have no way
1125 // to ask this question other than asking whether the target has a sqrt
1126 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001127 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001128 Callee->getAttributes());
1129
1130 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1131 }
1132 }
1133
Chris Bienemanad070d02014-09-17 20:55:46 +00001134 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001135 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1136 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001137
1138 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001139 if (CI->hasUnsafeAlgebra()) {
1140 IRBuilder<>::FastMathFlagGuard Guard(B);
1141 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001142
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001143 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1144 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001145 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001146 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001147 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001148
Chris Bienemanad070d02014-09-17 20:55:46 +00001149 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1150 // This is faster than calling pow, and still handles negative zero
1151 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001152 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1153 Value *Inf = ConstantFP::getInfinity(CI->getType());
1154 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001155
1156 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1157 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001158 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001159
1160 Module *M = Callee->getParent();
1161 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1162 CI->getType());
1163 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1164
Chris Bienemanad070d02014-09-17 20:55:46 +00001165 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1166 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1167 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001168 }
1169
Chris Bienemanad070d02014-09-17 20:55:46 +00001170 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1171 return Op1;
1172 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1173 return B.CreateFMul(Op1, Op1, "pow2");
1174 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1175 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001176
1177 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001178 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001179 APFloat V = abs(Op2C->getValueAPF());
1180 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1181 // This transformation applies to integer exponents only.
1182 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1183 !V.isInteger())
1184 return nullptr;
1185
Davide Italianof8711f02017-01-10 18:02:05 +00001186 // Propagate fast math flags.
1187 IRBuilder<>::FastMathFlagGuard Guard(B);
1188 B.setFastMathFlags(CI->getFastMathFlags());
1189
Weiming Zhao82130722015-12-04 22:00:47 +00001190 // We will memoize intermediate products of the Addition Chain.
1191 Value *InnerChain[33] = {nullptr};
1192 InnerChain[1] = Op1;
1193 InnerChain[2] = B.CreateFMul(Op1, Op1);
1194
1195 // We cannot readily convert a non-double type (like float) to a double.
1196 // So we first convert V to something which could be converted to double.
1197 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001198 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001199
Weiming Zhao82130722015-12-04 22:00:47 +00001200 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1201 // For negative exponents simply compute the reciprocal.
1202 if (Op2C->isNegative())
1203 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1204 return FMul;
1205 }
1206
Chris Bienemanad070d02014-09-17 20:55:46 +00001207 return nullptr;
1208}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001209
Chris Bienemanad070d02014-09-17 20:55:46 +00001210Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1211 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001212 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001213 StringRef Name = Callee->getName();
1214 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001215 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001216
Chris Bienemanad070d02014-09-17 20:55:46 +00001217 Value *Op = CI->getArgOperand(0);
1218 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1219 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001220 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001221 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001222 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001223 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001224 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001225
1226 if (TLI->has(LdExp)) {
1227 Value *LdExpArg = nullptr;
1228 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1229 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1230 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1231 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1232 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1233 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1234 }
1235
1236 if (LdExpArg) {
1237 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1238 if (!Op->getType()->isFloatTy())
1239 One = ConstantExpr::getFPExtend(One, Op->getType());
1240
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001241 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001242 Value *NewCallee =
1243 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001244 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001245 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001246 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1247 CI->setCallingConv(F->getCallingConv());
1248
1249 return CI;
1250 }
1251 }
1252 return Ret;
1253}
1254
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001255Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001256 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001257 // If we can shrink the call to a float function rather than a double
1258 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001259 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001260 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1261 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001262 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001263
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001264 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001265 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001266 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001267 // Unsafe algebra sets all fast-math-flags to true.
1268 FMF.setUnsafeAlgebra();
1269 } else {
1270 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001271 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001272 return nullptr;
1273 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1274 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001275 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001276 // might be impractical."
1277 FMF.setNoSignedZeros();
1278 FMF.setNoNaNs();
1279 }
Sanjay Patela2528152016-01-12 18:03:37 +00001280 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001281
1282 // We have a relaxed floating-point environment. We can ignore NaN-handling
1283 // and transform to a compare and select. We do not have to consider errno or
1284 // exceptions, because fmin/fmax do not have those.
1285 Value *Op0 = CI->getArgOperand(0);
1286 Value *Op1 = CI->getArgOperand(1);
1287 Value *Cmp = Callee->getName().startswith("fmin") ?
1288 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1289 return B.CreateSelect(Cmp, Op0, Op1);
1290}
1291
Davide Italianob8b71332015-11-29 20:58:04 +00001292Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1293 Function *Callee = CI->getCalledFunction();
1294 Value *Ret = nullptr;
1295 StringRef Name = Callee->getName();
1296 if (UnsafeFPShrink && hasFloatVersion(Name))
1297 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001298
Sanjay Patele896ede2016-01-11 23:31:48 +00001299 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001300 return Ret;
1301 Value *Op1 = CI->getArgOperand(0);
1302 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001303
1304 // The earlier call must also be unsafe in order to do these transforms.
1305 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001306 return Ret;
1307
1308 // log(pow(x,y)) -> y*log(x)
1309 // This is only applicable to log, log2, log10.
1310 if (Name != "log" && Name != "log2" && Name != "log10")
1311 return Ret;
1312
1313 IRBuilder<>::FastMathFlagGuard Guard(B);
1314 FastMathFlags FMF;
1315 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001316 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001317
David L. Jonesd21529f2017-01-23 23:16:46 +00001318 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001319 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001320 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001321 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001322 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001323 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001324 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001325
1326 // log(exp2(y)) -> y*log(2)
1327 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001328 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001329 return B.CreateFMul(
1330 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001331 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001332 Callee->getName(), B, Callee->getAttributes()),
1333 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001334 return Ret;
1335}
1336
Sanjay Patelc699a612014-10-16 18:48:17 +00001337Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1338 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001339 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001340 // TODO: Once we have a way (other than checking for the existince of the
1341 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1342 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001343 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001344 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001345 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001346
1347 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001348 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001349
Sanjay Patelc2d64612016-01-06 20:52:21 +00001350 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1351 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1352 return Ret;
1353
1354 // We're looking for a repeated factor in a multiplication tree,
1355 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001356 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001357 Value *Op0 = I->getOperand(0);
1358 Value *Op1 = I->getOperand(1);
1359 Value *RepeatOp = nullptr;
1360 Value *OtherOp = nullptr;
1361 if (Op0 == Op1) {
1362 // Simple match: the operands of the multiply are identical.
1363 RepeatOp = Op0;
1364 } else {
1365 // Look for a more complicated pattern: one of the operands is itself
1366 // a multiply, so search for a common factor in that multiply.
1367 // Note: We don't bother looking any deeper than this first level or for
1368 // variations of this pattern because instcombine's visitFMUL and/or the
1369 // reassociation pass should give us this form.
1370 Value *OtherMul0, *OtherMul1;
1371 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1372 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001373 if (OtherMul0 == OtherMul1 &&
1374 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001375 // Matched: sqrt((x * x) * z)
1376 RepeatOp = OtherMul0;
1377 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001378 }
1379 }
1380 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001381 if (!RepeatOp)
1382 return Ret;
1383
1384 // Fast math flags for any created instructions should match the sqrt
1385 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001386 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001387 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001388
Sanjay Patelc2d64612016-01-06 20:52:21 +00001389 // If we found a repeated factor, hoist it out of the square root and
1390 // replace it with the fabs of that factor.
1391 Module *M = Callee->getParent();
1392 Type *ArgType = I->getType();
1393 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1394 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1395 if (OtherOp) {
1396 // If we found a non-repeated factor, we still need to get its square
1397 // root. We then multiply that by the value that was simplified out
1398 // of the square root calculation.
1399 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1400 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1401 return B.CreateFMul(FabsCall, SqrtCall);
1402 }
1403 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001404}
1405
Sanjay Patelcddcd722016-01-06 19:23:35 +00001406// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001407Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1408 Function *Callee = CI->getCalledFunction();
1409 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001410 StringRef Name = Callee->getName();
1411 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001412 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001413
Davide Italiano51507d22015-11-04 23:36:56 +00001414 Value *Op1 = CI->getArgOperand(0);
1415 auto *OpC = dyn_cast<CallInst>(Op1);
1416 if (!OpC)
1417 return Ret;
1418
Sanjay Patelcddcd722016-01-06 19:23:35 +00001419 // Both calls must allow unsafe optimizations in order to remove them.
1420 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1421 return Ret;
1422
Davide Italiano51507d22015-11-04 23:36:56 +00001423 // tan(atan(x)) -> x
1424 // tanf(atanf(x)) -> x
1425 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001426 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001427 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001428 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001429 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1430 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1431 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001432 Ret = OpC->getArgOperand(0);
1433 return Ret;
1434}
1435
Sanjay Patel57747212016-01-21 23:38:43 +00001436static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001437 // We can only hope to do anything useful if we can ignore things like errno
1438 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001439 // We already checked the prototype.
1440 return CI->hasFnAttr(Attribute::NoUnwind) &&
1441 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001442}
1443
Chris Bienemanad070d02014-09-17 20:55:46 +00001444static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1445 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001446 Value *&SinCos) {
1447 Type *ArgTy = Arg->getType();
1448 Type *ResTy;
1449 StringRef Name;
1450
1451 Triple T(OrigCallee->getParent()->getTargetTriple());
1452 if (UseFloat) {
1453 Name = "__sincospif_stret";
1454
1455 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1456 // x86_64 can't use {float, float} since that would be returned in both
1457 // xmm0 and xmm1, which isn't what a real struct would do.
1458 ResTy = T.getArch() == Triple::x86_64
Serge Gueltone38003f2017-05-09 19:31:13 +00001459 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1460 : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
Sanjay Patel57747212016-01-21 23:38:43 +00001461 } else {
1462 Name = "__sincospi_stret";
Serge Gueltone38003f2017-05-09 19:31:13 +00001463 ResTy = StructType::get(ArgTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001464 }
1465
1466 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001467 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001468 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001469
1470 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1471 // If the argument is an instruction, it must dominate all uses so put our
1472 // sincos call there.
1473 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1474 } else {
1475 // Otherwise (e.g. for a constant) the beginning of the function is as
1476 // good a place as any.
1477 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1478 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1479 }
1480
1481 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1482
1483 if (SinCos->getType()->isStructTy()) {
1484 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1485 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1486 } else {
1487 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1488 "sinpi");
1489 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1490 "cospi");
1491 }
1492}
Chris Bienemanad070d02014-09-17 20:55:46 +00001493
1494Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001495 // Make sure the prototype is as expected, otherwise the rest of the
1496 // function is probably invalid and likely to abort.
1497 if (!isTrigLibCall(CI))
1498 return nullptr;
1499
1500 Value *Arg = CI->getArgOperand(0);
1501 SmallVector<CallInst *, 1> SinCalls;
1502 SmallVector<CallInst *, 1> CosCalls;
1503 SmallVector<CallInst *, 1> SinCosCalls;
1504
1505 bool IsFloat = Arg->getType()->isFloatTy();
1506
1507 // Look for all compatible sinpi, cospi and sincospi calls with the same
1508 // argument. If there are enough (in some sense) we can make the
1509 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001510 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001511 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001512 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001513
1514 // It's only worthwhile if both sinpi and cospi are actually used.
1515 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1516 return nullptr;
1517
1518 Value *Sin, *Cos, *SinCos;
1519 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1520
Davide Italianof024a562016-12-16 02:28:38 +00001521 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1522 Value *Res) {
1523 for (CallInst *C : Calls)
1524 replaceAllUsesWith(C, Res);
1525 };
1526
Chris Bienemanad070d02014-09-17 20:55:46 +00001527 replaceTrigInsts(SinCalls, Sin);
1528 replaceTrigInsts(CosCalls, Cos);
1529 replaceTrigInsts(SinCosCalls, SinCos);
1530
1531 return nullptr;
1532}
1533
David Majnemerabae6b52016-03-19 04:53:02 +00001534void LibCallSimplifier::classifyArgUse(
1535 Value *Val, Function *F, bool IsFloat,
1536 SmallVectorImpl<CallInst *> &SinCalls,
1537 SmallVectorImpl<CallInst *> &CosCalls,
1538 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001539 CallInst *CI = dyn_cast<CallInst>(Val);
1540
1541 if (!CI)
1542 return;
1543
David Majnemerabae6b52016-03-19 04:53:02 +00001544 // Don't consider calls in other functions.
1545 if (CI->getFunction() != F)
1546 return;
1547
Chris Bienemanad070d02014-09-17 20:55:46 +00001548 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001549 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001550 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001551 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001552 return;
1553
1554 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001555 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001556 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001557 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001558 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001559 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001560 SinCosCalls.push_back(CI);
1561 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001562 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001564 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001565 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001566 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001567 SinCosCalls.push_back(CI);
1568 }
1569}
1570
Meador Inge7415f842012-11-25 20:45:27 +00001571//===----------------------------------------------------------------------===//
1572// Integer Library Call Optimizations
1573//===----------------------------------------------------------------------===//
1574
Chris Bienemanad070d02014-09-17 20:55:46 +00001575Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001576 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001577 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001578 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001579 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1580 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001581 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001582 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1583 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001584
Chris Bienemanad070d02014-09-17 20:55:46 +00001585 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1586 return B.CreateSelect(Cond, V, B.getInt32(0));
1587}
Meador Ingea0b6d872012-11-26 00:24:07 +00001588
Davide Italiano85ad36b2016-12-15 23:45:11 +00001589Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1590 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1591 Value *Op = CI->getArgOperand(0);
1592 Type *ArgType = Op->getType();
1593 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1594 Intrinsic::ctlz, ArgType);
1595 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1596 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1597 V);
1598 return B.CreateIntCast(V, CI->getType(), false);
1599}
1600
Chris Bienemanad070d02014-09-17 20:55:46 +00001601Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001602 // abs(x) -> x >s -1 ? x : -x
1603 Value *Op = CI->getArgOperand(0);
1604 Value *Pos =
1605 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1606 Value *Neg = B.CreateNeg(Op, "neg");
1607 return B.CreateSelect(Pos, Op, Neg);
1608}
Meador Inge9a59ab62012-11-26 02:31:59 +00001609
Chris Bienemanad070d02014-09-17 20:55:46 +00001610Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001611 // isdigit(c) -> (c-'0') <u 10
1612 Value *Op = CI->getArgOperand(0);
1613 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1614 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1615 return B.CreateZExt(Op, CI->getType());
1616}
Meador Ingea62a39e2012-11-26 03:10:07 +00001617
Chris Bienemanad070d02014-09-17 20:55:46 +00001618Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001619 // isascii(c) -> c <u 128
1620 Value *Op = CI->getArgOperand(0);
1621 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1622 return B.CreateZExt(Op, CI->getType());
1623}
1624
1625Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001626 // toascii(c) -> c & 0x7f
1627 return B.CreateAnd(CI->getArgOperand(0),
1628 ConstantInt::get(CI->getType(), 0x7F));
1629}
Meador Inge604937d2012-11-26 03:38:52 +00001630
Meador Inge08ca1152012-11-26 20:37:20 +00001631//===----------------------------------------------------------------------===//
1632// Formatting and IO Library Call Optimizations
1633//===----------------------------------------------------------------------===//
1634
Chris Bienemanad070d02014-09-17 20:55:46 +00001635static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001636
Chris Bienemanad070d02014-09-17 20:55:46 +00001637Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1638 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001639 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001640 // Error reporting calls should be cold, mark them as such.
1641 // This applies even to non-builtin calls: it is only a hint and applies to
1642 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001643
Chris Bienemanad070d02014-09-17 20:55:46 +00001644 // This heuristic was suggested in:
1645 // Improving Static Branch Prediction in a Compiler
1646 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1647 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 if (!CI->hasFnAttr(Attribute::Cold) &&
1649 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001650 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001651 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001652
Chris Bienemanad070d02014-09-17 20:55:46 +00001653 return nullptr;
1654}
1655
1656static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001657 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001658 return false;
1659
1660 if (StreamArg < 0)
1661 return true;
1662
1663 // These functions might be considered cold, but only if their stream
1664 // argument is stderr.
1665
1666 if (StreamArg >= (int)CI->getNumArgOperands())
1667 return false;
1668 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1669 if (!LI)
1670 return false;
1671 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1672 if (!GV || !GV->isDeclaration())
1673 return false;
1674 return GV->getName() == "stderr";
1675}
1676
1677Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1678 // Check for a fixed format string.
1679 StringRef FormatStr;
1680 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001681 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001682
Chris Bienemanad070d02014-09-17 20:55:46 +00001683 // Empty format string -> noop.
1684 if (FormatStr.empty()) // Tolerate printf's declared void.
1685 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001686
Chris Bienemanad070d02014-09-17 20:55:46 +00001687 // Do not do any of the following transformations if the printf return value
1688 // is used, in general the printf return value is not compatible with either
1689 // putchar() or puts().
1690 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001691 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001692
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001693 // printf("x") -> putchar('x'), even for "%" and "%%".
1694 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001695 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001696
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001697 // printf("%s", "a") --> putchar('a')
1698 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1699 StringRef ChrStr;
1700 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1701 return nullptr;
1702 if (ChrStr.size() != 1)
1703 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001704 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001705 }
1706
Chris Bienemanad070d02014-09-17 20:55:46 +00001707 // printf("foo\n") --> puts("foo")
1708 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1709 FormatStr.find('%') == StringRef::npos) { // No format characters.
1710 // Create a string literal with no \n on it. We expect the constant merge
1711 // pass to be run after this pass, to merge duplicate strings.
1712 FormatStr = FormatStr.drop_back();
1713 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001714 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001715 }
Meador Inge08ca1152012-11-26 20:37:20 +00001716
Chris Bienemanad070d02014-09-17 20:55:46 +00001717 // Optimize specific format strings.
1718 // printf("%c", chr) --> putchar(chr)
1719 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001720 CI->getArgOperand(1)->getType()->isIntegerTy())
1721 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001722
1723 // printf("%s\n", str) --> puts(str)
1724 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001725 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001726 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001727 return nullptr;
1728}
1729
1730Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1731
1732 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001733 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001734 if (Value *V = optimizePrintFString(CI, B)) {
1735 return V;
1736 }
1737
1738 // printf(format, ...) -> iprintf(format, ...) if no floating point
1739 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001740 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001741 Module *M = B.GetInsertBlock()->getParent()->getParent();
1742 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001743 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001744 CallInst *New = cast<CallInst>(CI->clone());
1745 New->setCalledFunction(IPrintFFn);
1746 B.Insert(New);
1747 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001748 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001749 return nullptr;
1750}
Meador Inge08ca1152012-11-26 20:37:20 +00001751
Chris Bienemanad070d02014-09-17 20:55:46 +00001752Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1753 // Check for a fixed format string.
1754 StringRef FormatStr;
1755 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001756 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001757
Chris Bienemanad070d02014-09-17 20:55:46 +00001758 // If we just have a format string (nothing else crazy) transform it.
1759 if (CI->getNumArgOperands() == 2) {
1760 // Make sure there's no % in the constant array. We could try to handle
1761 // %% -> % in the future if we cared.
1762 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1763 if (FormatStr[i] == '%')
1764 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001765
Chris Bienemanad070d02014-09-17 20:55:46 +00001766 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001767 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1768 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1769 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001770 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001771 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001772 }
Meador Ingef8e72502012-11-29 15:45:43 +00001773
Chris Bienemanad070d02014-09-17 20:55:46 +00001774 // The remaining optimizations require the format string to be "%s" or "%c"
1775 // and have an extra operand.
1776 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1777 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001778 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001779
Chris Bienemanad070d02014-09-17 20:55:46 +00001780 // Decode the second character of the format string.
1781 if (FormatStr[1] == 'c') {
1782 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1783 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1784 return nullptr;
1785 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001786 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001787 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001788 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001790
Chris Bienemanad070d02014-09-17 20:55:46 +00001791 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001792 }
1793
Chris Bienemanad070d02014-09-17 20:55:46 +00001794 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001795 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1796 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1797 return nullptr;
1798
Sanjay Pateld3112a52016-01-19 19:46:10 +00001799 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 if (!Len)
1801 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001802 Value *IncLen =
1803 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1804 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001805
1806 // The sprintf result is the unincremented number of bytes in the string.
1807 return B.CreateIntCast(Len, CI->getType(), false);
1808 }
1809 return nullptr;
1810}
1811
1812Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1813 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001815 if (Value *V = optimizeSPrintFString(CI, B)) {
1816 return V;
1817 }
1818
1819 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1820 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001821 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001822 Module *M = B.GetInsertBlock()->getParent()->getParent();
1823 Constant *SIPrintFFn =
1824 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1825 CallInst *New = cast<CallInst>(CI->clone());
1826 New->setCalledFunction(SIPrintFFn);
1827 B.Insert(New);
1828 return New;
1829 }
1830 return nullptr;
1831}
1832
1833Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1834 optimizeErrorReporting(CI, B, 0);
1835
1836 // All the optimizations depend on the format string.
1837 StringRef FormatStr;
1838 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1839 return nullptr;
1840
1841 // Do not do any of the following transformations if the fprintf return
1842 // value is used, in general the fprintf return value is not compatible
1843 // with fwrite(), fputc() or fputs().
1844 if (!CI->use_empty())
1845 return nullptr;
1846
1847 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1848 if (CI->getNumArgOperands() == 2) {
1849 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1850 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1851 return nullptr; // We found a format specifier.
1852
Sanjay Pateld3112a52016-01-19 19:46:10 +00001853 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001854 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001855 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001856 CI->getArgOperand(0), B, DL, TLI);
1857 }
1858
1859 // The remaining optimizations require the format string to be "%s" or "%c"
1860 // and have an extra operand.
1861 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1862 CI->getNumArgOperands() < 3)
1863 return nullptr;
1864
1865 // Decode the second character of the format string.
1866 if (FormatStr[1] == 'c') {
1867 // fprintf(F, "%c", chr) --> fputc(chr, F)
1868 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1869 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001870 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001871 }
1872
1873 if (FormatStr[1] == 's') {
1874 // fprintf(F, "%s", str) --> fputs(str, F)
1875 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1876 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001877 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001878 }
1879 return nullptr;
1880}
1881
1882Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1883 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001884 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001885 if (Value *V = optimizeFPrintFString(CI, B)) {
1886 return V;
1887 }
1888
1889 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1890 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001891 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001892 Module *M = B.GetInsertBlock()->getParent()->getParent();
1893 Constant *FIPrintFFn =
1894 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1895 CallInst *New = cast<CallInst>(CI->clone());
1896 New->setCalledFunction(FIPrintFFn);
1897 B.Insert(New);
1898 return New;
1899 }
1900 return nullptr;
1901}
1902
1903Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1904 optimizeErrorReporting(CI, B, 3);
1905
Chris Bienemanad070d02014-09-17 20:55:46 +00001906 // Get the element size and count.
1907 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1908 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1909 if (!SizeC || !CountC)
1910 return nullptr;
1911 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1912
1913 // If this is writing zero records, remove the call (it's a noop).
1914 if (Bytes == 0)
1915 return ConstantInt::get(CI->getType(), 0);
1916
1917 // If this is writing one byte, turn it into fputc.
1918 // This optimisation is only valid, if the return value is unused.
1919 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001920 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1921 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001922 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1923 }
1924
1925 return nullptr;
1926}
1927
1928Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1929 optimizeErrorReporting(CI, B, 1);
1930
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001931 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1932 // requires more arguments and thus extra MOVs are required.
1933 if (CI->getParent()->getParent()->optForSize())
1934 return nullptr;
1935
Ahmed Bougachad765a822016-04-27 19:04:35 +00001936 // We can't optimize if return value is used.
1937 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001938 return nullptr;
1939
1940 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1941 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1942 if (!Len)
1943 return nullptr;
1944
1945 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001946 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001947 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001948 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001949 CI->getArgOperand(1), B, DL, TLI);
1950}
1951
1952Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001953 // Check for a constant string.
1954 StringRef Str;
1955 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1956 return nullptr;
1957
1958 if (Str.empty() && CI->use_empty()) {
1959 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001960 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001961 if (CI->use_empty() || !Res)
1962 return Res;
1963 return B.CreateIntCast(Res, CI->getType(), true);
1964 }
1965
1966 return nullptr;
1967}
1968
1969bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001970 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001971 SmallString<20> FloatFuncName = FuncName;
1972 FloatFuncName += 'f';
1973 if (TLI->getLibFunc(FloatFuncName, Func))
1974 return TLI->has(Func);
1975 return false;
1976}
Meador Inge7fb2f732012-10-13 16:45:32 +00001977
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001978Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1979 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001980 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001981 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001982 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001983 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001984 // Make sure we never change the calling convention.
1985 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001986 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001987 "Optimizing string/memory libcall would change the calling convention");
1988 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001989 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001990 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001991 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001992 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001993 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001994 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001995 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001996 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001997 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002001 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002003 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002004 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002005 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002006 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002007 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002008 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002009 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002010 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002011 case LibFunc_strtol:
2012 case LibFunc_strtod:
2013 case LibFunc_strtof:
2014 case LibFunc_strtoul:
2015 case LibFunc_strtoll:
2016 case LibFunc_strtold:
2017 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002018 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002019 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002020 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002021 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002022 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002024 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002025 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002026 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002027 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002028 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002029 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002030 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002031 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002032 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002033 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002034 return optimizeMemSet(CI, Builder);
Matthias Braun50ec0b52017-05-19 22:37:09 +00002035 case LibFunc_wcslen:
2036 return optimizeWcslen(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002037 default:
2038 break;
2039 }
2040 }
2041 return nullptr;
2042}
2043
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002044Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
2045 LibFunc Func,
2046 IRBuilder<> &Builder) {
2047 // Don't optimize calls that require strict floating point semantics.
2048 if (CI->isStrictFP())
2049 return nullptr;
2050
2051 switch (Func) {
2052 case LibFunc_cosf:
2053 case LibFunc_cos:
2054 case LibFunc_cosl:
2055 return optimizeCos(CI, Builder);
2056 case LibFunc_sinpif:
2057 case LibFunc_sinpi:
2058 case LibFunc_cospif:
2059 case LibFunc_cospi:
2060 return optimizeSinCosPi(CI, Builder);
2061 case LibFunc_powf:
2062 case LibFunc_pow:
2063 case LibFunc_powl:
2064 return optimizePow(CI, Builder);
2065 case LibFunc_exp2l:
2066 case LibFunc_exp2:
2067 case LibFunc_exp2f:
2068 return optimizeExp2(CI, Builder);
2069 case LibFunc_fabsf:
2070 case LibFunc_fabs:
2071 case LibFunc_fabsl:
2072 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
2073 case LibFunc_sqrtf:
2074 case LibFunc_sqrt:
2075 case LibFunc_sqrtl:
2076 return optimizeSqrt(CI, Builder);
2077 case LibFunc_log:
2078 case LibFunc_log10:
2079 case LibFunc_log1p:
2080 case LibFunc_log2:
2081 case LibFunc_logb:
2082 return optimizeLog(CI, Builder);
2083 case LibFunc_tan:
2084 case LibFunc_tanf:
2085 case LibFunc_tanl:
2086 return optimizeTan(CI, Builder);
2087 case LibFunc_ceil:
2088 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
2089 case LibFunc_floor:
2090 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
2091 case LibFunc_round:
2092 return replaceUnaryCall(CI, Builder, Intrinsic::round);
2093 case LibFunc_nearbyint:
2094 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
2095 case LibFunc_rint:
2096 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
2097 case LibFunc_trunc:
2098 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
2099 case LibFunc_acos:
2100 case LibFunc_acosh:
2101 case LibFunc_asin:
2102 case LibFunc_asinh:
2103 case LibFunc_atan:
2104 case LibFunc_atanh:
2105 case LibFunc_cbrt:
2106 case LibFunc_cosh:
2107 case LibFunc_exp:
2108 case LibFunc_exp10:
2109 case LibFunc_expm1:
2110 case LibFunc_sin:
2111 case LibFunc_sinh:
2112 case LibFunc_tanh:
2113 if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
2114 return optimizeUnaryDoubleFP(CI, Builder, true);
2115 return nullptr;
2116 case LibFunc_copysign:
2117 if (hasFloatVersion(CI->getCalledFunction()->getName()))
2118 return optimizeBinaryDoubleFP(CI, Builder);
2119 return nullptr;
2120 case LibFunc_fminf:
2121 case LibFunc_fmin:
2122 case LibFunc_fminl:
2123 case LibFunc_fmaxf:
2124 case LibFunc_fmax:
2125 case LibFunc_fmaxl:
2126 return optimizeFMinFMax(CI, Builder);
2127 default:
2128 return nullptr;
2129 }
2130}
2131
Chris Bienemanad070d02014-09-17 20:55:46 +00002132Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002133 // TODO: Split out the code below that operates on FP calls so that
2134 // we can all non-FP calls with the StrictFP attribute to be
2135 // optimized.
Chris Bienemanad070d02014-09-17 20:55:46 +00002136 if (CI->isNoBuiltin())
2137 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002138
David L. Jonesd21529f2017-01-23 23:16:46 +00002139 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002140 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002141
2142 SmallVector<OperandBundleDef, 2> OpBundles;
2143 CI->getOperandBundlesAsDefs(OpBundles);
2144 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002145 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002146
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002147 // Command-line parameter overrides instruction attribute.
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002148 // This can't be moved to optimizeFloatingPointLibCall() because it may be
2149 // used by the intrinsic optimizations.
Sanjay Patela92fa442014-10-22 15:29:23 +00002150 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2151 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002152 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002153 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002154
Sanjay Patel848309d2014-10-23 21:52:45 +00002155 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002156 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002157 if (!isCallingConvC)
2158 return nullptr;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002159 // The FP intrinsics have corresponding constrained versions so we don't
2160 // need to check for the StrictFP attribute here.
Meador Inge20255ef2013-03-12 00:08:29 +00002161 switch (II->getIntrinsicID()) {
2162 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002163 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002164 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002165 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002166 case Intrinsic::log:
2167 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002168 case Intrinsic::sqrt:
2169 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002170 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002171 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002172 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002173 }
2174 }
2175
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002176 // Also try to simplify calls to fortified library functions.
2177 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2178 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002179 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002180 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2181 // Use an IR Builder from SimplifiedCI if available instead of CI
2182 // to guarantee we reach all uses we might replace later on.
2183 IRBuilder<> TmpBuilder(SimplifiedCI);
2184 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002185 // If we were able to further simplify, remove the now redundant call.
2186 SimplifiedCI->replaceAllUsesWith(V);
2187 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002188 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002189 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002190 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002191 return SimplifiedFortifiedCI;
2192 }
2193
Meador Inge20255ef2013-03-12 00:08:29 +00002194 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002195 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002196 // We never change the calling convention.
2197 if (!ignoreCallingConv(Func) && !isCallingConvC)
2198 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002199 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2200 return V;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002201 if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
2202 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002203 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002204 case LibFunc_ffs:
2205 case LibFunc_ffsl:
2206 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002207 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002208 case LibFunc_fls:
2209 case LibFunc_flsl:
2210 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002211 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002212 case LibFunc_abs:
2213 case LibFunc_labs:
2214 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002215 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002216 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002217 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002218 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002219 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002220 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002221 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002222 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002223 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002224 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002225 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002226 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002227 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002228 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002229 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002230 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002231 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002232 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002233 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002234 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002235 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002236 case LibFunc_vfprintf:
2237 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002238 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002239 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002240 return optimizeErrorReporting(CI, Builder, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00002241 default:
2242 return nullptr;
2243 }
Meador Inge20255ef2013-03-12 00:08:29 +00002244 }
Craig Topperf40110f2014-04-25 05:29:35 +00002245 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002246}
2247
Chandler Carruth92803822015-01-21 02:11:59 +00002248LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002249 const DataLayout &DL, const TargetLibraryInfo *TLI,
Adam Nemetea06e6e2017-07-26 19:03:18 +00002250 OptimizationRemarkEmitter &ORE,
Chandler Carruth92803822015-01-21 02:11:59 +00002251 function_ref<void(Instruction *, Value *)> Replacer)
Adam Nemetea06e6e2017-07-26 19:03:18 +00002252 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
2253 UnsafeFPShrink(false), Replacer(Replacer) {}
Chandler Carruth92803822015-01-21 02:11:59 +00002254
2255void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2256 // Indirect through the replacer used in this instance.
2257 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002258}
2259
Meador Ingedfb08a22013-06-20 19:48:07 +00002260// TODO:
2261// Additional cases that we need to add to this file:
2262//
2263// cbrt:
2264// * cbrt(expN(X)) -> expN(x/3)
2265// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002266// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002267//
2268// exp, expf, expl:
2269// * exp(log(x)) -> x
2270//
2271// log, logf, logl:
2272// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002273// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002274// * log(exp10(y)) -> y*log(10)
2275// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002276//
Meador Ingedfb08a22013-06-20 19:48:07 +00002277// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002278// * pow(sqrt(x),y) -> pow(x,y*0.5)
2279// * pow(pow(x,y),z)-> pow(x,y*z)
2280//
Meador Ingedfb08a22013-06-20 19:48:07 +00002281// signbit:
2282// * signbit(cnst) -> cnst'
2283// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2284//
2285// sqrt, sqrtf, sqrtl:
2286// * sqrt(expN(x)) -> expN(x*0.5)
2287// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2288// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2289//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002290
2291//===----------------------------------------------------------------------===//
2292// Fortified Library Call Optimizations
2293//===----------------------------------------------------------------------===//
2294
2295bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2296 unsigned ObjSizeOp,
2297 unsigned SizeOp,
2298 bool isString) {
2299 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2300 return true;
2301 if (ConstantInt *ObjSizeCI =
2302 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
Craig Topper79ab6432017-07-06 18:39:47 +00002303 if (ObjSizeCI->isMinusOne())
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002304 return true;
2305 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2306 if (OnlyLowerUnknownSize)
2307 return false;
2308 if (isString) {
2309 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2310 // If the length is 0 we don't know how long it is and so we can't
2311 // remove the check.
2312 if (Len == 0)
2313 return false;
2314 return ObjSizeCI->getZExtValue() >= Len;
2315 }
2316 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2317 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2318 }
2319 return false;
2320}
2321
Sanjay Pateld707db92015-12-31 16:10:49 +00002322Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2323 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002324 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2325 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002326 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002327 return CI->getArgOperand(0);
2328 }
2329 return nullptr;
2330}
2331
Sanjay Pateld707db92015-12-31 16:10:49 +00002332Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2333 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002334 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2335 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002336 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002337 return CI->getArgOperand(0);
2338 }
2339 return nullptr;
2340}
2341
Sanjay Pateld707db92015-12-31 16:10:49 +00002342Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2343 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002344 // TODO: Try foldMallocMemset() here.
2345
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002346 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2347 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2348 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2349 return CI->getArgOperand(0);
2350 }
2351 return nullptr;
2352}
2353
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002354Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2355 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002356 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002357 Function *Callee = CI->getCalledFunction();
2358 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002359 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002360 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2361 *ObjSize = CI->getArgOperand(2);
2362
2363 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002364 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002365 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002366 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002367 }
2368
2369 // If a) we don't have any length information, or b) we know this will
2370 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2371 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2372 // TODO: It might be nice to get a maximum length out of the possible
2373 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002374 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002375 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002376
David Blaikie65fab6d2015-04-03 21:32:06 +00002377 if (OnlyLowerUnknownSize)
2378 return nullptr;
2379
2380 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2381 uint64_t Len = GetStringLength(Src);
2382 if (Len == 0)
2383 return nullptr;
2384
2385 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2386 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002387 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002388 // If the function was an __stpcpy_chk, and we were able to fold it into
2389 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002390 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002391 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2392 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002393}
2394
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002395Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2396 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002397 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002398 Function *Callee = CI->getCalledFunction();
2399 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002401 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002402 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002403 return Ret;
2404 }
2405 return nullptr;
2406}
2407
2408Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002409 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2410 // Some clang users checked for _chk libcall availability using:
2411 // __has_builtin(__builtin___memcpy_chk)
2412 // When compiling with -fno-builtin, this is always true.
2413 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2414 // end up with fortified libcalls, which isn't acceptable in a freestanding
2415 // environment which only provides their non-fortified counterparts.
2416 //
2417 // Until we change clang and/or teach external users to check for availability
2418 // differently, disregard the "nobuiltin" attribute and TLI::has.
2419 //
2420 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002421
David L. Jonesd21529f2017-01-23 23:16:46 +00002422 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002423 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002424
2425 SmallVector<OperandBundleDef, 2> OpBundles;
2426 CI->getOperandBundlesAsDefs(OpBundles);
2427 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002428 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002429
Ahmed Bougachad765a822016-04-27 19:04:35 +00002430 // First, check that this is a known library functions and that the prototype
2431 // is correct.
2432 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002433 return nullptr;
2434
2435 // We never change the calling convention.
2436 if (!ignoreCallingConv(Func) && !isCallingConvC)
2437 return nullptr;
2438
2439 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002440 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002441 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002442 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002443 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002444 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002445 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002446 case LibFunc_stpcpy_chk:
2447 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002448 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002449 case LibFunc_stpncpy_chk:
2450 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002451 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002452 default:
2453 break;
2454 }
2455 return nullptr;
2456}
2457
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002458FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2459 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2460 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}