blob: 9e71d746de34966798a849b456f95ff252a43c6d [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"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Meador Ingedf796f82012-10-13 16:45:24 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000024#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#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 only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000089static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000090 for (User *U : V->users()) {
91 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000092 if (IC->isEquality())
93 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
94 if (C->isNullValue())
95 continue;
96 // Unknown instruction.
97 return false;
98 }
99 return true;
100}
101
Sanjay Pateld707db92015-12-31 16:10:49 +0000102/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +0000103static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000104 for (User *U : V->users()) {
105 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +0000106 if (IC->isEquality() && IC->getOperand(1) == With)
107 continue;
108 // Unknown instruction.
109 return false;
110 }
111 return true;
112}
113
Meador Inge08ca1152012-11-26 20:37:20 +0000114static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +0000115 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +0000116 return OI->getType()->isFloatingPointTy();
117 });
Meador Inge08ca1152012-11-26 20:37:20 +0000118}
119
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000120/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +0000121/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000122static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
David L. Jonesd21529f2017-01-23 23:16:46 +0000123 LibFunc DoubleFn, LibFunc FloatFn,
124 LibFunc LongDoubleFn) {
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000125 switch (Ty->getTypeID()) {
126 case Type::FloatTyID:
127 return TLI->has(FloatFn);
128 case Type::DoubleTyID:
129 return TLI->has(DoubleFn);
130 default:
131 return TLI->has(LongDoubleFn);
132 }
133}
134
Meador Inged589ac62012-10-31 03:33:06 +0000135//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000136// String and Memory Library Call Optimizations
137//===----------------------------------------------------------------------===//
138
Chris Bienemanad070d02014-09-17 20:55:46 +0000139Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000140 // Extract some information from the instruction
141 Value *Dst = CI->getArgOperand(0);
142 Value *Src = CI->getArgOperand(1);
143
144 // See if we can get the length of the input string.
145 uint64_t Len = GetStringLength(Src);
146 if (Len == 0)
147 return nullptr;
148 --Len; // Unbias length.
149
150 // Handle the simple, do-nothing case: strcat(x, "") -> x
151 if (Len == 0)
152 return Dst;
153
Chris Bienemanad070d02014-09-17 20:55:46 +0000154 return emitStrLenMemCpy(Src, Dst, Len, B);
155}
156
157Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
158 IRBuilder<> &B) {
159 // We need to find the end of the destination string. That's where the
160 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000161 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000162 if (!DstLen)
163 return nullptr;
164
165 // Now that we have the destination's length, we must index into the
166 // destination's pointer to get the actual memcpy destination (end of
167 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000168 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000169
170 // We have enough information to now generate the memcpy call to do the
171 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000172 B.CreateMemCpy(CpyDst, Src,
173 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000174 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000175 return Dst;
176}
177
178Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000179 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000180 Value *Dst = CI->getArgOperand(0);
181 Value *Src = CI->getArgOperand(1);
182 uint64_t Len;
183
Sanjay Pateld707db92015-12-31 16:10:49 +0000184 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000185 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
186 Len = LengthArg->getZExtValue();
187 else
188 return nullptr;
189
190 // See if we can get the length of the input string.
191 uint64_t SrcLen = GetStringLength(Src);
192 if (SrcLen == 0)
193 return nullptr;
194 --SrcLen; // Unbias length.
195
196 // Handle the simple, do-nothing cases:
197 // strncat(x, "", c) -> x
198 // strncat(x, c, 0) -> x
199 if (SrcLen == 0 || Len == 0)
200 return Dst;
201
Sanjay Pateld707db92015-12-31 16:10:49 +0000202 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000203 if (Len < SrcLen)
204 return nullptr;
205
206 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000207 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000208 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
209}
210
211Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
212 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000213 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000214 Value *SrcStr = CI->getArgOperand(0);
215
216 // If the second operand is non-constant, see if we can compute the length
217 // of the input string and turn this into memchr.
218 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
219 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000220 uint64_t Len = GetStringLength(SrcStr);
221 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
222 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000223
Sanjay Pateld3112a52016-01-19 19:46:10 +0000224 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000225 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
226 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000227 }
228
Chris Bienemanad070d02014-09-17 20:55:46 +0000229 // Otherwise, the character is a constant, see if the first argument is
230 // a string literal. If so, we can constant fold.
231 StringRef Str;
232 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000234 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000235 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000236 return nullptr;
237 }
238
239 // Compute the offset, make sure to handle the case when we're searching for
240 // zero (a weird way to spell strlen).
241 size_t I = (0xFF & CharC->getSExtValue()) == 0
242 ? Str.size()
243 : Str.find(CharC->getSExtValue());
244 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
245 return Constant::getNullValue(CI->getType());
246
247 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000248 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000249}
250
251Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000252 Value *SrcStr = CI->getArgOperand(0);
253 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
254
255 // Cannot fold anything if we're not looking for a constant.
256 if (!CharC)
257 return nullptr;
258
259 StringRef Str;
260 if (!getConstantStringInfo(SrcStr, Str)) {
261 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000262 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000263 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000264 return nullptr;
265 }
266
267 // Compute the offset.
268 size_t I = (0xFF & CharC->getSExtValue()) == 0
269 ? Str.size()
270 : Str.rfind(CharC->getSExtValue());
271 if (I == StringRef::npos) // Didn't find the char. Return null.
272 return Constant::getNullValue(CI->getType());
273
274 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000275 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000276}
277
278Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000279 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
280 if (Str1P == Str2P) // strcmp(x,x) -> 0
281 return ConstantInt::get(CI->getType(), 0);
282
283 StringRef Str1, Str2;
284 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
285 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
286
287 // strcmp(x, y) -> cnst (if both x and y are constant strings)
288 if (HasStr1 && HasStr2)
289 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
290
291 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
292 return B.CreateNeg(
293 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
294
295 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
296 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
297
298 // strcmp(P, "x") -> memcmp(P, "x", 2)
299 uint64_t Len1 = GetStringLength(Str1P);
300 uint64_t Len2 = GetStringLength(Str2P);
301 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000302 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000303 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000304 std::min(Len1, Len2)),
305 B, DL, TLI);
306 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000307
Chris Bienemanad070d02014-09-17 20:55:46 +0000308 return nullptr;
309}
310
311Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000312 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
313 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
314 return ConstantInt::get(CI->getType(), 0);
315
316 // Get the length argument if it is constant.
317 uint64_t Length;
318 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
319 Length = LengthArg->getZExtValue();
320 else
321 return nullptr;
322
323 if (Length == 0) // strncmp(x,y,0) -> 0
324 return ConstantInt::get(CI->getType(), 0);
325
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000326 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000327 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000328
329 StringRef Str1, Str2;
330 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
331 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
332
333 // strncmp(x, y) -> cnst (if both x and y are constant strings)
334 if (HasStr1 && HasStr2) {
335 StringRef SubStr1 = Str1.substr(0, Length);
336 StringRef SubStr2 = Str2.substr(0, Length);
337 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
338 }
339
340 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
341 return B.CreateNeg(
342 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
343
344 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
345 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
346
347 return nullptr;
348}
349
350Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000351 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
352 if (Dst == Src) // strcpy(x,x) -> x
353 return Src;
354
Chris Bienemanad070d02014-09-17 20:55:46 +0000355 // See if we can get the length of the input string.
356 uint64_t Len = GetStringLength(Src);
357 if (Len == 0)
358 return nullptr;
359
360 // We have enough information to now generate the memcpy call to do the
361 // copy for us. Make a memcpy to copy the nul byte with align = 1.
362 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000363 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000364 return Dst;
365}
366
367Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
368 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000369 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
370 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000371 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000372 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000373 }
374
375 // See if we can get the length of the input string.
376 uint64_t Len = GetStringLength(Src);
377 if (Len == 0)
378 return nullptr;
379
Davide Italianob7487e62015-11-02 23:07:14 +0000380 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000381 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000382 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
383 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000384
385 // We have enough information to now generate the memcpy call to do the
386 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000387 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000388 return DstEnd;
389}
390
391Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
392 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000393 Value *Dst = CI->getArgOperand(0);
394 Value *Src = CI->getArgOperand(1);
395 Value *LenOp = CI->getArgOperand(2);
396
397 // See if we can get the length of the input string.
398 uint64_t SrcLen = GetStringLength(Src);
399 if (SrcLen == 0)
400 return nullptr;
401 --SrcLen;
402
403 if (SrcLen == 0) {
404 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
405 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000406 return Dst;
407 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000408
Chris Bienemanad070d02014-09-17 20:55:46 +0000409 uint64_t Len;
410 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
411 Len = LengthArg->getZExtValue();
412 else
413 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000414
Chris Bienemanad070d02014-09-17 20:55:46 +0000415 if (Len == 0)
416 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000417
Chris Bienemanad070d02014-09-17 20:55:46 +0000418 // Let strncpy handle the zero padding
419 if (Len > SrcLen + 1)
420 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000421
Davide Italianob7487e62015-11-02 23:07:14 +0000422 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000423 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000424 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000425
Chris Bienemanad070d02014-09-17 20:55:46 +0000426 return Dst;
427}
Meador Inge7fb2f732012-10-13 16:45:32 +0000428
Chris Bienemanad070d02014-09-17 20:55:46 +0000429Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000430 Value *Src = CI->getArgOperand(0);
431
432 // Constant folding: strlen("xyz") -> 3
433 if (uint64_t Len = GetStringLength(Src))
434 return ConstantInt::get(CI->getType(), Len - 1);
435
David L Kreitzer752c1442016-04-13 14:31:06 +0000436 // If s is a constant pointer pointing to a string literal, we can fold
437 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
438 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
439 // We only try to simplify strlen when the pointer s points to an array
440 // of i8. Otherwise, we would need to scale the offset x before doing the
441 // subtraction. This will make the optimization more complex, and it's not
442 // very useful because calling strlen for a pointer of other types is
443 // very uncommon.
444 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
445 if (!isGEPBasedOnPointerToString(GEP))
446 return nullptr;
447
448 StringRef Str;
449 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
450 size_t NullTermIdx = Str.find('\0');
451
452 // If the string does not have '\0', leave it to strlen to compute
453 // its length.
454 if (NullTermIdx == StringRef::npos)
455 return nullptr;
456
457 Value *Offset = GEP->getOperand(2);
458 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +0000459 KnownBits Known(BitWidth);
460 computeKnownBits(Offset, Known, DL, 0, nullptr, CI, nullptr);
461 Known.Zero.flipAllBits();
David L Kreitzer752c1442016-04-13 14:31:06 +0000462 size_t ArrSize =
463 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
464
465 // KnownZero's bits are flipped, so zeros in KnownZero now represent
466 // bits known to be zeros in Offset, and ones in KnowZero represent
467 // bits unknown in Offset. Therefore, Offset is known to be in range
468 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
469 // unsigned-less-than NullTermIdx.
470 //
471 // If Offset is not provably in the range [0, NullTermIdx], we can still
472 // optimize if we can prove that the program has undefined behavior when
473 // Offset is outside that range. That is the case when GEP->getOperand(0)
474 // is a pointer to an object whose memory extent is NullTermIdx+1.
Craig Topperb45eabc2017-04-26 16:39:58 +0000475 if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
David L Kreitzer752c1442016-04-13 14:31:06 +0000476 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
477 NullTermIdx == ArrSize - 1))
478 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
479 Offset);
480 }
481
482 return nullptr;
483 }
484
Chris Bienemanad070d02014-09-17 20:55:46 +0000485 // strlen(x?"foo":"bars") --> x ? 3 : 4
486 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
487 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
488 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
489 if (LenTrue && LenFalse) {
490 Function *Caller = CI->getParent()->getParent();
491 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
492 SI->getDebugLoc(),
493 "folded strlen(select) to select of constants");
494 return B.CreateSelect(SI->getCondition(),
495 ConstantInt::get(CI->getType(), LenTrue - 1),
496 ConstantInt::get(CI->getType(), LenFalse - 1));
497 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000498 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000499
Chris Bienemanad070d02014-09-17 20:55:46 +0000500 // strlen(x) != 0 --> *x != 0
501 // strlen(x) == 0 --> *x == 0
502 if (isOnlyUsedInZeroEqualityComparison(CI))
503 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000504
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 return nullptr;
506}
Meador Inge17418502012-10-13 16:45:37 +0000507
Chris Bienemanad070d02014-09-17 20:55:46 +0000508Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000509 StringRef S1, S2;
510 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
511 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000512
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000513 // strpbrk(s, "") -> nullptr
514 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000515 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
516 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000517
Chris Bienemanad070d02014-09-17 20:55:46 +0000518 // Constant folding.
519 if (HasS1 && HasS2) {
520 size_t I = S1.find_first_of(S2);
521 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000522 return Constant::getNullValue(CI->getType());
523
Sanjay Pateld707db92015-12-31 16:10:49 +0000524 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
525 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000526 }
Meador Inge17418502012-10-13 16:45:37 +0000527
Chris Bienemanad070d02014-09-17 20:55:46 +0000528 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000529 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000530 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000531
532 return nullptr;
533}
534
535Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000536 Value *EndPtr = CI->getArgOperand(1);
537 if (isa<ConstantPointerNull>(EndPtr)) {
538 // With a null EndPtr, this function won't capture the main argument.
539 // It would be readonly too, except that it still may write to errno.
Reid Klecknera0b45f42017-05-03 18:17:31 +0000540 CI->addParamAttr(0, Attribute::NoCapture);
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 }
542
543 return nullptr;
544}
545
546Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000547 StringRef S1, S2;
548 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
549 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
550
551 // strspn(s, "") -> 0
552 // strspn("", s) -> 0
553 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
554 return Constant::getNullValue(CI->getType());
555
556 // Constant folding.
557 if (HasS1 && HasS2) {
558 size_t Pos = S1.find_first_not_of(S2);
559 if (Pos == StringRef::npos)
560 Pos = S1.size();
561 return ConstantInt::get(CI->getType(), Pos);
562 }
563
564 return nullptr;
565}
566
567Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000568 StringRef S1, S2;
569 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
570 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
571
572 // strcspn("", s) -> 0
573 if (HasS1 && S1.empty())
574 return Constant::getNullValue(CI->getType());
575
576 // Constant folding.
577 if (HasS1 && HasS2) {
578 size_t Pos = S1.find_first_of(S2);
579 if (Pos == StringRef::npos)
580 Pos = S1.size();
581 return ConstantInt::get(CI->getType(), Pos);
582 }
583
584 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000586 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000587
588 return nullptr;
589}
590
591Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000592 // fold strstr(x, x) -> x.
593 if (CI->getArgOperand(0) == CI->getArgOperand(1))
594 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
595
596 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000597 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000598 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000599 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000600 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000601 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000602 StrLen, B, DL, TLI);
603 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000604 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000605 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
606 ICmpInst *Old = cast<ICmpInst>(*UI++);
607 Value *Cmp =
608 B.CreateICmp(Old->getPredicate(), StrNCmp,
609 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
610 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000611 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000612 return CI;
613 }
Meador Inge17418502012-10-13 16:45:37 +0000614
Chris Bienemanad070d02014-09-17 20:55:46 +0000615 // See if either input string is a constant string.
616 StringRef SearchStr, ToFindStr;
617 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
618 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
619
620 // fold strstr(x, "") -> x.
621 if (HasStr2 && ToFindStr.empty())
622 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
623
624 // If both strings are known, constant fold it.
625 if (HasStr1 && HasStr2) {
626 size_t Offset = SearchStr.find(ToFindStr);
627
628 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000629 return Constant::getNullValue(CI->getType());
630
Chris Bienemanad070d02014-09-17 20:55:46 +0000631 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000632 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000633 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
634 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000635 }
Meador Inge17418502012-10-13 16:45:37 +0000636
Chris Bienemanad070d02014-09-17 20:55:46 +0000637 // fold strstr(x, "y") -> strchr(x, 'y').
638 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000639 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000640 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
641 }
642 return nullptr;
643}
Meador Inge40b6fac2012-10-15 03:47:37 +0000644
Benjamin Kramer691363e2015-03-21 15:36:21 +0000645Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000646 Value *SrcStr = CI->getArgOperand(0);
647 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
648 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
649
650 // memchr(x, y, 0) -> null
651 if (LenC && LenC->isNullValue())
652 return Constant::getNullValue(CI->getType());
653
Benjamin Kramer7857d722015-03-21 21:09:33 +0000654 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000655 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000656 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000657 return nullptr;
658
659 // Truncate the string to LenC. If Str is smaller than LenC we will still only
660 // scan the string, as reading past the end of it is undefined and we can just
661 // return null if we don't find the char.
662 Str = Str.substr(0, LenC->getZExtValue());
663
Benjamin Kramer7857d722015-03-21 21:09:33 +0000664 // If the char is variable but the input str and length are not we can turn
665 // this memchr call into a simple bit field test. Of course this only works
666 // when the return value is only checked against null.
667 //
668 // It would be really nice to reuse switch lowering here but we can't change
669 // the CFG at this point.
670 //
671 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
672 // after bounds check.
673 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000674 unsigned char Max =
675 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
676 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000677
678 // Make sure the bit field we're about to create fits in a register on the
679 // target.
680 // FIXME: On a 64 bit architecture this prevents us from using the
681 // interesting range of alpha ascii chars. We could do better by emitting
682 // two bitfields or shifting the range by 64 if no lower chars are used.
683 if (!DL.fitsInLegalInteger(Max + 1))
684 return nullptr;
685
686 // For the bit field use a power-of-2 type with at least 8 bits to avoid
687 // creating unnecessary illegal types.
688 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
689
690 // Now build the bit field.
691 APInt Bitfield(Width, 0);
692 for (char C : Str)
693 Bitfield.setBit((unsigned char)C);
694 Value *BitfieldC = B.getInt(Bitfield);
695
696 // First check that the bit field access is within bounds.
697 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
698 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
699 "memchr.bounds");
700
701 // Create code that checks if the given bit is set in the field.
702 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
703 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
704
705 // Finally merge both checks and cast to pointer type. The inttoptr
706 // implicitly zexts the i1 to intptr type.
707 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
708 }
709
710 // Check if all arguments are constants. If so, we can constant fold.
711 if (!CharC)
712 return nullptr;
713
Benjamin Kramer691363e2015-03-21 15:36:21 +0000714 // Compute the offset.
715 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
716 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
717 return Constant::getNullValue(CI->getType());
718
719 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000720 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000721}
722
Chris Bienemanad070d02014-09-17 20:55:46 +0000723Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000724 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000725
Chris Bienemanad070d02014-09-17 20:55:46 +0000726 if (LHS == RHS) // memcmp(s,s,x) -> 0
727 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000728
Chris Bienemanad070d02014-09-17 20:55:46 +0000729 // Make sure we have a constant length.
730 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
731 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000732 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000733 uint64_t Len = LenC->getZExtValue();
734
735 if (Len == 0) // memcmp(s1,s2,0) -> 0
736 return Constant::getNullValue(CI->getType());
737
738 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
739 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000740 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000741 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000742 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 CI->getType(), "rhsv");
744 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000745 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000746
Chad Rosierdc655322015-08-28 18:30:18 +0000747 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
748 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
749
750 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
751 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
752
753 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
754 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
755
756 Type *LHSPtrTy =
757 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
758 Type *RHSPtrTy =
759 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
760
Sanjay Pateld707db92015-12-31 16:10:49 +0000761 Value *LHSV =
762 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
763 Value *RHSV =
764 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000765
766 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
767 }
768 }
769
Chris Bienemanad070d02014-09-17 20:55:46 +0000770 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
771 StringRef LHSStr, RHSStr;
772 if (getConstantStringInfo(LHS, LHSStr) &&
773 getConstantStringInfo(RHS, RHSStr)) {
774 // Make sure we're not reading out-of-bounds memory.
775 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000776 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000777 // Fold the memcmp and normalize the result. This way we get consistent
778 // results across multiple platforms.
779 uint64_t Ret = 0;
780 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
781 if (Cmp < 0)
782 Ret = -1;
783 else if (Cmp > 0)
784 Ret = 1;
785 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000786 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000787
Chris Bienemanad070d02014-09-17 20:55:46 +0000788 return nullptr;
789}
Meador Inge9a6a1902012-10-31 00:20:56 +0000790
Chris Bienemanad070d02014-09-17 20:55:46 +0000791Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000792 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
793 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000794 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000795 return CI->getArgOperand(0);
796}
Meador Inge05a625a2012-10-31 14:58:26 +0000797
Chris Bienemanad070d02014-09-17 20:55:46 +0000798Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000799 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
800 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000801 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000802 return CI->getArgOperand(0);
803}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000804
Sanjay Patel980b2802016-01-26 16:17:24 +0000805// TODO: Does this belong in BuildLibCalls or should all of those similar
806// functions be moved here?
Reid Klecknerb5180542017-03-21 16:57:19 +0000807static Value *emitCalloc(Value *Num, Value *Size, const AttributeList &Attrs,
Sanjay Patel980b2802016-01-26 16:17:24 +0000808 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
David L. Jonesd21529f2017-01-23 23:16:46 +0000809 LibFunc Func;
Sanjay Patel980b2802016-01-26 16:17:24 +0000810 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
811 return nullptr;
812
813 Module *M = B.GetInsertBlock()->getModule();
814 const DataLayout &DL = M->getDataLayout();
815 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
816 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000817 PtrType, PtrType);
Sanjay Patel980b2802016-01-26 16:17:24 +0000818 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
819
820 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
821 CI->setCallingConv(F->getCallingConv());
822
823 return CI;
824}
825
826/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
827static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
828 const TargetLibraryInfo &TLI) {
829 // This has to be a memset of zeros (bzero).
830 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
831 if (!FillValue || FillValue->getZExtValue() != 0)
832 return nullptr;
833
834 // TODO: We should handle the case where the malloc has more than one use.
835 // This is necessary to optimize common patterns such as when the result of
836 // the malloc is checked against null or when a memset intrinsic is used in
837 // place of a memset library call.
838 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
839 if (!Malloc || !Malloc->hasOneUse())
840 return nullptr;
841
842 // Is the inner call really malloc()?
843 Function *InnerCallee = Malloc->getCalledFunction();
Matthias Braunc36a78c2017-04-25 19:44:25 +0000844 if (!InnerCallee)
845 return nullptr;
846
David L. Jonesd21529f2017-01-23 23:16:46 +0000847 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000848 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
David L. Jonesd21529f2017-01-23 23:16:46 +0000849 Func != LibFunc_malloc)
Sanjay Patel980b2802016-01-26 16:17:24 +0000850 return nullptr;
851
Sanjay Patel980b2802016-01-26 16:17:24 +0000852 // The memset must cover the same number of bytes that are malloc'd.
853 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
854 return nullptr;
855
856 // Replace the malloc with a calloc. We need the data layout to know what the
857 // actual size of a 'size_t' parameter is.
858 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
859 const DataLayout &DL = Malloc->getModule()->getDataLayout();
860 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
861 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
862 Malloc->getArgOperand(0), Malloc->getAttributes(),
863 B, TLI);
864 if (!Calloc)
865 return nullptr;
866
867 Malloc->replaceAllUsesWith(Calloc);
868 Malloc->eraseFromParent();
869
870 return Calloc;
871}
872
Chris Bienemanad070d02014-09-17 20:55:46 +0000873Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000874 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
875 return Calloc;
876
Chris Bienemanad070d02014-09-17 20:55:46 +0000877 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
878 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
879 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
880 return CI->getArgOperand(0);
881}
Meador Inged4825782012-11-11 06:49:03 +0000882
Meador Inge193e0352012-11-13 04:16:17 +0000883//===----------------------------------------------------------------------===//
884// Math Library Optimizations
885//===----------------------------------------------------------------------===//
886
Matthias Braund34e4d22014-12-03 21:46:33 +0000887/// Return a variant of Val with float type.
888/// Currently this works in two cases: If Val is an FPExtension of a float
889/// value to something bigger, simply return the operand.
890/// If Val is a ConstantFP but can be converted to a float ConstantFP without
891/// loss of precision do so.
892static Value *valueHasFloatPrecision(Value *Val) {
893 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
894 Value *Op = Cast->getOperand(0);
895 if (Op->getType()->isFloatTy())
896 return Op;
897 }
898 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
899 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000900 bool losesInfo;
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000901 (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000902 &losesInfo);
903 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000904 return ConstantFP::get(Const->getContext(), F);
905 }
906 return nullptr;
907}
908
Sanjay Patel4e971da2016-01-21 18:01:57 +0000909/// Shrink double -> float for unary functions like 'floor'.
910static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
911 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000912 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000913 // We know this libcall has a valid prototype, but we don't know which.
914 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000915 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000916
Chris Bienemanad070d02014-09-17 20:55:46 +0000917 if (CheckRetType) {
918 // Check if all the uses for function like 'sin' are converted to float.
919 for (User *U : CI->users()) {
920 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
921 if (!Cast || !Cast->getType()->isFloatTy())
922 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000923 }
Meador Inge193e0352012-11-13 04:16:17 +0000924 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000925
926 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000927 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
928 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000929 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000930
Andrew Ng1606fc02017-04-25 12:36:14 +0000931 // If call isn't an intrinsic, check that it isn't within a function with the
932 // same name as the float version of this call.
933 //
934 // e.g. inline float expf(float val) { return (float) exp((double) val); }
935 //
936 // A similar such definition exists in the MinGW-w64 math.h header file which
937 // when compiled with -O2 -ffast-math causes the generation of infinite loops
938 // where expf is called.
939 if (!Callee->isIntrinsic()) {
940 const Function *F = CI->getFunction();
941 StringRef FName = F->getName();
942 StringRef CalleeName = Callee->getName();
943 if ((FName.size() == (CalleeName.size() + 1)) &&
944 (FName.back() == 'f') &&
945 FName.startswith(CalleeName))
946 return nullptr;
947 }
948
Sanjay Patelaa231142015-12-31 21:52:31 +0000949 // Propagate fast-math flags from the existing call to the new call.
950 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000951 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000952
953 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000954 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000955 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000956 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000957 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
958 V = B.CreateCall(F, V);
959 } else {
960 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000961 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000962 }
963
Chris Bienemanad070d02014-09-17 20:55:46 +0000964 return B.CreateFPExt(V, B.getDoubleTy());
965}
Meador Inge193e0352012-11-13 04:16:17 +0000966
Matt Arsenault954a6242017-01-23 23:55:08 +0000967// Replace a libcall \p CI with a call to intrinsic \p IID
968static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
969 // Propagate fast-math flags from the existing call to the new call.
970 IRBuilder<>::FastMathFlagGuard Guard(B);
971 B.setFastMathFlags(CI->getFastMathFlags());
972
973 Module *M = CI->getModule();
974 Value *V = CI->getArgOperand(0);
975 Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
976 CallInst *NewCall = B.CreateCall(F, V);
977 NewCall->takeName(CI);
978 return NewCall;
979}
980
Sanjay Patel4e971da2016-01-21 18:01:57 +0000981/// Shrink double -> float for binary functions like 'fmin/fmax'.
982static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000983 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000984 // We know this libcall has a valid prototype, but we don't know which.
985 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000986 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000987
Chris Bienemanad070d02014-09-17 20:55:46 +0000988 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000989 // or fmin(1.0, (double)floatval), then we convert it to fminf.
990 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
991 if (V1 == nullptr)
992 return nullptr;
993 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
994 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000995 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000996
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000997 // Propagate fast-math flags from the existing call to the new call.
998 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000999 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +00001000
Chris Bienemanad070d02014-09-17 20:55:46 +00001001 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001002 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001003 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +00001004 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +00001005 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001006 return B.CreateFPExt(V, B.getDoubleTy());
1007}
1008
1009Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1010 Function *Callee = CI->getCalledFunction();
1011 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001012 StringRef Name = Callee->getName();
1013 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001014 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001015
Chris Bienemanad070d02014-09-17 20:55:46 +00001016 // cos(-x) -> cos(x)
1017 Value *Op1 = CI->getArgOperand(0);
1018 if (BinaryOperator::isFNeg(Op1)) {
1019 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1020 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1021 }
1022 return Ret;
1023}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001024
Weiming Zhao82130722015-12-04 22:00:47 +00001025static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
1026 // Multiplications calculated using Addition Chains.
1027 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
1028
1029 assert(Exp != 0 && "Incorrect exponent 0 not handled");
1030
1031 if (InnerChain[Exp])
1032 return InnerChain[Exp];
1033
1034 static const unsigned AddChain[33][2] = {
1035 {0, 0}, // Unused.
1036 {0, 0}, // Unused (base case = pow1).
1037 {1, 1}, // Unused (pre-computed).
1038 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
1039 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
1040 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
1041 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
1042 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
1043 };
1044
1045 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
1046 getPow(InnerChain, AddChain[Exp][1], B));
1047 return InnerChain[Exp];
1048}
1049
Chris Bienemanad070d02014-09-17 20:55:46 +00001050Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1051 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001052 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001053 StringRef Name = Callee->getName();
1054 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001055 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001056
Chris Bienemanad070d02014-09-17 20:55:46 +00001057 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +00001058
1059 // pow(1.0, x) -> 1.0
1060 if (match(Op1, m_SpecificFP(1.0)))
1061 return Op1;
1062 // pow(2.0, x) -> llvm.exp2(x)
1063 if (match(Op1, m_SpecificFP(2.0))) {
1064 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1065 CI->getType());
1066 return B.CreateCall(Exp2, Op2, "exp2");
1067 }
1068
1069 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1070 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001071 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001072 // pow(10.0, x) -> exp10(x)
1073 if (Op1C->isExactlyValue(10.0) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001074 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc_exp10, LibFunc_exp10f,
1075 LibFunc_exp10l))
1076 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc_exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001077 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001078 }
1079
Sanjay Patel6002e782016-01-12 17:30:37 +00001080 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001081 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001082 // We enable these only with fast-math. Besides rounding differences, the
1083 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001084 // Example: x = 1000, y = 0.001.
1085 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001086 auto *OpC = dyn_cast<CallInst>(Op1);
1087 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001088 LibFunc Func;
Sanjay Patel6002e782016-01-12 17:30:37 +00001089 Function *OpCCallee = OpC->getCalledFunction();
1090 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001091 TLI->has(Func) && (Func == LibFunc_exp || Func == LibFunc_exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001092 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001093 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001094 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001095 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001096 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001097 }
1098 }
1099
Chris Bienemanad070d02014-09-17 20:55:46 +00001100 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1101 if (!Op2C)
1102 return Ret;
1103
1104 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1105 return ConstantFP::get(CI->getType(), 1.0);
1106
Davide Italiano472684e2017-01-09 21:55:23 +00001107 if (Op2C->isExactlyValue(-0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001108 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1109 LibFunc_sqrtl)) {
Davide Italiano472684e2017-01-09 21:55:23 +00001110 // If -ffast-math:
1111 // pow(x, -0.5) -> 1.0 / sqrt(x)
1112 if (CI->hasUnsafeAlgebra()) {
1113 IRBuilder<>::FastMathFlagGuard Guard(B);
1114 B.setFastMathFlags(CI->getFastMathFlags());
1115
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001116 // TODO: If the pow call is an intrinsic, we should lower to the sqrt
1117 // intrinsic, so we match errno semantics. We also should check that the
1118 // target can in fact lower the sqrt intrinsic -- we currently have no way
1119 // to ask this question other than asking whether the target has a sqrt
1120 // libcall, which is a sufficient but not necessary condition.
David L. Jonesd21529f2017-01-23 23:16:46 +00001121 Value *Sqrt = emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano472684e2017-01-09 21:55:23 +00001122 Callee->getAttributes());
1123
1124 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Sqrt, "sqrtrecip");
1125 }
1126 }
1127
Chris Bienemanad070d02014-09-17 20:55:46 +00001128 if (Op2C->isExactlyValue(0.5) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001129 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc_sqrt, LibFunc_sqrtf,
1130 LibFunc_sqrtl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001131
1132 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001133 if (CI->hasUnsafeAlgebra()) {
1134 IRBuilder<>::FastMathFlagGuard Guard(B);
1135 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001136
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001137 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1138 // intrinsic, to match errno semantics.
David L. Jonesd21529f2017-01-23 23:16:46 +00001139 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc_sqrt), B,
Davide Italiano873219c2016-08-10 06:33:32 +00001140 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001141 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001142
Chris Bienemanad070d02014-09-17 20:55:46 +00001143 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1144 // This is faster than calling pow, and still handles negative zero
1145 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001146 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1147 Value *Inf = ConstantFP::getInfinity(CI->getType());
1148 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001149
1150 // TODO: As above, we should lower to the sqrt intrinsic if the pow is an
1151 // intrinsic, to match errno semantics.
Sanjay Pateld3112a52016-01-19 19:46:10 +00001152 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Matt Arsenaultb948b4d2017-01-17 00:30:31 +00001153
1154 Module *M = Callee->getParent();
1155 Function *FabsF = Intrinsic::getDeclaration(M, Intrinsic::fabs,
1156 CI->getType());
1157 Value *FAbs = B.CreateCall(FabsF, Sqrt);
1158
Chris Bienemanad070d02014-09-17 20:55:46 +00001159 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1160 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1161 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001162 }
1163
Chris Bienemanad070d02014-09-17 20:55:46 +00001164 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1165 return Op1;
1166 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1167 return B.CreateFMul(Op1, Op1, "pow2");
1168 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1169 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001170
1171 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001172 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001173 APFloat V = abs(Op2C->getValueAPF());
1174 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1175 // This transformation applies to integer exponents only.
1176 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1177 !V.isInteger())
1178 return nullptr;
1179
Davide Italianof8711f02017-01-10 18:02:05 +00001180 // Propagate fast math flags.
1181 IRBuilder<>::FastMathFlagGuard Guard(B);
1182 B.setFastMathFlags(CI->getFastMathFlags());
1183
Weiming Zhao82130722015-12-04 22:00:47 +00001184 // We will memoize intermediate products of the Addition Chain.
1185 Value *InnerChain[33] = {nullptr};
1186 InnerChain[1] = Op1;
1187 InnerChain[2] = B.CreateFMul(Op1, Op1);
1188
1189 // We cannot readily convert a non-double type (like float) to a double.
1190 // So we first convert V to something which could be converted to double.
1191 bool ignored;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001192 V.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001193
Weiming Zhao82130722015-12-04 22:00:47 +00001194 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1195 // For negative exponents simply compute the reciprocal.
1196 if (Op2C->isNegative())
1197 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1198 return FMul;
1199 }
1200
Chris Bienemanad070d02014-09-17 20:55:46 +00001201 return nullptr;
1202}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001203
Chris Bienemanad070d02014-09-17 20:55:46 +00001204Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1205 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001206 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001207 StringRef Name = Callee->getName();
1208 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001209 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001210
Chris Bienemanad070d02014-09-17 20:55:46 +00001211 Value *Op = CI->getArgOperand(0);
1212 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1213 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
David L. Jonesd21529f2017-01-23 23:16:46 +00001214 LibFunc LdExp = LibFunc_ldexpl;
Chris Bienemanad070d02014-09-17 20:55:46 +00001215 if (Op->getType()->isFloatTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001216 LdExp = LibFunc_ldexpf;
Chris Bienemanad070d02014-09-17 20:55:46 +00001217 else if (Op->getType()->isDoubleTy())
David L. Jonesd21529f2017-01-23 23:16:46 +00001218 LdExp = LibFunc_ldexp;
Chris Bienemanad070d02014-09-17 20:55:46 +00001219
1220 if (TLI->has(LdExp)) {
1221 Value *LdExpArg = nullptr;
1222 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1223 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1224 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1225 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1226 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1227 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1228 }
1229
1230 if (LdExpArg) {
1231 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1232 if (!Op->getType()->isFloatTy())
1233 One = ConstantExpr::getFPExtend(One, Op->getType());
1234
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001235 Module *M = CI->getModule();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001236 Value *NewCallee =
1237 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001238 Op->getType(), B.getInt32Ty());
Sanjay Patel042aed902016-01-21 22:41:16 +00001239 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001240 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1241 CI->setCallingConv(F->getCallingConv());
1242
1243 return CI;
1244 }
1245 }
1246 return Ret;
1247}
1248
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001249Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001250 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001251 // If we can shrink the call to a float function rather than a double
1252 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001253 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001254 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1255 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001256 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001257
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001258 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001259 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001260 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001261 // Unsafe algebra sets all fast-math-flags to true.
1262 FMF.setUnsafeAlgebra();
1263 } else {
1264 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001265 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001266 return nullptr;
1267 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1268 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001269 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001270 // might be impractical."
1271 FMF.setNoSignedZeros();
1272 FMF.setNoNaNs();
1273 }
Sanjay Patela2528152016-01-12 18:03:37 +00001274 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001275
1276 // We have a relaxed floating-point environment. We can ignore NaN-handling
1277 // and transform to a compare and select. We do not have to consider errno or
1278 // exceptions, because fmin/fmax do not have those.
1279 Value *Op0 = CI->getArgOperand(0);
1280 Value *Op1 = CI->getArgOperand(1);
1281 Value *Cmp = Callee->getName().startswith("fmin") ?
1282 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1283 return B.CreateSelect(Cmp, Op0, Op1);
1284}
1285
Davide Italianob8b71332015-11-29 20:58:04 +00001286Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1287 Function *Callee = CI->getCalledFunction();
1288 Value *Ret = nullptr;
1289 StringRef Name = Callee->getName();
1290 if (UnsafeFPShrink && hasFloatVersion(Name))
1291 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001292
Sanjay Patele896ede2016-01-11 23:31:48 +00001293 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001294 return Ret;
1295 Value *Op1 = CI->getArgOperand(0);
1296 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001297
1298 // The earlier call must also be unsafe in order to do these transforms.
1299 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001300 return Ret;
1301
1302 // log(pow(x,y)) -> y*log(x)
1303 // This is only applicable to log, log2, log10.
1304 if (Name != "log" && Name != "log2" && Name != "log10")
1305 return Ret;
1306
1307 IRBuilder<>::FastMathFlagGuard Guard(B);
1308 FastMathFlags FMF;
1309 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001310 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001311
David L. Jonesd21529f2017-01-23 23:16:46 +00001312 LibFunc Func;
Davide Italianob8b71332015-11-29 20:58:04 +00001313 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001314 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001315 Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001316 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001317 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001318 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001319
1320 // log(exp2(y)) -> y*log(2)
1321 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001322 TLI->has(Func) && Func == LibFunc_exp2)
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001323 return B.CreateFMul(
1324 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001325 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001326 Callee->getName(), B, Callee->getAttributes()),
1327 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001328 return Ret;
1329}
1330
Sanjay Patelc699a612014-10-16 18:48:17 +00001331Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1332 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001333 Value *Ret = nullptr;
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001334 // TODO: Once we have a way (other than checking for the existince of the
1335 // libcall) to tell whether our target can lower @llvm.sqrt, relax the
1336 // condition below.
David L. Jonesd21529f2017-01-23 23:16:46 +00001337 if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
Justin Lebarcb9b41d2017-01-27 00:58:03 +00001338 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001339 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001340
1341 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001342 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001343
Sanjay Patelc2d64612016-01-06 20:52:21 +00001344 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1345 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1346 return Ret;
1347
1348 // We're looking for a repeated factor in a multiplication tree,
1349 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001350 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001351 Value *Op0 = I->getOperand(0);
1352 Value *Op1 = I->getOperand(1);
1353 Value *RepeatOp = nullptr;
1354 Value *OtherOp = nullptr;
1355 if (Op0 == Op1) {
1356 // Simple match: the operands of the multiply are identical.
1357 RepeatOp = Op0;
1358 } else {
1359 // Look for a more complicated pattern: one of the operands is itself
1360 // a multiply, so search for a common factor in that multiply.
1361 // Note: We don't bother looking any deeper than this first level or for
1362 // variations of this pattern because instcombine's visitFMUL and/or the
1363 // reassociation pass should give us this form.
1364 Value *OtherMul0, *OtherMul1;
1365 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1366 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001367 if (OtherMul0 == OtherMul1 &&
1368 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001369 // Matched: sqrt((x * x) * z)
1370 RepeatOp = OtherMul0;
1371 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001372 }
1373 }
1374 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001375 if (!RepeatOp)
1376 return Ret;
1377
1378 // Fast math flags for any created instructions should match the sqrt
1379 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001380 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001381 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001382
Sanjay Patelc2d64612016-01-06 20:52:21 +00001383 // If we found a repeated factor, hoist it out of the square root and
1384 // replace it with the fabs of that factor.
1385 Module *M = Callee->getParent();
1386 Type *ArgType = I->getType();
1387 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1388 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1389 if (OtherOp) {
1390 // If we found a non-repeated factor, we still need to get its square
1391 // root. We then multiply that by the value that was simplified out
1392 // of the square root calculation.
1393 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1394 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1395 return B.CreateFMul(FabsCall, SqrtCall);
1396 }
1397 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001398}
1399
Sanjay Patelcddcd722016-01-06 19:23:35 +00001400// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001401Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1402 Function *Callee = CI->getCalledFunction();
1403 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001404 StringRef Name = Callee->getName();
1405 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001406 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001407
Davide Italiano51507d22015-11-04 23:36:56 +00001408 Value *Op1 = CI->getArgOperand(0);
1409 auto *OpC = dyn_cast<CallInst>(Op1);
1410 if (!OpC)
1411 return Ret;
1412
Sanjay Patelcddcd722016-01-06 19:23:35 +00001413 // Both calls must allow unsafe optimizations in order to remove them.
1414 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1415 return Ret;
1416
Davide Italiano51507d22015-11-04 23:36:56 +00001417 // tan(atan(x)) -> x
1418 // tanf(atanf(x)) -> x
1419 // tanl(atanl(x)) -> x
David L. Jonesd21529f2017-01-23 23:16:46 +00001420 LibFunc Func;
Davide Italiano51507d22015-11-04 23:36:56 +00001421 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001422 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
David L. Jonesd21529f2017-01-23 23:16:46 +00001423 ((Func == LibFunc_atan && Callee->getName() == "tan") ||
1424 (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
1425 (Func == LibFunc_atanl && Callee->getName() == "tanl")))
Davide Italiano51507d22015-11-04 23:36:56 +00001426 Ret = OpC->getArgOperand(0);
1427 return Ret;
1428}
1429
Sanjay Patel57747212016-01-21 23:38:43 +00001430static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001431 // We can only hope to do anything useful if we can ignore things like errno
1432 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001433 // We already checked the prototype.
1434 return CI->hasFnAttr(Attribute::NoUnwind) &&
1435 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001436}
1437
Chris Bienemanad070d02014-09-17 20:55:46 +00001438static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1439 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001440 Value *&SinCos) {
1441 Type *ArgTy = Arg->getType();
1442 Type *ResTy;
1443 StringRef Name;
1444
1445 Triple T(OrigCallee->getParent()->getTargetTriple());
1446 if (UseFloat) {
1447 Name = "__sincospif_stret";
1448
1449 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1450 // x86_64 can't use {float, float} since that would be returned in both
1451 // xmm0 and xmm1, which isn't what a real struct would do.
1452 ResTy = T.getArch() == Triple::x86_64
1453 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1454 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1455 } else {
1456 Name = "__sincospi_stret";
1457 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1458 }
1459
1460 Module *M = OrigCallee->getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001461 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001462 ResTy, ArgTy);
Sanjay Patel57747212016-01-21 23:38:43 +00001463
1464 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1465 // If the argument is an instruction, it must dominate all uses so put our
1466 // sincos call there.
1467 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1468 } else {
1469 // Otherwise (e.g. for a constant) the beginning of the function is as
1470 // good a place as any.
1471 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1472 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1473 }
1474
1475 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1476
1477 if (SinCos->getType()->isStructTy()) {
1478 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1479 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1480 } else {
1481 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1482 "sinpi");
1483 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1484 "cospi");
1485 }
1486}
Chris Bienemanad070d02014-09-17 20:55:46 +00001487
1488Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001489 // Make sure the prototype is as expected, otherwise the rest of the
1490 // function is probably invalid and likely to abort.
1491 if (!isTrigLibCall(CI))
1492 return nullptr;
1493
1494 Value *Arg = CI->getArgOperand(0);
1495 SmallVector<CallInst *, 1> SinCalls;
1496 SmallVector<CallInst *, 1> CosCalls;
1497 SmallVector<CallInst *, 1> SinCosCalls;
1498
1499 bool IsFloat = Arg->getType()->isFloatTy();
1500
1501 // Look for all compatible sinpi, cospi and sincospi calls with the same
1502 // argument. If there are enough (in some sense) we can make the
1503 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001504 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001505 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001506 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001507
1508 // It's only worthwhile if both sinpi and cospi are actually used.
1509 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1510 return nullptr;
1511
1512 Value *Sin, *Cos, *SinCos;
1513 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1514
Davide Italianof024a562016-12-16 02:28:38 +00001515 auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
1516 Value *Res) {
1517 for (CallInst *C : Calls)
1518 replaceAllUsesWith(C, Res);
1519 };
1520
Chris Bienemanad070d02014-09-17 20:55:46 +00001521 replaceTrigInsts(SinCalls, Sin);
1522 replaceTrigInsts(CosCalls, Cos);
1523 replaceTrigInsts(SinCosCalls, SinCos);
1524
1525 return nullptr;
1526}
1527
David Majnemerabae6b52016-03-19 04:53:02 +00001528void LibCallSimplifier::classifyArgUse(
1529 Value *Val, Function *F, bool IsFloat,
1530 SmallVectorImpl<CallInst *> &SinCalls,
1531 SmallVectorImpl<CallInst *> &CosCalls,
1532 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001533 CallInst *CI = dyn_cast<CallInst>(Val);
1534
1535 if (!CI)
1536 return;
1537
David Majnemerabae6b52016-03-19 04:53:02 +00001538 // Don't consider calls in other functions.
1539 if (CI->getFunction() != F)
1540 return;
1541
Chris Bienemanad070d02014-09-17 20:55:46 +00001542 Function *Callee = CI->getCalledFunction();
David L. Jonesd21529f2017-01-23 23:16:46 +00001543 LibFunc Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001544 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001545 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001546 return;
1547
1548 if (IsFloat) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001549 if (Func == LibFunc_sinpif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001550 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001551 else if (Func == LibFunc_cospif)
Chris Bienemanad070d02014-09-17 20:55:46 +00001552 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001553 else if (Func == LibFunc_sincospif_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001554 SinCosCalls.push_back(CI);
1555 } else {
David L. Jonesd21529f2017-01-23 23:16:46 +00001556 if (Func == LibFunc_sinpi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001557 SinCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001558 else if (Func == LibFunc_cospi)
Chris Bienemanad070d02014-09-17 20:55:46 +00001559 CosCalls.push_back(CI);
David L. Jonesd21529f2017-01-23 23:16:46 +00001560 else if (Func == LibFunc_sincospi_stret)
Chris Bienemanad070d02014-09-17 20:55:46 +00001561 SinCosCalls.push_back(CI);
1562 }
1563}
1564
Meador Inge7415f842012-11-25 20:45:27 +00001565//===----------------------------------------------------------------------===//
1566// Integer Library Call Optimizations
1567//===----------------------------------------------------------------------===//
1568
Chris Bienemanad070d02014-09-17 20:55:46 +00001569Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001570 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Davide Italiano890e8502016-12-15 23:11:00 +00001571 Value *Op = CI->getArgOperand(0);
Chris Bienemanad070d02014-09-17 20:55:46 +00001572 Type *ArgType = Op->getType();
Davide Italiano890e8502016-12-15 23:11:00 +00001573 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1574 Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001575 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001576 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1577 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001578
Chris Bienemanad070d02014-09-17 20:55:46 +00001579 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1580 return B.CreateSelect(Cond, V, B.getInt32(0));
1581}
Meador Ingea0b6d872012-11-26 00:24:07 +00001582
Davide Italiano85ad36b2016-12-15 23:45:11 +00001583Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
1584 // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
1585 Value *Op = CI->getArgOperand(0);
1586 Type *ArgType = Op->getType();
1587 Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
1588 Intrinsic::ctlz, ArgType);
1589 Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
1590 V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
1591 V);
1592 return B.CreateIntCast(V, CI->getType(), false);
1593}
1594
Chris Bienemanad070d02014-09-17 20:55:46 +00001595Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001596 // abs(x) -> x >s -1 ? x : -x
1597 Value *Op = CI->getArgOperand(0);
1598 Value *Pos =
1599 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1600 Value *Neg = B.CreateNeg(Op, "neg");
1601 return B.CreateSelect(Pos, Op, Neg);
1602}
Meador Inge9a59ab62012-11-26 02:31:59 +00001603
Chris Bienemanad070d02014-09-17 20:55:46 +00001604Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001605 // isdigit(c) -> (c-'0') <u 10
1606 Value *Op = CI->getArgOperand(0);
1607 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1608 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1609 return B.CreateZExt(Op, CI->getType());
1610}
Meador Ingea62a39e2012-11-26 03:10:07 +00001611
Chris Bienemanad070d02014-09-17 20:55:46 +00001612Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001613 // isascii(c) -> c <u 128
1614 Value *Op = CI->getArgOperand(0);
1615 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1616 return B.CreateZExt(Op, CI->getType());
1617}
1618
1619Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001620 // toascii(c) -> c & 0x7f
1621 return B.CreateAnd(CI->getArgOperand(0),
1622 ConstantInt::get(CI->getType(), 0x7F));
1623}
Meador Inge604937d2012-11-26 03:38:52 +00001624
Meador Inge08ca1152012-11-26 20:37:20 +00001625//===----------------------------------------------------------------------===//
1626// Formatting and IO Library Call Optimizations
1627//===----------------------------------------------------------------------===//
1628
Chris Bienemanad070d02014-09-17 20:55:46 +00001629static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001630
Chris Bienemanad070d02014-09-17 20:55:46 +00001631Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1632 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001633 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001634 // Error reporting calls should be cold, mark them as such.
1635 // This applies even to non-builtin calls: it is only a hint and applies to
1636 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001637
Chris Bienemanad070d02014-09-17 20:55:46 +00001638 // This heuristic was suggested in:
1639 // Improving Static Branch Prediction in a Compiler
1640 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1641 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001642 if (!CI->hasFnAttr(Attribute::Cold) &&
1643 isReportingError(Callee, CI, StreamArg)) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001644 CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
Chris Bienemanad070d02014-09-17 20:55:46 +00001645 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001646
Chris Bienemanad070d02014-09-17 20:55:46 +00001647 return nullptr;
1648}
1649
1650static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italiano5b65f122017-04-25 03:48:47 +00001651 if (!Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001652 return false;
1653
1654 if (StreamArg < 0)
1655 return true;
1656
1657 // These functions might be considered cold, but only if their stream
1658 // argument is stderr.
1659
1660 if (StreamArg >= (int)CI->getNumArgOperands())
1661 return false;
1662 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1663 if (!LI)
1664 return false;
1665 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1666 if (!GV || !GV->isDeclaration())
1667 return false;
1668 return GV->getName() == "stderr";
1669}
1670
1671Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1672 // Check for a fixed format string.
1673 StringRef FormatStr;
1674 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001675 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001676
Chris Bienemanad070d02014-09-17 20:55:46 +00001677 // Empty format string -> noop.
1678 if (FormatStr.empty()) // Tolerate printf's declared void.
1679 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001680
Chris Bienemanad070d02014-09-17 20:55:46 +00001681 // Do not do any of the following transformations if the printf return value
1682 // is used, in general the printf return value is not compatible with either
1683 // putchar() or puts().
1684 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001685 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001686
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001687 // printf("x") -> putchar('x'), even for "%" and "%%".
1688 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001689 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001690
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001691 // printf("%s", "a") --> putchar('a')
1692 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1693 StringRef ChrStr;
1694 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1695 return nullptr;
1696 if (ChrStr.size() != 1)
1697 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001698 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001699 }
1700
Chris Bienemanad070d02014-09-17 20:55:46 +00001701 // printf("foo\n") --> puts("foo")
1702 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1703 FormatStr.find('%') == StringRef::npos) { // No format characters.
1704 // Create a string literal with no \n on it. We expect the constant merge
1705 // pass to be run after this pass, to merge duplicate strings.
1706 FormatStr = FormatStr.drop_back();
1707 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001708 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 }
Meador Inge08ca1152012-11-26 20:37:20 +00001710
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 // Optimize specific format strings.
1712 // printf("%c", chr) --> putchar(chr)
1713 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001714 CI->getArgOperand(1)->getType()->isIntegerTy())
1715 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001716
1717 // printf("%s\n", str) --> puts(str)
1718 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001719 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001720 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001721 return nullptr;
1722}
1723
1724Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1725
1726 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001727 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001728 if (Value *V = optimizePrintFString(CI, B)) {
1729 return V;
1730 }
1731
1732 // printf(format, ...) -> iprintf(format, ...) if no floating point
1733 // arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001734 if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001735 Module *M = B.GetInsertBlock()->getParent()->getParent();
1736 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001737 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001738 CallInst *New = cast<CallInst>(CI->clone());
1739 New->setCalledFunction(IPrintFFn);
1740 B.Insert(New);
1741 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001742 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 return nullptr;
1744}
Meador Inge08ca1152012-11-26 20:37:20 +00001745
Chris Bienemanad070d02014-09-17 20:55:46 +00001746Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1747 // Check for a fixed format string.
1748 StringRef FormatStr;
1749 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001750 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001751
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 // If we just have a format string (nothing else crazy) transform it.
1753 if (CI->getNumArgOperands() == 2) {
1754 // Make sure there's no % in the constant array. We could try to handle
1755 // %% -> % in the future if we cared.
1756 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1757 if (FormatStr[i] == '%')
1758 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001759
Chris Bienemanad070d02014-09-17 20:55:46 +00001760 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001761 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1762 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1763 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001764 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001766 }
Meador Ingef8e72502012-11-29 15:45:43 +00001767
Chris Bienemanad070d02014-09-17 20:55:46 +00001768 // The remaining optimizations require the format string to be "%s" or "%c"
1769 // and have an extra operand.
1770 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1771 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001772 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001773
Chris Bienemanad070d02014-09-17 20:55:46 +00001774 // Decode the second character of the format string.
1775 if (FormatStr[1] == 'c') {
1776 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1777 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1778 return nullptr;
1779 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001780 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001781 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001782 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001783 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001784
Chris Bienemanad070d02014-09-17 20:55:46 +00001785 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001786 }
1787
Chris Bienemanad070d02014-09-17 20:55:46 +00001788 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001789 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1790 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1791 return nullptr;
1792
Sanjay Pateld3112a52016-01-19 19:46:10 +00001793 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001794 if (!Len)
1795 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001796 Value *IncLen =
1797 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1798 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001799
1800 // The sprintf result is the unincremented number of bytes in the string.
1801 return B.CreateIntCast(Len, CI->getType(), false);
1802 }
1803 return nullptr;
1804}
1805
1806Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1807 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001808 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001809 if (Value *V = optimizeSPrintFString(CI, B)) {
1810 return V;
1811 }
1812
1813 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1814 // point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001815 if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001816 Module *M = B.GetInsertBlock()->getParent()->getParent();
1817 Constant *SIPrintFFn =
1818 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1819 CallInst *New = cast<CallInst>(CI->clone());
1820 New->setCalledFunction(SIPrintFFn);
1821 B.Insert(New);
1822 return New;
1823 }
1824 return nullptr;
1825}
1826
1827Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1828 optimizeErrorReporting(CI, B, 0);
1829
1830 // All the optimizations depend on the format string.
1831 StringRef FormatStr;
1832 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1833 return nullptr;
1834
1835 // Do not do any of the following transformations if the fprintf return
1836 // value is used, in general the fprintf return value is not compatible
1837 // with fwrite(), fputc() or fputs().
1838 if (!CI->use_empty())
1839 return nullptr;
1840
1841 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1842 if (CI->getNumArgOperands() == 2) {
1843 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1844 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1845 return nullptr; // We found a format specifier.
1846
Sanjay Pateld3112a52016-01-19 19:46:10 +00001847 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001848 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001849 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001850 CI->getArgOperand(0), B, DL, TLI);
1851 }
1852
1853 // The remaining optimizations require the format string to be "%s" or "%c"
1854 // and have an extra operand.
1855 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1856 CI->getNumArgOperands() < 3)
1857 return nullptr;
1858
1859 // Decode the second character of the format string.
1860 if (FormatStr[1] == 'c') {
1861 // fprintf(F, "%c", chr) --> fputc(chr, F)
1862 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1863 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001864 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001865 }
1866
1867 if (FormatStr[1] == 's') {
1868 // fprintf(F, "%s", str) --> fputs(str, F)
1869 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1870 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001871 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001872 }
1873 return nullptr;
1874}
1875
1876Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1877 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001878 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001879 if (Value *V = optimizeFPrintFString(CI, B)) {
1880 return V;
1881 }
1882
1883 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1884 // floating point arguments.
David L. Jonesd21529f2017-01-23 23:16:46 +00001885 if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001886 Module *M = B.GetInsertBlock()->getParent()->getParent();
1887 Constant *FIPrintFFn =
1888 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1889 CallInst *New = cast<CallInst>(CI->clone());
1890 New->setCalledFunction(FIPrintFFn);
1891 B.Insert(New);
1892 return New;
1893 }
1894 return nullptr;
1895}
1896
1897Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1898 optimizeErrorReporting(CI, B, 3);
1899
Chris Bienemanad070d02014-09-17 20:55:46 +00001900 // Get the element size and count.
1901 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1902 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1903 if (!SizeC || !CountC)
1904 return nullptr;
1905 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1906
1907 // If this is writing zero records, remove the call (it's a noop).
1908 if (Bytes == 0)
1909 return ConstantInt::get(CI->getType(), 0);
1910
1911 // If this is writing one byte, turn it into fputc.
1912 // This optimisation is only valid, if the return value is unused.
1913 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001914 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1915 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001916 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1917 }
1918
1919 return nullptr;
1920}
1921
1922Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1923 optimizeErrorReporting(CI, B, 1);
1924
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001925 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1926 // requires more arguments and thus extra MOVs are required.
1927 if (CI->getParent()->getParent()->optForSize())
1928 return nullptr;
1929
Ahmed Bougachad765a822016-04-27 19:04:35 +00001930 // We can't optimize if return value is used.
1931 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001932 return nullptr;
1933
1934 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1935 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1936 if (!Len)
1937 return nullptr;
1938
1939 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001940 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001941 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001942 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001943 CI->getArgOperand(1), B, DL, TLI);
1944}
1945
1946Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001947 // Check for a constant string.
1948 StringRef Str;
1949 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1950 return nullptr;
1951
1952 if (Str.empty() && CI->use_empty()) {
1953 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001954 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001955 if (CI->use_empty() || !Res)
1956 return Res;
1957 return B.CreateIntCast(Res, CI->getType(), true);
1958 }
1959
1960 return nullptr;
1961}
1962
1963bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001964 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00001965 SmallString<20> FloatFuncName = FuncName;
1966 FloatFuncName += 'f';
1967 if (TLI->getLibFunc(FloatFuncName, Func))
1968 return TLI->has(Func);
1969 return false;
1970}
Meador Inge7fb2f732012-10-13 16:45:32 +00001971
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001972Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1973 IRBuilder<> &Builder) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001974 LibFunc Func;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001975 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001976 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001977 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001978 // Make sure we never change the calling convention.
1979 assert((ignoreCallingConv(Func) ||
Sam Parker214f7bf2016-09-13 12:10:14 +00001980 isCallingConvCCompatible(CI)) &&
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001981 "Optimizing string/memory libcall would change the calling convention");
1982 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00001983 case LibFunc_strcat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001984 return optimizeStrCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001985 case LibFunc_strncat:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001986 return optimizeStrNCat(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001987 case LibFunc_strchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001988 return optimizeStrChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001989 case LibFunc_strrchr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001990 return optimizeStrRChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001991 case LibFunc_strcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001992 return optimizeStrCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001993 case LibFunc_strncmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001994 return optimizeStrNCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001995 case LibFunc_strcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001996 return optimizeStrCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001997 case LibFunc_stpcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001998 return optimizeStpCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00001999 case LibFunc_strncpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002000 return optimizeStrNCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002001 case LibFunc_strlen:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002002 return optimizeStrLen(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002003 case LibFunc_strpbrk:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002004 return optimizeStrPBrk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002005 case LibFunc_strtol:
2006 case LibFunc_strtod:
2007 case LibFunc_strtof:
2008 case LibFunc_strtoul:
2009 case LibFunc_strtoll:
2010 case LibFunc_strtold:
2011 case LibFunc_strtoull:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002012 return optimizeStrTo(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002013 case LibFunc_strspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002014 return optimizeStrSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002015 case LibFunc_strcspn:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002016 return optimizeStrCSpn(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002017 case LibFunc_strstr:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002018 return optimizeStrStr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002019 case LibFunc_memchr:
Benjamin Kramer691363e2015-03-21 15:36:21 +00002020 return optimizeMemChr(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002021 case LibFunc_memcmp:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002022 return optimizeMemCmp(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002023 case LibFunc_memcpy:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002024 return optimizeMemCpy(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002025 case LibFunc_memmove:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002026 return optimizeMemMove(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002027 case LibFunc_memset:
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002028 return optimizeMemSet(CI, Builder);
2029 default:
2030 break;
2031 }
2032 }
2033 return nullptr;
2034}
2035
Chris Bienemanad070d02014-09-17 20:55:46 +00002036Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2037 if (CI->isNoBuiltin())
2038 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002039
David L. Jonesd21529f2017-01-23 23:16:46 +00002040 LibFunc Func;
Meador Inge20255ef2013-03-12 00:08:29 +00002041 Function *Callee = CI->getCalledFunction();
2042 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00002043
2044 SmallVector<OperandBundleDef, 2> OpBundles;
2045 CI->getOperandBundlesAsDefs(OpBundles);
2046 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002047 bool isCallingConvC = isCallingConvCCompatible(CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002048
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002049 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00002050 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2051 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00002052 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00002053 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002054
Sanjay Patel848309d2014-10-23 21:52:45 +00002055 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002056 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002057 if (!isCallingConvC)
2058 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002059 switch (II->getIntrinsicID()) {
2060 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002061 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002062 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002063 return optimizeExp2(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002064 case Intrinsic::log:
2065 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002066 case Intrinsic::sqrt:
2067 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00002068 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00002069 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002070 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002071 }
2072 }
2073
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002074 // Also try to simplify calls to fortified library functions.
2075 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2076 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002077 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002078 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2079 // Use an IR Builder from SimplifiedCI if available instead of CI
2080 // to guarantee we reach all uses we might replace later on.
2081 IRBuilder<> TmpBuilder(SimplifiedCI);
2082 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002083 // If we were able to further simplify, remove the now redundant call.
2084 SimplifiedCI->replaceAllUsesWith(V);
2085 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002086 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002087 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002088 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002089 return SimplifiedFortifiedCI;
2090 }
2091
Meador Inge20255ef2013-03-12 00:08:29 +00002092 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002093 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002094 // We never change the calling convention.
2095 if (!ignoreCallingConv(Func) && !isCallingConvC)
2096 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002097 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2098 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002099 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002100 case LibFunc_cosf:
2101 case LibFunc_cos:
2102 case LibFunc_cosl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002103 return optimizeCos(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002104 case LibFunc_sinpif:
2105 case LibFunc_sinpi:
2106 case LibFunc_cospif:
2107 case LibFunc_cospi:
Chris Bienemanad070d02014-09-17 20:55:46 +00002108 return optimizeSinCosPi(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002109 case LibFunc_powf:
2110 case LibFunc_pow:
2111 case LibFunc_powl:
Chris Bienemanad070d02014-09-17 20:55:46 +00002112 return optimizePow(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002113 case LibFunc_exp2l:
2114 case LibFunc_exp2:
2115 case LibFunc_exp2f:
Chris Bienemanad070d02014-09-17 20:55:46 +00002116 return optimizeExp2(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002117 case LibFunc_fabsf:
2118 case LibFunc_fabs:
2119 case LibFunc_fabsl:
Matt Arsenault954a6242017-01-23 23:55:08 +00002120 return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
David L. Jonesd21529f2017-01-23 23:16:46 +00002121 case LibFunc_sqrtf:
2122 case LibFunc_sqrt:
2123 case LibFunc_sqrtl:
Sanjay Patelc699a612014-10-16 18:48:17 +00002124 return optimizeSqrt(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002125 case LibFunc_ffs:
2126 case LibFunc_ffsl:
2127 case LibFunc_ffsll:
Chris Bienemanad070d02014-09-17 20:55:46 +00002128 return optimizeFFS(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002129 case LibFunc_fls:
2130 case LibFunc_flsl:
2131 case LibFunc_flsll:
Davide Italiano85ad36b2016-12-15 23:45:11 +00002132 return optimizeFls(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002133 case LibFunc_abs:
2134 case LibFunc_labs:
2135 case LibFunc_llabs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002136 return optimizeAbs(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002137 case LibFunc_isdigit:
Chris Bienemanad070d02014-09-17 20:55:46 +00002138 return optimizeIsDigit(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002139 case LibFunc_isascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002140 return optimizeIsAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002141 case LibFunc_toascii:
Chris Bienemanad070d02014-09-17 20:55:46 +00002142 return optimizeToAscii(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002143 case LibFunc_printf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002144 return optimizePrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002145 case LibFunc_sprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002146 return optimizeSPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002147 case LibFunc_fprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002148 return optimizeFPrintF(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002149 case LibFunc_fwrite:
Chris Bienemanad070d02014-09-17 20:55:46 +00002150 return optimizeFWrite(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002151 case LibFunc_fputs:
Chris Bienemanad070d02014-09-17 20:55:46 +00002152 return optimizeFPuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002153 case LibFunc_log:
2154 case LibFunc_log10:
2155 case LibFunc_log1p:
2156 case LibFunc_log2:
2157 case LibFunc_logb:
Davide Italianob8b71332015-11-29 20:58:04 +00002158 return optimizeLog(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002159 case LibFunc_puts:
Chris Bienemanad070d02014-09-17 20:55:46 +00002160 return optimizePuts(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002161 case LibFunc_tan:
2162 case LibFunc_tanf:
2163 case LibFunc_tanl:
Davide Italiano51507d22015-11-04 23:36:56 +00002164 return optimizeTan(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002165 case LibFunc_perror:
Chris Bienemanad070d02014-09-17 20:55:46 +00002166 return optimizeErrorReporting(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002167 case LibFunc_vfprintf:
2168 case LibFunc_fiprintf:
Chris Bienemanad070d02014-09-17 20:55:46 +00002169 return optimizeErrorReporting(CI, Builder, 0);
David L. Jonesd21529f2017-01-23 23:16:46 +00002170 case LibFunc_fputc:
Chris Bienemanad070d02014-09-17 20:55:46 +00002171 return optimizeErrorReporting(CI, Builder, 1);
David L. Jonesd21529f2017-01-23 23:16:46 +00002172 case LibFunc_ceil:
Matt Arsenault954a6242017-01-23 23:55:08 +00002173 return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
David L. Jonesd21529f2017-01-23 23:16:46 +00002174 case LibFunc_floor:
Matt Arsenault954a6242017-01-23 23:55:08 +00002175 return replaceUnaryCall(CI, Builder, Intrinsic::floor);
David L. Jonesd21529f2017-01-23 23:16:46 +00002176 case LibFunc_round:
Matt Arsenault954a6242017-01-23 23:55:08 +00002177 return replaceUnaryCall(CI, Builder, Intrinsic::round);
David L. Jonesd21529f2017-01-23 23:16:46 +00002178 case LibFunc_nearbyint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002179 return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002180 case LibFunc_rint:
2181 return replaceUnaryCall(CI, Builder, Intrinsic::rint);
David L. Jonesd21529f2017-01-23 23:16:46 +00002182 case LibFunc_trunc:
Matt Arsenault954a6242017-01-23 23:55:08 +00002183 return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
David L. Jonesd21529f2017-01-23 23:16:46 +00002184 case LibFunc_acos:
2185 case LibFunc_acosh:
2186 case LibFunc_asin:
2187 case LibFunc_asinh:
2188 case LibFunc_atan:
2189 case LibFunc_atanh:
2190 case LibFunc_cbrt:
2191 case LibFunc_cosh:
2192 case LibFunc_exp:
2193 case LibFunc_exp10:
2194 case LibFunc_expm1:
2195 case LibFunc_sin:
2196 case LibFunc_sinh:
2197 case LibFunc_tanh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002198 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2199 return optimizeUnaryDoubleFP(CI, Builder, true);
2200 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002201 case LibFunc_copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002202 if (hasFloatVersion(FuncName))
2203 return optimizeBinaryDoubleFP(CI, Builder);
2204 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00002205 case LibFunc_fminf:
2206 case LibFunc_fmin:
2207 case LibFunc_fminl:
2208 case LibFunc_fmaxf:
2209 case LibFunc_fmax:
2210 case LibFunc_fmaxl:
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002211 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002212 default:
2213 return nullptr;
2214 }
Meador Inge20255ef2013-03-12 00:08:29 +00002215 }
Craig Topperf40110f2014-04-25 05:29:35 +00002216 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002217}
2218
Chandler Carruth92803822015-01-21 02:11:59 +00002219LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002220 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002221 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002222 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002223 Replacer(Replacer) {}
2224
2225void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2226 // Indirect through the replacer used in this instance.
2227 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002228}
2229
Meador Ingedfb08a22013-06-20 19:48:07 +00002230// TODO:
2231// Additional cases that we need to add to this file:
2232//
2233// cbrt:
2234// * cbrt(expN(X)) -> expN(x/3)
2235// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002236// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002237//
2238// exp, expf, expl:
2239// * exp(log(x)) -> x
2240//
2241// log, logf, logl:
2242// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002243// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002244// * log(exp10(y)) -> y*log(10)
2245// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002246//
Meador Ingedfb08a22013-06-20 19:48:07 +00002247// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002248// * pow(sqrt(x),y) -> pow(x,y*0.5)
2249// * pow(pow(x,y),z)-> pow(x,y*z)
2250//
Meador Ingedfb08a22013-06-20 19:48:07 +00002251// signbit:
2252// * signbit(cnst) -> cnst'
2253// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2254//
2255// sqrt, sqrtf, sqrtl:
2256// * sqrt(expN(x)) -> expN(x*0.5)
2257// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2258// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2259//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002260
2261//===----------------------------------------------------------------------===//
2262// Fortified Library Call Optimizations
2263//===----------------------------------------------------------------------===//
2264
2265bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2266 unsigned ObjSizeOp,
2267 unsigned SizeOp,
2268 bool isString) {
2269 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2270 return true;
2271 if (ConstantInt *ObjSizeCI =
2272 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2273 if (ObjSizeCI->isAllOnesValue())
2274 return true;
2275 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2276 if (OnlyLowerUnknownSize)
2277 return false;
2278 if (isString) {
2279 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2280 // If the length is 0 we don't know how long it is and so we can't
2281 // remove the check.
2282 if (Len == 0)
2283 return false;
2284 return ObjSizeCI->getZExtValue() >= Len;
2285 }
2286 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2287 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2288 }
2289 return false;
2290}
2291
Sanjay Pateld707db92015-12-31 16:10:49 +00002292Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2293 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002294 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2295 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002296 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002297 return CI->getArgOperand(0);
2298 }
2299 return nullptr;
2300}
2301
Sanjay Pateld707db92015-12-31 16:10:49 +00002302Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2303 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002304 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2305 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002306 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002307 return CI->getArgOperand(0);
2308 }
2309 return nullptr;
2310}
2311
Sanjay Pateld707db92015-12-31 16:10:49 +00002312Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2313 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002314 // TODO: Try foldMallocMemset() here.
2315
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002316 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2317 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2318 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2319 return CI->getArgOperand(0);
2320 }
2321 return nullptr;
2322}
2323
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002324Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2325 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002326 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002327 Function *Callee = CI->getCalledFunction();
2328 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002329 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002330 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2331 *ObjSize = CI->getArgOperand(2);
2332
2333 // __stpcpy_chk(x,x,...) -> x+strlen(x)
David L. Jonesd21529f2017-01-23 23:16:46 +00002334 if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002335 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002336 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002337 }
2338
2339 // If a) we don't have any length information, or b) we know this will
2340 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2341 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2342 // TODO: It might be nice to get a maximum length out of the possible
2343 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002344 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002345 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002346
David Blaikie65fab6d2015-04-03 21:32:06 +00002347 if (OnlyLowerUnknownSize)
2348 return nullptr;
2349
2350 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2351 uint64_t Len = GetStringLength(Src);
2352 if (Len == 0)
2353 return nullptr;
2354
2355 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2356 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002357 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002358 // If the function was an __stpcpy_chk, and we were able to fold it into
2359 // a __memcpy_chk, we still need to return the correct end pointer.
David L. Jonesd21529f2017-01-23 23:16:46 +00002360 if (Ret && Func == LibFunc_stpcpy_chk)
David Blaikie65fab6d2015-04-03 21:32:06 +00002361 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2362 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002363}
2364
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002365Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2366 IRBuilder<> &B,
David L. Jonesd21529f2017-01-23 23:16:46 +00002367 LibFunc Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002368 Function *Callee = CI->getCalledFunction();
2369 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002370 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002371 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002372 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002373 return Ret;
2374 }
2375 return nullptr;
2376}
2377
2378Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002379 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2380 // Some clang users checked for _chk libcall availability using:
2381 // __has_builtin(__builtin___memcpy_chk)
2382 // When compiling with -fno-builtin, this is always true.
2383 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2384 // end up with fortified libcalls, which isn't acceptable in a freestanding
2385 // environment which only provides their non-fortified counterparts.
2386 //
2387 // Until we change clang and/or teach external users to check for availability
2388 // differently, disregard the "nobuiltin" attribute and TLI::has.
2389 //
2390 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002391
David L. Jonesd21529f2017-01-23 23:16:46 +00002392 LibFunc Func;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002393 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002394
2395 SmallVector<OperandBundleDef, 2> OpBundles;
2396 CI->getOperandBundlesAsDefs(OpBundles);
2397 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Sam Parker214f7bf2016-09-13 12:10:14 +00002398 bool isCallingConvC = isCallingConvCCompatible(CI);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002399
Ahmed Bougachad765a822016-04-27 19:04:35 +00002400 // First, check that this is a known library functions and that the prototype
2401 // is correct.
2402 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002403 return nullptr;
2404
2405 // We never change the calling convention.
2406 if (!ignoreCallingConv(Func) && !isCallingConvC)
2407 return nullptr;
2408
2409 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002410 case LibFunc_memcpy_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002411 return optimizeMemCpyChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002412 case LibFunc_memmove_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002413 return optimizeMemMoveChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002414 case LibFunc_memset_chk:
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002415 return optimizeMemSetChk(CI, Builder);
David L. Jonesd21529f2017-01-23 23:16:46 +00002416 case LibFunc_stpcpy_chk:
2417 case LibFunc_strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002418 return optimizeStrpCpyChk(CI, Builder, Func);
David L. Jonesd21529f2017-01-23 23:16:46 +00002419 case LibFunc_stpncpy_chk:
2420 case LibFunc_strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002421 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002422 default:
2423 break;
2424 }
2425 return nullptr;
2426}
2427
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002428FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2429 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2430 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}