blob: 6eafc44a52022798def119b9ed7bffa2d37f2178 [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"
Meador Ingedf796f82012-10-13 16:45:24 +000033#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000034#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000035
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000040 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000042
Sanjay Patela92fa442014-10-22 15:29:23 +000043static cl::opt<bool>
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
45 cl::init(false),
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
48
49
Meador Ingedf796f82012-10-13 16:45:24 +000050//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000051// Helper Functions
52//===----------------------------------------------------------------------===//
53
Chris Bienemanad070d02014-09-17 20:55:46 +000054static bool ignoreCallingConv(LibFunc::Func Func) {
Davide Italianob883b012015-11-12 23:39:00 +000055 return Func == LibFunc::abs || Func == LibFunc::labs ||
56 Func == LibFunc::llabs || Func == LibFunc::strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000057}
58
Sanjay Pateld707db92015-12-31 16:10:49 +000059/// Return true if it only matters that the value is equal or not-equal to zero.
Meador Inged589ac62012-10-31 03:33:06 +000060static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000061 for (User *U : V->users()) {
62 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000063 if (IC->isEquality())
64 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
65 if (C->isNullValue())
66 continue;
67 // Unknown instruction.
68 return false;
69 }
70 return true;
71}
72
Sanjay Pateld707db92015-12-31 16:10:49 +000073/// Return true if it is only used in equality comparisons with With.
Meador Inge56edbc92012-11-11 03:51:48 +000074static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000075 for (User *U : V->users()) {
76 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000077 if (IC->isEquality() && IC->getOperand(1) == With)
78 continue;
79 // Unknown instruction.
80 return false;
81 }
82 return true;
83}
84
Meador Inge08ca1152012-11-26 20:37:20 +000085static bool callHasFloatingPointArgument(const CallInst *CI) {
David Majnemer0a16c222016-08-11 21:15:00 +000086 return any_of(CI->operands(), [](const Use &OI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +000087 return OI->getType()->isFloatingPointTy();
88 });
Meador Inge08ca1152012-11-26 20:37:20 +000089}
90
Benjamin Kramer2702caa2013-08-31 18:19:35 +000091/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000092/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000093static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
94 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
95 LibFunc::Func LongDoubleFn) {
96 switch (Ty->getTypeID()) {
97 case Type::FloatTyID:
98 return TLI->has(FloatFn);
99 case Type::DoubleTyID:
100 return TLI->has(DoubleFn);
101 default:
102 return TLI->has(LongDoubleFn);
103 }
104}
105
Meador Inged589ac62012-10-31 03:33:06 +0000106//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000107// String and Memory Library Call Optimizations
108//===----------------------------------------------------------------------===//
109
Chris Bienemanad070d02014-09-17 20:55:46 +0000110Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000111 // Extract some information from the instruction
112 Value *Dst = CI->getArgOperand(0);
113 Value *Src = CI->getArgOperand(1);
114
115 // See if we can get the length of the input string.
116 uint64_t Len = GetStringLength(Src);
117 if (Len == 0)
118 return nullptr;
119 --Len; // Unbias length.
120
121 // Handle the simple, do-nothing case: strcat(x, "") -> x
122 if (Len == 0)
123 return Dst;
124
Chris Bienemanad070d02014-09-17 20:55:46 +0000125 return emitStrLenMemCpy(Src, Dst, Len, B);
126}
127
128Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
129 IRBuilder<> &B) {
130 // We need to find the end of the destination string. That's where the
131 // memory is to be moved to. We just generate a call to strlen.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000132 Value *DstLen = emitStrLen(Dst, B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000133 if (!DstLen)
134 return nullptr;
135
136 // Now that we have the destination's length, we must index into the
137 // destination's pointer to get the actual memcpy destination (end of
138 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000139 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000140
141 // We have enough information to now generate the memcpy call to do the
142 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 B.CreateMemCpy(CpyDst, Src,
144 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000145 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000146 return Dst;
147}
148
149Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
Sanjay Pateld707db92015-12-31 16:10:49 +0000150 // Extract some information from the instruction.
Chris Bienemanad070d02014-09-17 20:55:46 +0000151 Value *Dst = CI->getArgOperand(0);
152 Value *Src = CI->getArgOperand(1);
153 uint64_t Len;
154
Sanjay Pateld707db92015-12-31 16:10:49 +0000155 // We don't do anything if length is not constant.
Chris Bienemanad070d02014-09-17 20:55:46 +0000156 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
157 Len = LengthArg->getZExtValue();
158 else
159 return nullptr;
160
161 // See if we can get the length of the input string.
162 uint64_t SrcLen = GetStringLength(Src);
163 if (SrcLen == 0)
164 return nullptr;
165 --SrcLen; // Unbias length.
166
167 // Handle the simple, do-nothing cases:
168 // strncat(x, "", c) -> x
169 // strncat(x, c, 0) -> x
170 if (SrcLen == 0 || Len == 0)
171 return Dst;
172
Sanjay Pateld707db92015-12-31 16:10:49 +0000173 // We don't optimize this case.
Chris Bienemanad070d02014-09-17 20:55:46 +0000174 if (Len < SrcLen)
175 return nullptr;
176
177 // strncat(x, s, c) -> strcat(x, s)
Sanjay Pateld707db92015-12-31 16:10:49 +0000178 // s is constant so the strcat can be optimized further.
Chris Bienemanad070d02014-09-17 20:55:46 +0000179 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
180}
181
182Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
183 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000184 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +0000185 Value *SrcStr = CI->getArgOperand(0);
186
187 // If the second operand is non-constant, see if we can compute the length
188 // of the input string and turn this into memchr.
189 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
190 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000191 uint64_t Len = GetStringLength(SrcStr);
192 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
193 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000194
Sanjay Pateld3112a52016-01-19 19:46:10 +0000195 return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000196 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
197 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000198 }
199
Chris Bienemanad070d02014-09-17 20:55:46 +0000200 // Otherwise, the character is a constant, see if the first argument is
201 // a string literal. If so, we can constant fold.
202 StringRef Str;
203 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000204 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000205 return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
Sanjay Pateld707db92015-12-31 16:10:49 +0000206 "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000207 return nullptr;
208 }
209
210 // Compute the offset, make sure to handle the case when we're searching for
211 // zero (a weird way to spell strlen).
212 size_t I = (0xFF & CharC->getSExtValue()) == 0
213 ? Str.size()
214 : Str.find(CharC->getSExtValue());
215 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
216 return Constant::getNullValue(CI->getType());
217
218 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000219 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000220}
221
222Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000223 Value *SrcStr = CI->getArgOperand(0);
224 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
225
226 // Cannot fold anything if we're not looking for a constant.
227 if (!CharC)
228 return nullptr;
229
230 StringRef Str;
231 if (!getConstantStringInfo(SrcStr, Str)) {
232 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 if (CharC->isZero())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000234 return emitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000235 return nullptr;
236 }
237
238 // Compute the offset.
239 size_t I = (0xFF & CharC->getSExtValue()) == 0
240 ? Str.size()
241 : Str.rfind(CharC->getSExtValue());
242 if (I == StringRef::npos) // Didn't find the char. Return null.
243 return Constant::getNullValue(CI->getType());
244
245 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000246 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000247}
248
249Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000250 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
251 if (Str1P == Str2P) // strcmp(x,x) -> 0
252 return ConstantInt::get(CI->getType(), 0);
253
254 StringRef Str1, Str2;
255 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
256 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
257
258 // strcmp(x, y) -> cnst (if both x and y are constant strings)
259 if (HasStr1 && HasStr2)
260 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
261
262 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
263 return B.CreateNeg(
264 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
265
266 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
267 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
268
269 // strcmp(P, "x") -> memcmp(P, "x", 2)
270 uint64_t Len1 = GetStringLength(Str1P);
271 uint64_t Len2 = GetStringLength(Str2P);
272 if (Len1 && Len2) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000273 return emitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000274 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000275 std::min(Len1, Len2)),
276 B, DL, TLI);
277 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000278
Chris Bienemanad070d02014-09-17 20:55:46 +0000279 return nullptr;
280}
281
282Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000283 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
284 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
285 return ConstantInt::get(CI->getType(), 0);
286
287 // Get the length argument if it is constant.
288 uint64_t Length;
289 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
290 Length = LengthArg->getZExtValue();
291 else
292 return nullptr;
293
294 if (Length == 0) // strncmp(x,y,0) -> 0
295 return ConstantInt::get(CI->getType(), 0);
296
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000298 return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000299
300 StringRef Str1, Str2;
301 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
302 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
303
304 // strncmp(x, y) -> cnst (if both x and y are constant strings)
305 if (HasStr1 && HasStr2) {
306 StringRef SubStr1 = Str1.substr(0, Length);
307 StringRef SubStr2 = Str2.substr(0, Length);
308 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
309 }
310
311 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
312 return B.CreateNeg(
313 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
314
315 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
316 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
317
318 return nullptr;
319}
320
321Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000322 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
323 if (Dst == Src) // strcpy(x,x) -> x
324 return Src;
325
Chris Bienemanad070d02014-09-17 20:55:46 +0000326 // See if we can get the length of the input string.
327 uint64_t Len = GetStringLength(Src);
328 if (Len == 0)
329 return nullptr;
330
331 // We have enough information to now generate the memcpy call to do the
332 // copy for us. Make a memcpy to copy the nul byte with align = 1.
333 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000334 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000335 return Dst;
336}
337
338Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
339 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000340 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
341 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000342 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000343 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000344 }
345
346 // See if we can get the length of the input string.
347 uint64_t Len = GetStringLength(Src);
348 if (Len == 0)
349 return nullptr;
350
Davide Italianob7487e62015-11-02 23:07:14 +0000351 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Sanjay Pateld707db92015-12-31 16:10:49 +0000353 Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
354 ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000355
356 // We have enough information to now generate the memcpy call to do the
357 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000358 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000359 return DstEnd;
360}
361
362Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
363 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000364 Value *Dst = CI->getArgOperand(0);
365 Value *Src = CI->getArgOperand(1);
366 Value *LenOp = CI->getArgOperand(2);
367
368 // See if we can get the length of the input string.
369 uint64_t SrcLen = GetStringLength(Src);
370 if (SrcLen == 0)
371 return nullptr;
372 --SrcLen;
373
374 if (SrcLen == 0) {
375 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
376 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000377 return Dst;
378 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000379
Chris Bienemanad070d02014-09-17 20:55:46 +0000380 uint64_t Len;
381 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
382 Len = LengthArg->getZExtValue();
383 else
384 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000385
Chris Bienemanad070d02014-09-17 20:55:46 +0000386 if (Len == 0)
387 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000388
Chris Bienemanad070d02014-09-17 20:55:46 +0000389 // Let strncpy handle the zero padding
390 if (Len > SrcLen + 1)
391 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000392
Davide Italianob7487e62015-11-02 23:07:14 +0000393 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000394 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000395 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000396
Chris Bienemanad070d02014-09-17 20:55:46 +0000397 return Dst;
398}
Meador Inge7fb2f732012-10-13 16:45:32 +0000399
Chris Bienemanad070d02014-09-17 20:55:46 +0000400Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000401 Value *Src = CI->getArgOperand(0);
402
403 // Constant folding: strlen("xyz") -> 3
404 if (uint64_t Len = GetStringLength(Src))
405 return ConstantInt::get(CI->getType(), Len - 1);
406
David L Kreitzer752c1442016-04-13 14:31:06 +0000407 // If s is a constant pointer pointing to a string literal, we can fold
408 // strlen(s + x) to strlen(s) - x, when x is known to be in the range
409 // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
410 // We only try to simplify strlen when the pointer s points to an array
411 // of i8. Otherwise, we would need to scale the offset x before doing the
412 // subtraction. This will make the optimization more complex, and it's not
413 // very useful because calling strlen for a pointer of other types is
414 // very uncommon.
415 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
416 if (!isGEPBasedOnPointerToString(GEP))
417 return nullptr;
418
419 StringRef Str;
420 if (getConstantStringInfo(GEP->getOperand(0), Str, 0, false)) {
421 size_t NullTermIdx = Str.find('\0');
422
423 // If the string does not have '\0', leave it to strlen to compute
424 // its length.
425 if (NullTermIdx == StringRef::npos)
426 return nullptr;
427
428 Value *Offset = GEP->getOperand(2);
429 unsigned BitWidth = Offset->getType()->getIntegerBitWidth();
430 APInt KnownZero(BitWidth, 0);
431 APInt KnownOne(BitWidth, 0);
432 computeKnownBits(Offset, KnownZero, KnownOne, DL, 0, nullptr, CI,
433 nullptr);
434 KnownZero.flipAllBits();
435 size_t ArrSize =
436 cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
437
438 // KnownZero's bits are flipped, so zeros in KnownZero now represent
439 // bits known to be zeros in Offset, and ones in KnowZero represent
440 // bits unknown in Offset. Therefore, Offset is known to be in range
441 // [0, NullTermIdx] when the flipped KnownZero is non-negative and
442 // unsigned-less-than NullTermIdx.
443 //
444 // If Offset is not provably in the range [0, NullTermIdx], we can still
445 // optimize if we can prove that the program has undefined behavior when
446 // Offset is outside that range. That is the case when GEP->getOperand(0)
447 // is a pointer to an object whose memory extent is NullTermIdx+1.
448 if ((KnownZero.isNonNegative() && KnownZero.ule(NullTermIdx)) ||
449 (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
450 NullTermIdx == ArrSize - 1))
451 return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
452 Offset);
453 }
454
455 return nullptr;
456 }
457
Chris Bienemanad070d02014-09-17 20:55:46 +0000458 // strlen(x?"foo":"bars") --> x ? 3 : 4
459 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
460 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
461 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
462 if (LenTrue && LenFalse) {
463 Function *Caller = CI->getParent()->getParent();
464 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
465 SI->getDebugLoc(),
466 "folded strlen(select) to select of constants");
467 return B.CreateSelect(SI->getCondition(),
468 ConstantInt::get(CI->getType(), LenTrue - 1),
469 ConstantInt::get(CI->getType(), LenFalse - 1));
470 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000471 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000472
Chris Bienemanad070d02014-09-17 20:55:46 +0000473 // strlen(x) != 0 --> *x != 0
474 // strlen(x) == 0 --> *x == 0
475 if (isOnlyUsedInZeroEqualityComparison(CI))
476 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000477
Chris Bienemanad070d02014-09-17 20:55:46 +0000478 return nullptr;
479}
Meador Inge17418502012-10-13 16:45:37 +0000480
Chris Bienemanad070d02014-09-17 20:55:46 +0000481Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000482 StringRef S1, S2;
483 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
484 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000485
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000486 // strpbrk(s, "") -> nullptr
487 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000488 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
489 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000490
Chris Bienemanad070d02014-09-17 20:55:46 +0000491 // Constant folding.
492 if (HasS1 && HasS2) {
493 size_t I = S1.find_first_of(S2);
494 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000495 return Constant::getNullValue(CI->getType());
496
Sanjay Pateld707db92015-12-31 16:10:49 +0000497 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
498 "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000499 }
Meador Inge17418502012-10-13 16:45:37 +0000500
Chris Bienemanad070d02014-09-17 20:55:46 +0000501 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000502 if (HasS2 && S2.size() == 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000503 return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000504
505 return nullptr;
506}
507
508Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000509 Value *EndPtr = CI->getArgOperand(1);
510 if (isa<ConstantPointerNull>(EndPtr)) {
511 // With a null EndPtr, this function won't capture the main argument.
512 // It would be readonly too, except that it still may write to errno.
513 CI->addAttribute(1, Attribute::NoCapture);
514 }
515
516 return nullptr;
517}
518
519Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000520 StringRef S1, S2;
521 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
522 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
523
524 // strspn(s, "") -> 0
525 // strspn("", s) -> 0
526 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
527 return Constant::getNullValue(CI->getType());
528
529 // Constant folding.
530 if (HasS1 && HasS2) {
531 size_t Pos = S1.find_first_not_of(S2);
532 if (Pos == StringRef::npos)
533 Pos = S1.size();
534 return ConstantInt::get(CI->getType(), Pos);
535 }
536
537 return nullptr;
538}
539
540Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 StringRef S1, S2;
542 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
543 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
544
545 // strcspn("", s) -> 0
546 if (HasS1 && S1.empty())
547 return Constant::getNullValue(CI->getType());
548
549 // Constant folding.
550 if (HasS1 && HasS2) {
551 size_t Pos = S1.find_first_of(S2);
552 if (Pos == StringRef::npos)
553 Pos = S1.size();
554 return ConstantInt::get(CI->getType(), Pos);
555 }
556
557 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000558 if (HasS2 && S2.empty())
Sanjay Pateld3112a52016-01-19 19:46:10 +0000559 return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000560
561 return nullptr;
562}
563
564Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000565 // fold strstr(x, x) -> x.
566 if (CI->getArgOperand(0) == CI->getArgOperand(1))
567 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
568
569 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000570 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000571 Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000572 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000573 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +0000574 Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 StrLen, B, DL, TLI);
576 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000577 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000578 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
579 ICmpInst *Old = cast<ICmpInst>(*UI++);
580 Value *Cmp =
581 B.CreateICmp(Old->getPredicate(), StrNCmp,
582 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
583 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000584 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000585 return CI;
586 }
Meador Inge17418502012-10-13 16:45:37 +0000587
Chris Bienemanad070d02014-09-17 20:55:46 +0000588 // See if either input string is a constant string.
589 StringRef SearchStr, ToFindStr;
590 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
591 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
592
593 // fold strstr(x, "") -> x.
594 if (HasStr2 && ToFindStr.empty())
595 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
596
597 // If both strings are known, constant fold it.
598 if (HasStr1 && HasStr2) {
599 size_t Offset = SearchStr.find(ToFindStr);
600
601 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000602 return Constant::getNullValue(CI->getType());
603
Chris Bienemanad070d02014-09-17 20:55:46 +0000604 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Sanjay Pateld3112a52016-01-19 19:46:10 +0000605 Value *Result = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +0000606 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
607 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000608 }
Meador Inge17418502012-10-13 16:45:37 +0000609
Chris Bienemanad070d02014-09-17 20:55:46 +0000610 // fold strstr(x, "y") -> strchr(x, 'y').
611 if (HasStr2 && ToFindStr.size() == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000612 Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000613 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
614 }
615 return nullptr;
616}
Meador Inge40b6fac2012-10-15 03:47:37 +0000617
Benjamin Kramer691363e2015-03-21 15:36:21 +0000618Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
Benjamin Kramer691363e2015-03-21 15:36:21 +0000619 Value *SrcStr = CI->getArgOperand(0);
620 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
621 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
622
623 // memchr(x, y, 0) -> null
624 if (LenC && LenC->isNullValue())
625 return Constant::getNullValue(CI->getType());
626
Benjamin Kramer7857d722015-03-21 21:09:33 +0000627 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000628 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000629 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000630 return nullptr;
631
632 // Truncate the string to LenC. If Str is smaller than LenC we will still only
633 // scan the string, as reading past the end of it is undefined and we can just
634 // return null if we don't find the char.
635 Str = Str.substr(0, LenC->getZExtValue());
636
Benjamin Kramer7857d722015-03-21 21:09:33 +0000637 // If the char is variable but the input str and length are not we can turn
638 // this memchr call into a simple bit field test. Of course this only works
639 // when the return value is only checked against null.
640 //
641 // It would be really nice to reuse switch lowering here but we can't change
642 // the CFG at this point.
643 //
644 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
645 // after bounds check.
646 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000647 unsigned char Max =
648 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
649 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000650
651 // Make sure the bit field we're about to create fits in a register on the
652 // target.
653 // FIXME: On a 64 bit architecture this prevents us from using the
654 // interesting range of alpha ascii chars. We could do better by emitting
655 // two bitfields or shifting the range by 64 if no lower chars are used.
656 if (!DL.fitsInLegalInteger(Max + 1))
657 return nullptr;
658
659 // For the bit field use a power-of-2 type with at least 8 bits to avoid
660 // creating unnecessary illegal types.
661 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
662
663 // Now build the bit field.
664 APInt Bitfield(Width, 0);
665 for (char C : Str)
666 Bitfield.setBit((unsigned char)C);
667 Value *BitfieldC = B.getInt(Bitfield);
668
669 // First check that the bit field access is within bounds.
670 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
671 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
672 "memchr.bounds");
673
674 // Create code that checks if the given bit is set in the field.
675 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
676 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
677
678 // Finally merge both checks and cast to pointer type. The inttoptr
679 // implicitly zexts the i1 to intptr type.
680 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
681 }
682
683 // Check if all arguments are constants. If so, we can constant fold.
684 if (!CharC)
685 return nullptr;
686
Benjamin Kramer691363e2015-03-21 15:36:21 +0000687 // Compute the offset.
688 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
689 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
690 return Constant::getNullValue(CI->getType());
691
692 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000693 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000694}
695
Chris Bienemanad070d02014-09-17 20:55:46 +0000696Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000697 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000698
Chris Bienemanad070d02014-09-17 20:55:46 +0000699 if (LHS == RHS) // memcmp(s,s,x) -> 0
700 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000701
Chris Bienemanad070d02014-09-17 20:55:46 +0000702 // Make sure we have a constant length.
703 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
704 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 uint64_t Len = LenC->getZExtValue();
707
708 if (Len == 0) // memcmp(s1,s2,0) -> 0
709 return Constant::getNullValue(CI->getType());
710
711 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
712 if (Len == 1) {
Sanjay Pateld3112a52016-01-19 19:46:10 +0000713 Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000714 CI->getType(), "lhsv");
Sanjay Pateld3112a52016-01-19 19:46:10 +0000715 Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
Chris Bienemanad070d02014-09-17 20:55:46 +0000716 CI->getType(), "rhsv");
717 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000718 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000719
Chad Rosierdc655322015-08-28 18:30:18 +0000720 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
721 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
722
723 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
724 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
725
726 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
727 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
728
729 Type *LHSPtrTy =
730 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
731 Type *RHSPtrTy =
732 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
733
Sanjay Pateld707db92015-12-31 16:10:49 +0000734 Value *LHSV =
735 B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
736 Value *RHSV =
737 B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
Chad Rosierdc655322015-08-28 18:30:18 +0000738
739 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
740 }
741 }
742
Chris Bienemanad070d02014-09-17 20:55:46 +0000743 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
744 StringRef LHSStr, RHSStr;
745 if (getConstantStringInfo(LHS, LHSStr) &&
746 getConstantStringInfo(RHS, RHSStr)) {
747 // Make sure we're not reading out-of-bounds memory.
748 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000749 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000750 // Fold the memcmp and normalize the result. This way we get consistent
751 // results across multiple platforms.
752 uint64_t Ret = 0;
753 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
754 if (Cmp < 0)
755 Ret = -1;
756 else if (Cmp > 0)
757 Ret = 1;
758 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000759 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000760
Chris Bienemanad070d02014-09-17 20:55:46 +0000761 return nullptr;
762}
Meador Inge9a6a1902012-10-31 00:20:56 +0000763
Chris Bienemanad070d02014-09-17 20:55:46 +0000764Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000765 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
766 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000767 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000768 return CI->getArgOperand(0);
769}
Meador Inge05a625a2012-10-31 14:58:26 +0000770
Chris Bienemanad070d02014-09-17 20:55:46 +0000771Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000772 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
773 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000774 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000775 return CI->getArgOperand(0);
776}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000777
Sanjay Patel980b2802016-01-26 16:17:24 +0000778// TODO: Does this belong in BuildLibCalls or should all of those similar
779// functions be moved here?
780static Value *emitCalloc(Value *Num, Value *Size, const AttributeSet &Attrs,
781 IRBuilder<> &B, const TargetLibraryInfo &TLI) {
782 LibFunc::Func Func;
783 if (!TLI.getLibFunc("calloc", Func) || !TLI.has(Func))
784 return nullptr;
785
786 Module *M = B.GetInsertBlock()->getModule();
787 const DataLayout &DL = M->getDataLayout();
788 IntegerType *PtrType = DL.getIntPtrType((B.GetInsertBlock()->getContext()));
789 Value *Calloc = M->getOrInsertFunction("calloc", Attrs, B.getInt8PtrTy(),
790 PtrType, PtrType, nullptr);
791 CallInst *CI = B.CreateCall(Calloc, { Num, Size }, "calloc");
792
793 if (const auto *F = dyn_cast<Function>(Calloc->stripPointerCasts()))
794 CI->setCallingConv(F->getCallingConv());
795
796 return CI;
797}
798
799/// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
800static Value *foldMallocMemset(CallInst *Memset, IRBuilder<> &B,
801 const TargetLibraryInfo &TLI) {
802 // This has to be a memset of zeros (bzero).
803 auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
804 if (!FillValue || FillValue->getZExtValue() != 0)
805 return nullptr;
806
807 // TODO: We should handle the case where the malloc has more than one use.
808 // This is necessary to optimize common patterns such as when the result of
809 // the malloc is checked against null or when a memset intrinsic is used in
810 // place of a memset library call.
811 auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
812 if (!Malloc || !Malloc->hasOneUse())
813 return nullptr;
814
815 // Is the inner call really malloc()?
816 Function *InnerCallee = Malloc->getCalledFunction();
817 LibFunc::Func Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +0000818 if (!TLI.getLibFunc(*InnerCallee, Func) || !TLI.has(Func) ||
Sanjay Patel980b2802016-01-26 16:17:24 +0000819 Func != LibFunc::malloc)
820 return nullptr;
821
Sanjay Patel980b2802016-01-26 16:17:24 +0000822 // The memset must cover the same number of bytes that are malloc'd.
823 if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
824 return nullptr;
825
826 // Replace the malloc with a calloc. We need the data layout to know what the
827 // actual size of a 'size_t' parameter is.
828 B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
829 const DataLayout &DL = Malloc->getModule()->getDataLayout();
830 IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
831 Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
832 Malloc->getArgOperand(0), Malloc->getAttributes(),
833 B, TLI);
834 if (!Calloc)
835 return nullptr;
836
837 Malloc->replaceAllUsesWith(Calloc);
838 Malloc->eraseFromParent();
839
840 return Calloc;
841}
842
Chris Bienemanad070d02014-09-17 20:55:46 +0000843Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +0000844 if (auto *Calloc = foldMallocMemset(CI, B, *TLI))
845 return Calloc;
846
Chris Bienemanad070d02014-09-17 20:55:46 +0000847 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
848 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
849 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
850 return CI->getArgOperand(0);
851}
Meador Inged4825782012-11-11 06:49:03 +0000852
Meador Inge193e0352012-11-13 04:16:17 +0000853//===----------------------------------------------------------------------===//
854// Math Library Optimizations
855//===----------------------------------------------------------------------===//
856
Matthias Braund34e4d22014-12-03 21:46:33 +0000857/// Return a variant of Val with float type.
858/// Currently this works in two cases: If Val is an FPExtension of a float
859/// value to something bigger, simply return the operand.
860/// If Val is a ConstantFP but can be converted to a float ConstantFP without
861/// loss of precision do so.
862static Value *valueHasFloatPrecision(Value *Val) {
863 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
864 Value *Op = Cast->getOperand(0);
865 if (Op->getType()->isFloatTy())
866 return Op;
867 }
868 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
869 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000870 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000871 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000872 &losesInfo);
873 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000874 return ConstantFP::get(Const->getContext(), F);
875 }
876 return nullptr;
877}
878
Sanjay Patel4e971da2016-01-21 18:01:57 +0000879/// Shrink double -> float for unary functions like 'floor'.
880static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
881 bool CheckRetType) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000882 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000883 // We know this libcall has a valid prototype, but we don't know which.
884 if (!CI->getType()->isDoubleTy())
Chris Bienemanad070d02014-09-17 20:55:46 +0000885 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000886
Chris Bienemanad070d02014-09-17 20:55:46 +0000887 if (CheckRetType) {
888 // Check if all the uses for function like 'sin' are converted to float.
889 for (User *U : CI->users()) {
890 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
891 if (!Cast || !Cast->getType()->isFloatTy())
892 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000893 }
Meador Inge193e0352012-11-13 04:16:17 +0000894 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000895
896 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000897 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
898 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000899 return nullptr;
Sanjay Patelaa231142015-12-31 21:52:31 +0000900
901 // Propagate fast-math flags from the existing call to the new call.
902 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000903 B.setFastMathFlags(CI->getFastMathFlags());
Chris Bienemanad070d02014-09-17 20:55:46 +0000904
905 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000906 if (Callee->isIntrinsic()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000907 Module *M = CI->getModule();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000908 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +0000909 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
910 V = B.CreateCall(F, V);
911 } else {
912 // The call is a library call rather than an intrinsic.
Sanjay Pateld3112a52016-01-19 19:46:10 +0000913 V = emitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Sanjay Patel848309d2014-10-23 21:52:45 +0000914 }
915
Chris Bienemanad070d02014-09-17 20:55:46 +0000916 return B.CreateFPExt(V, B.getDoubleTy());
917}
Meador Inge193e0352012-11-13 04:16:17 +0000918
Sanjay Patel4e971da2016-01-21 18:01:57 +0000919/// Shrink double -> float for binary functions like 'fmin/fmax'.
920static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000921 Function *Callee = CI->getCalledFunction();
Ahmed Bougachad765a822016-04-27 19:04:35 +0000922 // We know this libcall has a valid prototype, but we don't know which.
923 if (!CI->getType()->isDoubleTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000924 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000925
Chris Bienemanad070d02014-09-17 20:55:46 +0000926 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +0000927 // or fmin(1.0, (double)floatval), then we convert it to fminf.
928 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
929 if (V1 == nullptr)
930 return nullptr;
931 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
932 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +0000933 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000934
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000935 // Propagate fast-math flags from the existing call to the new call.
936 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +0000937 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patelbee05ca2015-12-31 23:40:59 +0000938
Chris Bienemanad070d02014-09-17 20:55:46 +0000939 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +0000940 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +0000941 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Sanjay Pateld3112a52016-01-19 19:46:10 +0000942 Value *V = emitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
Matthias Braund34e4d22014-12-03 21:46:33 +0000943 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +0000944 return B.CreateFPExt(V, B.getDoubleTy());
945}
946
947Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
948 Function *Callee = CI->getCalledFunction();
949 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +0000950 StringRef Name = Callee->getName();
951 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +0000952 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +0000953
Chris Bienemanad070d02014-09-17 20:55:46 +0000954 // cos(-x) -> cos(x)
955 Value *Op1 = CI->getArgOperand(0);
956 if (BinaryOperator::isFNeg(Op1)) {
957 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
958 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
959 }
960 return Ret;
961}
Bob Wilsond8d92d92013-11-03 06:48:38 +0000962
Weiming Zhao82130722015-12-04 22:00:47 +0000963static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
964 // Multiplications calculated using Addition Chains.
965 // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
966
967 assert(Exp != 0 && "Incorrect exponent 0 not handled");
968
969 if (InnerChain[Exp])
970 return InnerChain[Exp];
971
972 static const unsigned AddChain[33][2] = {
973 {0, 0}, // Unused.
974 {0, 0}, // Unused (base case = pow1).
975 {1, 1}, // Unused (pre-computed).
976 {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
977 {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
978 {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
979 {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
980 {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
981 };
982
983 InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
984 getPow(InnerChain, AddChain[Exp][1], B));
985 return InnerChain[Exp];
986}
987
Chris Bienemanad070d02014-09-17 20:55:46 +0000988Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
989 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +0000990 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +0000991 StringRef Name = Callee->getName();
992 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +0000993 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +0000994
Chris Bienemanad070d02014-09-17 20:55:46 +0000995 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Davide Italiano27da1312016-08-07 20:27:03 +0000996
997 // pow(1.0, x) -> 1.0
998 if (match(Op1, m_SpecificFP(1.0)))
999 return Op1;
1000 // pow(2.0, x) -> llvm.exp2(x)
1001 if (match(Op1, m_SpecificFP(2.0))) {
1002 Value *Exp2 = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::exp2,
1003 CI->getType());
1004 return B.CreateCall(Exp2, Op2, "exp2");
1005 }
1006
1007 // There's no llvm.exp10 intrinsic yet, but, maybe, some day there will
1008 // be one.
Chris Bienemanad070d02014-09-17 20:55:46 +00001009 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001010 // pow(10.0, x) -> exp10(x)
1011 if (Op1C->isExactlyValue(10.0) &&
1012 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1013 LibFunc::exp10l))
Sanjay Pateld3112a52016-01-19 19:46:10 +00001014 return emitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
Chris Bienemanad070d02014-09-17 20:55:46 +00001015 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001016 }
1017
Sanjay Patel6002e782016-01-12 17:30:37 +00001018 // pow(exp(x), y) -> exp(x * y)
Davide Italianoc8a79132015-11-03 20:32:23 +00001019 // pow(exp2(x), y) -> exp2(x * y)
Sanjay Patel6002e782016-01-12 17:30:37 +00001020 // We enable these only with fast-math. Besides rounding differences, the
1021 // transformation changes overflow and underflow behavior quite dramatically.
Davide Italianoc8a79132015-11-03 20:32:23 +00001022 // Example: x = 1000, y = 0.001.
1023 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Sanjay Patel6002e782016-01-12 17:30:37 +00001024 auto *OpC = dyn_cast<CallInst>(Op1);
1025 if (OpC && OpC->hasUnsafeAlgebra() && CI->hasUnsafeAlgebra()) {
1026 LibFunc::Func Func;
1027 Function *OpCCallee = OpC->getCalledFunction();
1028 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1029 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2)) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001030 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001031 B.setFastMathFlags(CI->getFastMathFlags());
Sanjay Patel6002e782016-01-12 17:30:37 +00001032 Value *FMul = B.CreateFMul(OpC->getArgOperand(0), Op2, "mul");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001033 return emitUnaryFloatFnCall(FMul, OpCCallee->getName(), B,
Sanjay Patel6002e782016-01-12 17:30:37 +00001034 OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001035 }
1036 }
1037
Chris Bienemanad070d02014-09-17 20:55:46 +00001038 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1039 if (!Op2C)
1040 return Ret;
1041
1042 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1043 return ConstantFP::get(CI->getType(), 1.0);
1044
1045 if (Op2C->isExactlyValue(0.5) &&
1046 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1047 LibFunc::sqrtl) &&
1048 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1049 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001050
1051 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001052 if (CI->hasUnsafeAlgebra()) {
1053 IRBuilder<>::FastMathFlagGuard Guard(B);
1054 B.setFastMathFlags(CI->getFastMathFlags());
Davide Italiano873219c2016-08-10 06:33:32 +00001055
1056 // Unlike other math intrinsics, sqrt has differerent semantics
1057 // from the libc function. See LangRef for details.
1058 return emitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1059 Callee->getAttributes());
Sanjay Patel53ba88d2016-01-12 19:06:35 +00001060 }
Davide Italianoc5cedd12015-11-18 23:21:32 +00001061
Chris Bienemanad070d02014-09-17 20:55:46 +00001062 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1063 // This is faster than calling pow, and still handles negative zero
1064 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001065 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1066 Value *Inf = ConstantFP::getInfinity(CI->getType());
1067 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Sanjay Pateld3112a52016-01-19 19:46:10 +00001068 Value *Sqrt = emitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001069 Value *FAbs =
Sanjay Pateld3112a52016-01-19 19:46:10 +00001070 emitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001071 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1072 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1073 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001074 }
1075
Chris Bienemanad070d02014-09-17 20:55:46 +00001076 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1077 return Op1;
1078 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1079 return B.CreateFMul(Op1, Op1, "pow2");
1080 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1081 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
Weiming Zhao82130722015-12-04 22:00:47 +00001082
1083 // In -ffast-math, generate repeated fmul instead of generating pow(x, n).
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001084 if (CI->hasUnsafeAlgebra()) {
Weiming Zhao82130722015-12-04 22:00:47 +00001085 APFloat V = abs(Op2C->getValueAPF());
1086 // We limit to a max of 7 fmul(s). Thus max exponent is 32.
1087 // This transformation applies to integer exponents only.
1088 if (V.compare(APFloat(V.getSemantics(), 32.0)) == APFloat::cmpGreaterThan ||
1089 !V.isInteger())
1090 return nullptr;
1091
1092 // We will memoize intermediate products of the Addition Chain.
1093 Value *InnerChain[33] = {nullptr};
1094 InnerChain[1] = Op1;
1095 InnerChain[2] = B.CreateFMul(Op1, Op1);
1096
1097 // We cannot readily convert a non-double type (like float) to a double.
1098 // So we first convert V to something which could be converted to double.
1099 bool ignored;
1100 V.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &ignored);
Sanjay Patel81a63cd2016-01-19 18:15:12 +00001101
1102 // TODO: Should the new instructions propagate the 'fast' flag of the pow()?
Weiming Zhao82130722015-12-04 22:00:47 +00001103 Value *FMul = getPow(InnerChain, V.convertToDouble(), B);
1104 // For negative exponents simply compute the reciprocal.
1105 if (Op2C->isNegative())
1106 FMul = B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), FMul);
1107 return FMul;
1108 }
1109
Chris Bienemanad070d02014-09-17 20:55:46 +00001110 return nullptr;
1111}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001112
Chris Bienemanad070d02014-09-17 20:55:46 +00001113Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1114 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001115 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001116 StringRef Name = Callee->getName();
1117 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001118 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001119
Chris Bienemanad070d02014-09-17 20:55:46 +00001120 Value *Op = CI->getArgOperand(0);
1121 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1122 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1123 LibFunc::Func LdExp = LibFunc::ldexpl;
1124 if (Op->getType()->isFloatTy())
1125 LdExp = LibFunc::ldexpf;
1126 else if (Op->getType()->isDoubleTy())
1127 LdExp = LibFunc::ldexp;
1128
1129 if (TLI->has(LdExp)) {
1130 Value *LdExpArg = nullptr;
1131 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1132 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1133 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1134 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1135 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1136 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1137 }
1138
1139 if (LdExpArg) {
1140 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1141 if (!Op->getType()->isFloatTy())
1142 One = ConstantExpr::getFPExtend(One, Op->getType());
1143
Sanjay Patel0e603fc2016-01-21 22:31:18 +00001144 Module *M = CI->getModule();
Sanjay Patel042aed902016-01-21 22:41:16 +00001145 Value *NewCallee =
Chris Bienemanad070d02014-09-17 20:55:46 +00001146 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001147 Op->getType(), B.getInt32Ty(), nullptr);
Sanjay Patel042aed902016-01-21 22:41:16 +00001148 CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001149 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1150 CI->setCallingConv(F->getCallingConv());
1151
1152 return CI;
1153 }
1154 }
1155 return Ret;
1156}
1157
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001158Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1159 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001160 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001161 StringRef Name = Callee->getName();
1162 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001163 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001164
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001165 Value *Op = CI->getArgOperand(0);
1166 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1167 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1168 if (I->getOpcode() == Instruction::FMul)
1169 if (I->getOperand(0) == I->getOperand(1))
1170 return Op;
1171 }
1172 return Ret;
1173}
1174
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001175Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
Sanjay Patel9beec212016-01-21 22:58:01 +00001176 Function *Callee = CI->getCalledFunction();
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001177 // If we can shrink the call to a float function rather than a double
1178 // function, do that first.
Davide Italianoa3458772015-11-05 19:18:23 +00001179 StringRef Name = Callee->getName();
Sanjay Patelc7ddb7f2016-01-06 00:32:15 +00001180 if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
1181 if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001182 return Ret;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001183
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001184 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001185 FastMathFlags FMF;
Sanjay Patel29095ea2016-01-05 20:46:19 +00001186 if (CI->hasUnsafeAlgebra()) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001187 // Unsafe algebra sets all fast-math-flags to true.
1188 FMF.setUnsafeAlgebra();
1189 } else {
1190 // At a minimum, no-nans-fp-math must be true.
Sanjay Patel29095ea2016-01-05 20:46:19 +00001191 if (!CI->hasNoNaNs())
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001192 return nullptr;
1193 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1194 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001195 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001196 // might be impractical."
1197 FMF.setNoSignedZeros();
1198 FMF.setNoNaNs();
1199 }
Sanjay Patela2528152016-01-12 18:03:37 +00001200 B.setFastMathFlags(FMF);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001201
1202 // We have a relaxed floating-point environment. We can ignore NaN-handling
1203 // and transform to a compare and select. We do not have to consider errno or
1204 // exceptions, because fmin/fmax do not have those.
1205 Value *Op0 = CI->getArgOperand(0);
1206 Value *Op1 = CI->getArgOperand(1);
1207 Value *Cmp = Callee->getName().startswith("fmin") ?
1208 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1209 return B.CreateSelect(Cmp, Op0, Op1);
1210}
1211
Davide Italianob8b71332015-11-29 20:58:04 +00001212Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1213 Function *Callee = CI->getCalledFunction();
1214 Value *Ret = nullptr;
1215 StringRef Name = Callee->getName();
1216 if (UnsafeFPShrink && hasFloatVersion(Name))
1217 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianob8b71332015-11-29 20:58:04 +00001218
Sanjay Patele896ede2016-01-11 23:31:48 +00001219 if (!CI->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001220 return Ret;
1221 Value *Op1 = CI->getArgOperand(0);
1222 auto *OpC = dyn_cast<CallInst>(Op1);
Sanjay Patele896ede2016-01-11 23:31:48 +00001223
1224 // The earlier call must also be unsafe in order to do these transforms.
1225 if (!OpC || !OpC->hasUnsafeAlgebra())
Davide Italianob8b71332015-11-29 20:58:04 +00001226 return Ret;
1227
1228 // log(pow(x,y)) -> y*log(x)
1229 // This is only applicable to log, log2, log10.
1230 if (Name != "log" && Name != "log2" && Name != "log10")
1231 return Ret;
1232
1233 IRBuilder<>::FastMathFlagGuard Guard(B);
1234 FastMathFlags FMF;
1235 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +00001236 B.setFastMathFlags(FMF);
Davide Italianob8b71332015-11-29 20:58:04 +00001237
1238 LibFunc::Func Func;
1239 Function *F = OpC->getCalledFunction();
Davide Italiano0b14f292015-11-29 21:58:56 +00001240 if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
1241 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow))
Davide Italianob8b71332015-11-29 20:58:04 +00001242 return B.CreateFMul(OpC->getArgOperand(1),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001243 emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
Davide Italianob8b71332015-11-29 20:58:04 +00001244 Callee->getAttributes()), "mul");
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001245
1246 // log(exp2(y)) -> y*log(2)
1247 if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
1248 TLI->has(Func) && Func == LibFunc::exp2)
1249 return B.CreateFMul(
1250 OpC->getArgOperand(0),
Sanjay Pateld3112a52016-01-19 19:46:10 +00001251 emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
Davide Italiano1aeed6a2015-11-30 19:36:35 +00001252 Callee->getName(), B, Callee->getAttributes()),
1253 "logmul");
Davide Italianob8b71332015-11-29 20:58:04 +00001254 return Ret;
1255}
1256
Sanjay Patelc699a612014-10-16 18:48:17 +00001257Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1258 Function *Callee = CI->getCalledFunction();
Sanjay Patelc699a612014-10-16 18:48:17 +00001259 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001260 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1261 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001262 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patel683f2972016-01-11 22:34:19 +00001263
1264 if (!CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001265 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001266
Sanjay Patelc2d64612016-01-06 20:52:21 +00001267 Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
1268 if (!I || I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
1269 return Ret;
1270
1271 // We're looking for a repeated factor in a multiplication tree,
1272 // so we can do this fold: sqrt(x * x) -> fabs(x);
Sanjay Patel683f2972016-01-11 22:34:19 +00001273 // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
Sanjay Patelc2d64612016-01-06 20:52:21 +00001274 Value *Op0 = I->getOperand(0);
1275 Value *Op1 = I->getOperand(1);
1276 Value *RepeatOp = nullptr;
1277 Value *OtherOp = nullptr;
1278 if (Op0 == Op1) {
1279 // Simple match: the operands of the multiply are identical.
1280 RepeatOp = Op0;
1281 } else {
1282 // Look for a more complicated pattern: one of the operands is itself
1283 // a multiply, so search for a common factor in that multiply.
1284 // Note: We don't bother looking any deeper than this first level or for
1285 // variations of this pattern because instcombine's visitFMUL and/or the
1286 // reassociation pass should give us this form.
1287 Value *OtherMul0, *OtherMul1;
1288 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1289 // Pattern: sqrt((x * y) * z)
Sanjay Patel6c1ddbb2016-01-11 22:50:36 +00001290 if (OtherMul0 == OtherMul1 &&
1291 cast<Instruction>(Op0)->hasUnsafeAlgebra()) {
Sanjay Patelc2d64612016-01-06 20:52:21 +00001292 // Matched: sqrt((x * x) * z)
1293 RepeatOp = OtherMul0;
1294 OtherOp = Op1;
Sanjay Patelc699a612014-10-16 18:48:17 +00001295 }
1296 }
1297 }
Sanjay Patelc2d64612016-01-06 20:52:21 +00001298 if (!RepeatOp)
1299 return Ret;
1300
1301 // Fast math flags for any created instructions should match the sqrt
1302 // and multiply.
Sanjay Patelc2d64612016-01-06 20:52:21 +00001303 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patela2528152016-01-12 18:03:37 +00001304 B.setFastMathFlags(I->getFastMathFlags());
Sanjay Patel9f67dad2016-01-11 22:35:39 +00001305
Sanjay Patelc2d64612016-01-06 20:52:21 +00001306 // If we found a repeated factor, hoist it out of the square root and
1307 // replace it with the fabs of that factor.
1308 Module *M = Callee->getParent();
1309 Type *ArgType = I->getType();
1310 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1311 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1312 if (OtherOp) {
1313 // If we found a non-repeated factor, we still need to get its square
1314 // root. We then multiply that by the value that was simplified out
1315 // of the square root calculation.
1316 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1317 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1318 return B.CreateFMul(FabsCall, SqrtCall);
1319 }
1320 return FabsCall;
Sanjay Patelc699a612014-10-16 18:48:17 +00001321}
1322
Sanjay Patelcddcd722016-01-06 19:23:35 +00001323// TODO: Generalize to handle any trig function and its inverse.
Davide Italiano51507d22015-11-04 23:36:56 +00001324Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1325 Function *Callee = CI->getCalledFunction();
1326 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001327 StringRef Name = Callee->getName();
1328 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001329 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italiano51507d22015-11-04 23:36:56 +00001330
Davide Italiano51507d22015-11-04 23:36:56 +00001331 Value *Op1 = CI->getArgOperand(0);
1332 auto *OpC = dyn_cast<CallInst>(Op1);
1333 if (!OpC)
1334 return Ret;
1335
Sanjay Patelcddcd722016-01-06 19:23:35 +00001336 // Both calls must allow unsafe optimizations in order to remove them.
1337 if (!CI->hasUnsafeAlgebra() || !OpC->hasUnsafeAlgebra())
1338 return Ret;
1339
Davide Italiano51507d22015-11-04 23:36:56 +00001340 // tan(atan(x)) -> x
1341 // tanf(atanf(x)) -> x
1342 // tanl(atanl(x)) -> x
1343 LibFunc::Func Func;
1344 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001345 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001346 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1347 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1348 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1349 Ret = OpC->getArgOperand(0);
1350 return Ret;
1351}
1352
Sanjay Patel57747212016-01-21 23:38:43 +00001353static bool isTrigLibCall(CallInst *CI) {
Sanjay Patel57747212016-01-21 23:38:43 +00001354 // We can only hope to do anything useful if we can ignore things like errno
1355 // and floating-point exceptions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001356 // We already checked the prototype.
1357 return CI->hasFnAttr(Attribute::NoUnwind) &&
1358 CI->hasFnAttr(Attribute::ReadNone);
Sanjay Patel57747212016-01-21 23:38:43 +00001359}
1360
Chris Bienemanad070d02014-09-17 20:55:46 +00001361static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1362 bool UseFloat, Value *&Sin, Value *&Cos,
Sanjay Patel57747212016-01-21 23:38:43 +00001363 Value *&SinCos) {
1364 Type *ArgTy = Arg->getType();
1365 Type *ResTy;
1366 StringRef Name;
1367
1368 Triple T(OrigCallee->getParent()->getTargetTriple());
1369 if (UseFloat) {
1370 Name = "__sincospif_stret";
1371
1372 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1373 // x86_64 can't use {float, float} since that would be returned in both
1374 // xmm0 and xmm1, which isn't what a real struct would do.
1375 ResTy = T.getArch() == Triple::x86_64
1376 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1377 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
1378 } else {
1379 Name = "__sincospi_stret";
1380 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
1381 }
1382
1383 Module *M = OrigCallee->getParent();
1384 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1385 ResTy, ArgTy, nullptr);
1386
1387 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1388 // If the argument is an instruction, it must dominate all uses so put our
1389 // sincos call there.
1390 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1391 } else {
1392 // Otherwise (e.g. for a constant) the beginning of the function is as
1393 // good a place as any.
1394 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1395 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1396 }
1397
1398 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1399
1400 if (SinCos->getType()->isStructTy()) {
1401 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1402 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1403 } else {
1404 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1405 "sinpi");
1406 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1407 "cospi");
1408 }
1409}
Chris Bienemanad070d02014-09-17 20:55:46 +00001410
1411Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001412 // Make sure the prototype is as expected, otherwise the rest of the
1413 // function is probably invalid and likely to abort.
1414 if (!isTrigLibCall(CI))
1415 return nullptr;
1416
1417 Value *Arg = CI->getArgOperand(0);
1418 SmallVector<CallInst *, 1> SinCalls;
1419 SmallVector<CallInst *, 1> CosCalls;
1420 SmallVector<CallInst *, 1> SinCosCalls;
1421
1422 bool IsFloat = Arg->getType()->isFloatTy();
1423
1424 // Look for all compatible sinpi, cospi and sincospi calls with the same
1425 // argument. If there are enough (in some sense) we can make the
1426 // substitution.
David Majnemerabae6b52016-03-19 04:53:02 +00001427 Function *F = CI->getFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001428 for (User *U : Arg->users())
David Majnemerabae6b52016-03-19 04:53:02 +00001429 classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
Chris Bienemanad070d02014-09-17 20:55:46 +00001430
1431 // It's only worthwhile if both sinpi and cospi are actually used.
1432 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1433 return nullptr;
1434
1435 Value *Sin, *Cos, *SinCos;
1436 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1437
1438 replaceTrigInsts(SinCalls, Sin);
1439 replaceTrigInsts(CosCalls, Cos);
1440 replaceTrigInsts(SinCosCalls, SinCos);
1441
1442 return nullptr;
1443}
1444
David Majnemerabae6b52016-03-19 04:53:02 +00001445void LibCallSimplifier::classifyArgUse(
1446 Value *Val, Function *F, bool IsFloat,
1447 SmallVectorImpl<CallInst *> &SinCalls,
1448 SmallVectorImpl<CallInst *> &CosCalls,
1449 SmallVectorImpl<CallInst *> &SinCosCalls) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001450 CallInst *CI = dyn_cast<CallInst>(Val);
1451
1452 if (!CI)
1453 return;
1454
David Majnemerabae6b52016-03-19 04:53:02 +00001455 // Don't consider calls in other functions.
1456 if (CI->getFunction() != F)
1457 return;
1458
Chris Bienemanad070d02014-09-17 20:55:46 +00001459 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001460 LibFunc::Func Func;
Ahmed Bougachad765a822016-04-27 19:04:35 +00001461 if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
Benjamin Kramer89766e52015-11-28 21:43:12 +00001462 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001463 return;
1464
1465 if (IsFloat) {
1466 if (Func == LibFunc::sinpif)
1467 SinCalls.push_back(CI);
1468 else if (Func == LibFunc::cospif)
1469 CosCalls.push_back(CI);
1470 else if (Func == LibFunc::sincospif_stret)
1471 SinCosCalls.push_back(CI);
1472 } else {
1473 if (Func == LibFunc::sinpi)
1474 SinCalls.push_back(CI);
1475 else if (Func == LibFunc::cospi)
1476 CosCalls.push_back(CI);
1477 else if (Func == LibFunc::sincospi_stret)
1478 SinCosCalls.push_back(CI);
1479 }
1480}
1481
1482void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1483 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001484 for (CallInst *C : Calls)
1485 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001486}
1487
Meador Inge7415f842012-11-25 20:45:27 +00001488//===----------------------------------------------------------------------===//
1489// Integer Library Call Optimizations
1490//===----------------------------------------------------------------------===//
1491
Chris Bienemanad070d02014-09-17 20:55:46 +00001492Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1493 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001494 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001495
Chris Bienemanad070d02014-09-17 20:55:46 +00001496 // Constant fold.
1497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1498 if (CI->isZero()) // ffs(0) -> 0.
1499 return B.getInt32(0);
1500 // ffs(c) -> cttz(c)+1
1501 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001502 }
Meador Inge7415f842012-11-25 20:45:27 +00001503
Chris Bienemanad070d02014-09-17 20:55:46 +00001504 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1505 Type *ArgType = Op->getType();
1506 Value *F =
1507 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001508 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1510 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001511
Chris Bienemanad070d02014-09-17 20:55:46 +00001512 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1513 return B.CreateSelect(Cond, V, B.getInt32(0));
1514}
Meador Ingea0b6d872012-11-26 00:24:07 +00001515
Chris Bienemanad070d02014-09-17 20:55:46 +00001516Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001517 // abs(x) -> x >s -1 ? x : -x
1518 Value *Op = CI->getArgOperand(0);
1519 Value *Pos =
1520 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1521 Value *Neg = B.CreateNeg(Op, "neg");
1522 return B.CreateSelect(Pos, Op, Neg);
1523}
Meador Inge9a59ab62012-11-26 02:31:59 +00001524
Chris Bienemanad070d02014-09-17 20:55:46 +00001525Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001526 // isdigit(c) -> (c-'0') <u 10
1527 Value *Op = CI->getArgOperand(0);
1528 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1529 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1530 return B.CreateZExt(Op, CI->getType());
1531}
Meador Ingea62a39e2012-11-26 03:10:07 +00001532
Chris Bienemanad070d02014-09-17 20:55:46 +00001533Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001534 // isascii(c) -> c <u 128
1535 Value *Op = CI->getArgOperand(0);
1536 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1537 return B.CreateZExt(Op, CI->getType());
1538}
1539
1540Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001541 // toascii(c) -> c & 0x7f
1542 return B.CreateAnd(CI->getArgOperand(0),
1543 ConstantInt::get(CI->getType(), 0x7F));
1544}
Meador Inge604937d2012-11-26 03:38:52 +00001545
Meador Inge08ca1152012-11-26 20:37:20 +00001546//===----------------------------------------------------------------------===//
1547// Formatting and IO Library Call Optimizations
1548//===----------------------------------------------------------------------===//
1549
Chris Bienemanad070d02014-09-17 20:55:46 +00001550static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001551
Chris Bienemanad070d02014-09-17 20:55:46 +00001552Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1553 int StreamArg) {
Ahmed Bougachad765a822016-04-27 19:04:35 +00001554 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 // Error reporting calls should be cold, mark them as such.
1556 // This applies even to non-builtin calls: it is only a hint and applies to
1557 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001558
Chris Bienemanad070d02014-09-17 20:55:46 +00001559 // This heuristic was suggested in:
1560 // Improving Static Branch Prediction in a Compiler
1561 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1562 // Proceedings of PACT'98, Oct. 1998, IEEE
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 if (!CI->hasFnAttr(Attribute::Cold) &&
1564 isReportingError(Callee, CI, StreamArg)) {
1565 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1566 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001567
Chris Bienemanad070d02014-09-17 20:55:46 +00001568 return nullptr;
1569}
1570
1571static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001572 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001573 return false;
1574
1575 if (StreamArg < 0)
1576 return true;
1577
1578 // These functions might be considered cold, but only if their stream
1579 // argument is stderr.
1580
1581 if (StreamArg >= (int)CI->getNumArgOperands())
1582 return false;
1583 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1584 if (!LI)
1585 return false;
1586 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1587 if (!GV || !GV->isDeclaration())
1588 return false;
1589 return GV->getName() == "stderr";
1590}
1591
1592Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1593 // Check for a fixed format string.
1594 StringRef FormatStr;
1595 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001596 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001597
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 // Empty format string -> noop.
1599 if (FormatStr.empty()) // Tolerate printf's declared void.
1600 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001601
Chris Bienemanad070d02014-09-17 20:55:46 +00001602 // Do not do any of the following transformations if the printf return value
1603 // is used, in general the printf return value is not compatible with either
1604 // putchar() or puts().
1605 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001606 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001607
Joerg Sonnenberger8ffe7ab2016-05-09 14:36:16 +00001608 // printf("x") -> putchar('x'), even for "%" and "%%".
1609 if (FormatStr.size() == 1 || FormatStr == "%%")
Davide Italianod4f5a052016-04-03 01:46:52 +00001610 return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001611
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001612 // printf("%s", "a") --> putchar('a')
1613 if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
1614 StringRef ChrStr;
1615 if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
1616 return nullptr;
1617 if (ChrStr.size() != 1)
1618 return nullptr;
Davide Italianod4f5a052016-04-03 01:46:52 +00001619 return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
Davide Italiano6db1dcb2016-03-28 15:54:01 +00001620 }
1621
Chris Bienemanad070d02014-09-17 20:55:46 +00001622 // printf("foo\n") --> puts("foo")
1623 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1624 FormatStr.find('%') == StringRef::npos) { // No format characters.
1625 // Create a string literal with no \n on it. We expect the constant merge
1626 // pass to be run after this pass, to merge duplicate strings.
1627 FormatStr = FormatStr.drop_back();
1628 Value *GV = B.CreateGlobalString(FormatStr, "str");
Davide Italianod4f5a052016-04-03 01:46:52 +00001629 return emitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001630 }
Meador Inge08ca1152012-11-26 20:37:20 +00001631
Chris Bienemanad070d02014-09-17 20:55:46 +00001632 // Optimize specific format strings.
1633 // printf("%c", chr) --> putchar(chr)
1634 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001635 CI->getArgOperand(1)->getType()->isIntegerTy())
1636 return emitPutChar(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001637
1638 // printf("%s\n", str) --> puts(str)
1639 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Davide Italianod4f5a052016-04-03 01:46:52 +00001640 CI->getArgOperand(1)->getType()->isPointerTy())
Sanjay Pateld3112a52016-01-19 19:46:10 +00001641 return emitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001642 return nullptr;
1643}
1644
1645Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1646
1647 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001648 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001649 if (Value *V = optimizePrintFString(CI, B)) {
1650 return V;
1651 }
1652
1653 // printf(format, ...) -> iprintf(format, ...) if no floating point
1654 // arguments.
1655 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1656 Module *M = B.GetInsertBlock()->getParent()->getParent();
1657 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001658 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001659 CallInst *New = cast<CallInst>(CI->clone());
1660 New->setCalledFunction(IPrintFFn);
1661 B.Insert(New);
1662 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001663 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001664 return nullptr;
1665}
Meador Inge08ca1152012-11-26 20:37:20 +00001666
Chris Bienemanad070d02014-09-17 20:55:46 +00001667Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1668 // Check for a fixed format string.
1669 StringRef FormatStr;
1670 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001671 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001672
Chris Bienemanad070d02014-09-17 20:55:46 +00001673 // If we just have a format string (nothing else crazy) transform it.
1674 if (CI->getNumArgOperands() == 2) {
1675 // Make sure there's no % in the constant array. We could try to handle
1676 // %% -> % in the future if we cared.
1677 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1678 if (FormatStr[i] == '%')
1679 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001680
Chris Bienemanad070d02014-09-17 20:55:46 +00001681 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001682 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1683 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1684 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001685 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001686 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001687 }
Meador Ingef8e72502012-11-29 15:45:43 +00001688
Chris Bienemanad070d02014-09-17 20:55:46 +00001689 // The remaining optimizations require the format string to be "%s" or "%c"
1690 // and have an extra operand.
1691 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1692 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001694
Chris Bienemanad070d02014-09-17 20:55:46 +00001695 // Decode the second character of the format string.
1696 if (FormatStr[1] == 'c') {
1697 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1698 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1699 return nullptr;
1700 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Sanjay Pateld3112a52016-01-19 19:46:10 +00001701 Value *Ptr = castToCStr(CI->getArgOperand(0), B);
Chris Bienemanad070d02014-09-17 20:55:46 +00001702 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001703 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001704 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001705
Chris Bienemanad070d02014-09-17 20:55:46 +00001706 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001707 }
1708
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001710 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1711 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1712 return nullptr;
1713
Sanjay Pateld3112a52016-01-19 19:46:10 +00001714 Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001715 if (!Len)
1716 return nullptr;
David Majnemerabb9f552016-04-26 21:04:47 +00001717 Value *IncLen =
1718 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1719 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001720
1721 // The sprintf result is the unincremented number of bytes in the string.
1722 return B.CreateIntCast(Len, CI->getType(), false);
1723 }
1724 return nullptr;
1725}
1726
1727Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1728 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001729 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001730 if (Value *V = optimizeSPrintFString(CI, B)) {
1731 return V;
1732 }
1733
1734 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1735 // point arguments.
1736 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1737 Module *M = B.GetInsertBlock()->getParent()->getParent();
1738 Constant *SIPrintFFn =
1739 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1740 CallInst *New = cast<CallInst>(CI->clone());
1741 New->setCalledFunction(SIPrintFFn);
1742 B.Insert(New);
1743 return New;
1744 }
1745 return nullptr;
1746}
1747
1748Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1749 optimizeErrorReporting(CI, B, 0);
1750
1751 // All the optimizations depend on the format string.
1752 StringRef FormatStr;
1753 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1754 return nullptr;
1755
1756 // Do not do any of the following transformations if the fprintf return
1757 // value is used, in general the fprintf return value is not compatible
1758 // with fwrite(), fputc() or fputs().
1759 if (!CI->use_empty())
1760 return nullptr;
1761
1762 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1763 if (CI->getNumArgOperands() == 2) {
1764 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1765 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1766 return nullptr; // We found a format specifier.
1767
Sanjay Pateld3112a52016-01-19 19:46:10 +00001768 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001769 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001770 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001771 CI->getArgOperand(0), B, DL, TLI);
1772 }
1773
1774 // The remaining optimizations require the format string to be "%s" or "%c"
1775 // and have an extra operand.
1776 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1777 CI->getNumArgOperands() < 3)
1778 return nullptr;
1779
1780 // Decode the second character of the format string.
1781 if (FormatStr[1] == 'c') {
1782 // fprintf(F, "%c", chr) --> fputc(chr, F)
1783 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1784 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001785 return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001786 }
1787
1788 if (FormatStr[1] == 's') {
1789 // fprintf(F, "%s", str) --> fputs(str, F)
1790 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1791 return nullptr;
Sanjay Pateld3112a52016-01-19 19:46:10 +00001792 return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 }
1794 return nullptr;
1795}
1796
1797Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1798 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001799 FunctionType *FT = Callee->getFunctionType();
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 if (Value *V = optimizeFPrintFString(CI, B)) {
1801 return V;
1802 }
1803
1804 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1805 // floating point arguments.
1806 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1807 Module *M = B.GetInsertBlock()->getParent()->getParent();
1808 Constant *FIPrintFFn =
1809 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1810 CallInst *New = cast<CallInst>(CI->clone());
1811 New->setCalledFunction(FIPrintFFn);
1812 B.Insert(New);
1813 return New;
1814 }
1815 return nullptr;
1816}
1817
1818Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1819 optimizeErrorReporting(CI, B, 3);
1820
Chris Bienemanad070d02014-09-17 20:55:46 +00001821 // Get the element size and count.
1822 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1823 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1824 if (!SizeC || !CountC)
1825 return nullptr;
1826 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1827
1828 // If this is writing zero records, remove the call (it's a noop).
1829 if (Bytes == 0)
1830 return ConstantInt::get(CI->getType(), 0);
1831
1832 // If this is writing one byte, turn it into fputc.
1833 // This optimisation is only valid, if the return value is unused.
1834 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Sanjay Pateld3112a52016-01-19 19:46:10 +00001835 Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
1836 Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001837 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1838 }
1839
1840 return nullptr;
1841}
1842
1843Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1844 optimizeErrorReporting(CI, B, 1);
1845
Sjoerd Meijer7435a912016-07-07 14:31:19 +00001846 // Don't rewrite fputs to fwrite when optimising for size because fwrite
1847 // requires more arguments and thus extra MOVs are required.
1848 if (CI->getParent()->getParent()->optForSize())
1849 return nullptr;
1850
Ahmed Bougachad765a822016-04-27 19:04:35 +00001851 // We can't optimize if return value is used.
1852 if (!CI->use_empty())
Chris Bienemanad070d02014-09-17 20:55:46 +00001853 return nullptr;
1854
1855 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1856 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1857 if (!Len)
1858 return nullptr;
1859
1860 // Known to have no uses (see above).
Sanjay Pateld3112a52016-01-19 19:46:10 +00001861 return emitFWrite(
Chris Bienemanad070d02014-09-17 20:55:46 +00001862 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001863 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001864 CI->getArgOperand(1), B, DL, TLI);
1865}
1866
1867Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001868 // Check for a constant string.
1869 StringRef Str;
1870 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1871 return nullptr;
1872
1873 if (Str.empty() && CI->use_empty()) {
1874 // puts("") -> putchar('\n')
Sanjay Pateld3112a52016-01-19 19:46:10 +00001875 Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001876 if (CI->use_empty() || !Res)
1877 return Res;
1878 return B.CreateIntCast(Res, CI->getType(), true);
1879 }
1880
1881 return nullptr;
1882}
1883
1884bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001885 LibFunc::Func Func;
1886 SmallString<20> FloatFuncName = FuncName;
1887 FloatFuncName += 'f';
1888 if (TLI->getLibFunc(FloatFuncName, Func))
1889 return TLI->has(Func);
1890 return false;
1891}
Meador Inge7fb2f732012-10-13 16:45:32 +00001892
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001893Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
1894 IRBuilder<> &Builder) {
1895 LibFunc::Func Func;
1896 Function *Callee = CI->getCalledFunction();
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001897 // Check for string/memory library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00001898 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001899 // Make sure we never change the calling convention.
1900 assert((ignoreCallingConv(Func) ||
1901 CI->getCallingConv() == llvm::CallingConv::C) &&
1902 "Optimizing string/memory libcall would change the calling convention");
1903 switch (Func) {
1904 case LibFunc::strcat:
1905 return optimizeStrCat(CI, Builder);
1906 case LibFunc::strncat:
1907 return optimizeStrNCat(CI, Builder);
1908 case LibFunc::strchr:
1909 return optimizeStrChr(CI, Builder);
1910 case LibFunc::strrchr:
1911 return optimizeStrRChr(CI, Builder);
1912 case LibFunc::strcmp:
1913 return optimizeStrCmp(CI, Builder);
1914 case LibFunc::strncmp:
1915 return optimizeStrNCmp(CI, Builder);
1916 case LibFunc::strcpy:
1917 return optimizeStrCpy(CI, Builder);
1918 case LibFunc::stpcpy:
1919 return optimizeStpCpy(CI, Builder);
1920 case LibFunc::strncpy:
1921 return optimizeStrNCpy(CI, Builder);
1922 case LibFunc::strlen:
1923 return optimizeStrLen(CI, Builder);
1924 case LibFunc::strpbrk:
1925 return optimizeStrPBrk(CI, Builder);
1926 case LibFunc::strtol:
1927 case LibFunc::strtod:
1928 case LibFunc::strtof:
1929 case LibFunc::strtoul:
1930 case LibFunc::strtoll:
1931 case LibFunc::strtold:
1932 case LibFunc::strtoull:
1933 return optimizeStrTo(CI, Builder);
1934 case LibFunc::strspn:
1935 return optimizeStrSpn(CI, Builder);
1936 case LibFunc::strcspn:
1937 return optimizeStrCSpn(CI, Builder);
1938 case LibFunc::strstr:
1939 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00001940 case LibFunc::memchr:
1941 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00001942 case LibFunc::memcmp:
1943 return optimizeMemCmp(CI, Builder);
1944 case LibFunc::memcpy:
1945 return optimizeMemCpy(CI, Builder);
1946 case LibFunc::memmove:
1947 return optimizeMemMove(CI, Builder);
1948 case LibFunc::memset:
1949 return optimizeMemSet(CI, Builder);
1950 default:
1951 break;
1952 }
1953 }
1954 return nullptr;
1955}
1956
Chris Bienemanad070d02014-09-17 20:55:46 +00001957Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
1958 if (CI->isNoBuiltin())
1959 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00001960
Meador Inge20255ef2013-03-12 00:08:29 +00001961 LibFunc::Func Func;
1962 Function *Callee = CI->getCalledFunction();
1963 StringRef FuncName = Callee->getName();
David Majnemerb70e23c2016-01-06 05:01:34 +00001964
1965 SmallVector<OperandBundleDef, 2> OpBundles;
1966 CI->getOperandBundlesAsDefs(OpBundles);
1967 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Chris Bienemanad070d02014-09-17 20:55:46 +00001968 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00001969
Sanjay Pateld1f4f032016-01-19 18:38:52 +00001970 // Command-line parameter overrides instruction attribute.
Sanjay Patela92fa442014-10-22 15:29:23 +00001971 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
1972 UnsafeFPShrink = EnableUnsafeFPShrink;
Sanjay Pateld1f4f032016-01-19 18:38:52 +00001973 else if (isa<FPMathOperator>(CI) && CI->hasUnsafeAlgebra())
Davide Italianoa904e522015-10-29 02:58:44 +00001974 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00001975
Sanjay Patel848309d2014-10-23 21:52:45 +00001976 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00001977 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00001978 if (!isCallingConvC)
1979 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001980 switch (II->getIntrinsicID()) {
1981 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00001982 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00001983 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00001984 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001985 case Intrinsic::fabs:
1986 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00001987 case Intrinsic::log:
1988 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00001989 case Intrinsic::sqrt:
1990 return optimizeSqrt(CI, Builder);
Sanjay Patel980b2802016-01-26 16:17:24 +00001991 // TODO: Use foldMallocMemset() with memset intrinsic.
Meador Inge20255ef2013-03-12 00:08:29 +00001992 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00001993 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00001994 }
1995 }
1996
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001997 // Also try to simplify calls to fortified library functions.
1998 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
1999 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002000 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002001 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2002 // Use an IR Builder from SimplifiedCI if available instead of CI
2003 // to guarantee we reach all uses we might replace later on.
2004 IRBuilder<> TmpBuilder(SimplifiedCI);
2005 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002006 // If we were able to further simplify, remove the now redundant call.
2007 SimplifiedCI->replaceAllUsesWith(V);
2008 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002009 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002010 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002011 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002012 return SimplifiedFortifiedCI;
2013 }
2014
Meador Inge20255ef2013-03-12 00:08:29 +00002015 // Then check for known library functions.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002016 if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002017 // We never change the calling convention.
2018 if (!ignoreCallingConv(Func) && !isCallingConvC)
2019 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002020 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2021 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002022 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002023 case LibFunc::cosf:
2024 case LibFunc::cos:
2025 case LibFunc::cosl:
2026 return optimizeCos(CI, Builder);
2027 case LibFunc::sinpif:
2028 case LibFunc::sinpi:
2029 case LibFunc::cospif:
2030 case LibFunc::cospi:
2031 return optimizeSinCosPi(CI, Builder);
2032 case LibFunc::powf:
2033 case LibFunc::pow:
2034 case LibFunc::powl:
2035 return optimizePow(CI, Builder);
2036 case LibFunc::exp2l:
2037 case LibFunc::exp2:
2038 case LibFunc::exp2f:
2039 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002040 case LibFunc::fabsf:
2041 case LibFunc::fabs:
2042 case LibFunc::fabsl:
2043 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002044 case LibFunc::sqrtf:
2045 case LibFunc::sqrt:
2046 case LibFunc::sqrtl:
2047 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002048 case LibFunc::ffs:
2049 case LibFunc::ffsl:
2050 case LibFunc::ffsll:
2051 return optimizeFFS(CI, Builder);
2052 case LibFunc::abs:
2053 case LibFunc::labs:
2054 case LibFunc::llabs:
2055 return optimizeAbs(CI, Builder);
2056 case LibFunc::isdigit:
2057 return optimizeIsDigit(CI, Builder);
2058 case LibFunc::isascii:
2059 return optimizeIsAscii(CI, Builder);
2060 case LibFunc::toascii:
2061 return optimizeToAscii(CI, Builder);
2062 case LibFunc::printf:
2063 return optimizePrintF(CI, Builder);
2064 case LibFunc::sprintf:
2065 return optimizeSPrintF(CI, Builder);
2066 case LibFunc::fprintf:
2067 return optimizeFPrintF(CI, Builder);
2068 case LibFunc::fwrite:
2069 return optimizeFWrite(CI, Builder);
2070 case LibFunc::fputs:
2071 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002072 case LibFunc::log:
2073 case LibFunc::log10:
2074 case LibFunc::log1p:
2075 case LibFunc::log2:
2076 case LibFunc::logb:
2077 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002078 case LibFunc::puts:
2079 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002080 case LibFunc::tan:
2081 case LibFunc::tanf:
2082 case LibFunc::tanl:
2083 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002084 case LibFunc::perror:
2085 return optimizeErrorReporting(CI, Builder);
2086 case LibFunc::vfprintf:
2087 case LibFunc::fiprintf:
2088 return optimizeErrorReporting(CI, Builder, 0);
2089 case LibFunc::fputc:
2090 return optimizeErrorReporting(CI, Builder, 1);
2091 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002092 case LibFunc::floor:
2093 case LibFunc::rint:
2094 case LibFunc::round:
2095 case LibFunc::nearbyint:
2096 case LibFunc::trunc:
2097 if (hasFloatVersion(FuncName))
2098 return optimizeUnaryDoubleFP(CI, Builder, false);
2099 return nullptr;
2100 case LibFunc::acos:
2101 case LibFunc::acosh:
2102 case LibFunc::asin:
2103 case LibFunc::asinh:
2104 case LibFunc::atan:
2105 case LibFunc::atanh:
2106 case LibFunc::cbrt:
2107 case LibFunc::cosh:
2108 case LibFunc::exp:
2109 case LibFunc::exp10:
2110 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002111 case LibFunc::sin:
2112 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002113 case LibFunc::tanh:
2114 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2115 return optimizeUnaryDoubleFP(CI, Builder, true);
2116 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002117 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002118 if (hasFloatVersion(FuncName))
2119 return optimizeBinaryDoubleFP(CI, Builder);
2120 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002121 case LibFunc::fminf:
2122 case LibFunc::fmin:
2123 case LibFunc::fminl:
2124 case LibFunc::fmaxf:
2125 case LibFunc::fmax:
2126 case LibFunc::fmaxl:
2127 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002128 default:
2129 return nullptr;
2130 }
Meador Inge20255ef2013-03-12 00:08:29 +00002131 }
Craig Topperf40110f2014-04-25 05:29:35 +00002132 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002133}
2134
Chandler Carruth92803822015-01-21 02:11:59 +00002135LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002136 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002137 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002138 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002139 Replacer(Replacer) {}
2140
2141void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2142 // Indirect through the replacer used in this instance.
2143 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002144}
2145
Meador Ingedfb08a22013-06-20 19:48:07 +00002146// TODO:
2147// Additional cases that we need to add to this file:
2148//
2149// cbrt:
2150// * cbrt(expN(X)) -> expN(x/3)
2151// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002152// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002153//
2154// exp, expf, expl:
2155// * exp(log(x)) -> x
2156//
2157// log, logf, logl:
2158// * log(exp(x)) -> x
Meador Ingedfb08a22013-06-20 19:48:07 +00002159// * log(exp(y)) -> y*log(e)
Meador Ingedfb08a22013-06-20 19:48:07 +00002160// * log(exp10(y)) -> y*log(10)
2161// * log(sqrt(x)) -> 0.5*log(x)
Meador Ingedfb08a22013-06-20 19:48:07 +00002162//
2163// lround, lroundf, lroundl:
2164// * lround(cnst) -> cnst'
2165//
2166// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002167// * pow(sqrt(x),y) -> pow(x,y*0.5)
2168// * pow(pow(x,y),z)-> pow(x,y*z)
2169//
2170// round, roundf, roundl:
2171// * round(cnst) -> cnst'
2172//
2173// signbit:
2174// * signbit(cnst) -> cnst'
2175// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2176//
2177// sqrt, sqrtf, sqrtl:
2178// * sqrt(expN(x)) -> expN(x*0.5)
2179// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2180// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2181//
Meador Ingedfb08a22013-06-20 19:48:07 +00002182// trunc, truncf, truncl:
2183// * trunc(cnst) -> cnst'
2184//
2185//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002186
2187//===----------------------------------------------------------------------===//
2188// Fortified Library Call Optimizations
2189//===----------------------------------------------------------------------===//
2190
2191bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2192 unsigned ObjSizeOp,
2193 unsigned SizeOp,
2194 bool isString) {
2195 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2196 return true;
2197 if (ConstantInt *ObjSizeCI =
2198 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2199 if (ObjSizeCI->isAllOnesValue())
2200 return true;
2201 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2202 if (OnlyLowerUnknownSize)
2203 return false;
2204 if (isString) {
2205 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2206 // If the length is 0 we don't know how long it is and so we can't
2207 // remove the check.
2208 if (Len == 0)
2209 return false;
2210 return ObjSizeCI->getZExtValue() >= Len;
2211 }
2212 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2213 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2214 }
2215 return false;
2216}
2217
Sanjay Pateld707db92015-12-31 16:10:49 +00002218Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
2219 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002220 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2221 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002222 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002223 return CI->getArgOperand(0);
2224 }
2225 return nullptr;
2226}
2227
Sanjay Pateld707db92015-12-31 16:10:49 +00002228Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
2229 IRBuilder<> &B) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002230 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2231 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002232 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002233 return CI->getArgOperand(0);
2234 }
2235 return nullptr;
2236}
2237
Sanjay Pateld707db92015-12-31 16:10:49 +00002238Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
2239 IRBuilder<> &B) {
Sanjay Patel980b2802016-01-26 16:17:24 +00002240 // TODO: Try foldMallocMemset() here.
2241
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002242 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2243 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2244 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2245 return CI->getArgOperand(0);
2246 }
2247 return nullptr;
2248}
2249
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002250Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2251 IRBuilder<> &B,
2252 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002253 Function *Callee = CI->getCalledFunction();
2254 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002255 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002256 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2257 *ObjSize = CI->getArgOperand(2);
2258
2259 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002260 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002261 Value *StrLen = emitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002262 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002263 }
2264
2265 // If a) we don't have any length information, or b) we know this will
2266 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2267 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2268 // TODO: It might be nice to get a maximum length out of the possible
2269 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002270 if (isFortifiedCallFoldable(CI, 2, 1, true))
Sanjay Pateld3112a52016-01-19 19:46:10 +00002271 return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002272
David Blaikie65fab6d2015-04-03 21:32:06 +00002273 if (OnlyLowerUnknownSize)
2274 return nullptr;
2275
2276 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2277 uint64_t Len = GetStringLength(Src);
2278 if (Len == 0)
2279 return nullptr;
2280
2281 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2282 Value *LenV = ConstantInt::get(SizeTTy, Len);
Sanjay Pateld3112a52016-01-19 19:46:10 +00002283 Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
David Blaikie65fab6d2015-04-03 21:32:06 +00002284 // If the function was an __stpcpy_chk, and we were able to fold it into
2285 // a __memcpy_chk, we still need to return the correct end pointer.
2286 if (Ret && Func == LibFunc::stpcpy_chk)
2287 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2288 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002289}
2290
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002291Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2292 IRBuilder<> &B,
2293 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002294 Function *Callee = CI->getCalledFunction();
2295 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002296 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Sanjay Pateld3112a52016-01-19 19:46:10 +00002297 Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002298 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002299 return Ret;
2300 }
2301 return nullptr;
2302}
2303
2304Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002305 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2306 // Some clang users checked for _chk libcall availability using:
2307 // __has_builtin(__builtin___memcpy_chk)
2308 // When compiling with -fno-builtin, this is always true.
2309 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2310 // end up with fortified libcalls, which isn't acceptable in a freestanding
2311 // environment which only provides their non-fortified counterparts.
2312 //
2313 // Until we change clang and/or teach external users to check for availability
2314 // differently, disregard the "nobuiltin" attribute and TLI::has.
2315 //
2316 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002317
2318 LibFunc::Func Func;
2319 Function *Callee = CI->getCalledFunction();
David Majnemerb70e23c2016-01-06 05:01:34 +00002320
2321 SmallVector<OperandBundleDef, 2> OpBundles;
2322 CI->getOperandBundlesAsDefs(OpBundles);
2323 IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002324 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2325
Ahmed Bougachad765a822016-04-27 19:04:35 +00002326 // First, check that this is a known library functions and that the prototype
2327 // is correct.
2328 if (!TLI->getLibFunc(*Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002329 return nullptr;
2330
2331 // We never change the calling convention.
2332 if (!ignoreCallingConv(Func) && !isCallingConvC)
2333 return nullptr;
2334
2335 switch (Func) {
2336 case LibFunc::memcpy_chk:
2337 return optimizeMemCpyChk(CI, Builder);
2338 case LibFunc::memmove_chk:
2339 return optimizeMemMoveChk(CI, Builder);
2340 case LibFunc::memset_chk:
2341 return optimizeMemSetChk(CI, Builder);
2342 case LibFunc::stpcpy_chk:
2343 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002344 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002345 case LibFunc::stpncpy_chk:
2346 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002347 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002348 default:
2349 break;
2350 }
2351 return nullptr;
2352}
2353
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002354FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2355 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2356 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}