blob: c811e19f8b27d2c7539ac7993718e7824ebb98bd [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"
Nadav Rotem464e8072013-02-27 05:53:43 +000032#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000033#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000034#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chad Rosierdc655322015-08-28 18:30:18 +000035#include "llvm/Transforms/Utils/Local.h"
Meador Ingedf796f82012-10-13 16:45:24 +000036
37using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000038using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000039
Hal Finkel66cd3f12013-11-17 02:06:35 +000040static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000041 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
42 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000043
Sanjay Patela92fa442014-10-22 15:29:23 +000044static cl::opt<bool>
45 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
46 cl::init(false),
47 cl::desc("Enable unsafe double to float "
48 "shrinking for math lib calls"));
49
50
Meador Ingedf796f82012-10-13 16:45:24 +000051//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000052// Helper Functions
53//===----------------------------------------------------------------------===//
54
Chris Bienemanad070d02014-09-17 20:55:46 +000055static bool ignoreCallingConv(LibFunc::Func Func) {
Davide Italianob883b012015-11-12 23:39:00 +000056 return Func == LibFunc::abs || Func == LibFunc::labs ||
57 Func == LibFunc::llabs || Func == LibFunc::strlen;
Chris Bienemanad070d02014-09-17 20:55:46 +000058}
59
Meador Inged589ac62012-10-31 03:33:06 +000060/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
61/// value is equal or not-equal to zero.
62static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000063 for (User *U : V->users()) {
64 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000065 if (IC->isEquality())
66 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
67 if (C->isNullValue())
68 continue;
69 // Unknown instruction.
70 return false;
71 }
72 return true;
73}
74
Meador Inge56edbc92012-11-11 03:51:48 +000075/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
76/// comparisons with With.
77static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000078 for (User *U : V->users()) {
79 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000080 if (IC->isEquality() && IC->getOperand(1) == With)
81 continue;
82 // Unknown instruction.
83 return false;
84 }
85 return true;
86}
87
Meador Inge08ca1152012-11-26 20:37:20 +000088static bool callHasFloatingPointArgument(const CallInst *CI) {
Davide Italianoda3beeb2015-11-28 22:27:48 +000089 return std::any_of(CI->op_begin(), CI->op_end(), [](const Use &OI) {
90 return OI->getType()->isFloatingPointTy();
91 });
Meador Inge08ca1152012-11-26 20:37:20 +000092}
93
Benjamin Kramer2702caa2013-08-31 18:19:35 +000094/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000095/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000096static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
97 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
98 LibFunc::Func LongDoubleFn) {
99 switch (Ty->getTypeID()) {
100 case Type::FloatTyID:
101 return TLI->has(FloatFn);
102 case Type::DoubleTyID:
103 return TLI->has(DoubleFn);
104 default:
105 return TLI->has(LongDoubleFn);
106 }
107}
108
Davide Italianoa904e522015-10-29 02:58:44 +0000109/// \brief Check whether we can use unsafe floating point math for
110/// the function passed as input.
111static bool canUseUnsafeFPMath(Function *F) {
112
113 // FIXME: For finer-grain optimization, we need intrinsics to have the same
114 // fast-math flag decorations that are applied to FP instructions. For now,
115 // we have to rely on the function-level unsafe-fp-math attribute to do this
Davide Italianoed5cc952015-11-16 16:54:28 +0000116 // optimization because there's no other way to express that the call can be
117 // relaxed.
Davide Italianoa904e522015-10-29 02:58:44 +0000118 if (F->hasFnAttribute("unsafe-fp-math")) {
119 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
120 if (Attr.getValueAsString() == "true")
121 return true;
122 }
123 return false;
124}
125
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000126/// \brief Returns whether \p F matches the signature expected for the
127/// string/memory copying library function \p Func.
128/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
129/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
131 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000132 FunctionType *FT = F->getFunctionType();
133 LLVMContext &Context = F->getContext();
134 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000136 unsigned NumParams = FT->getNumParams();
137
138 // All string libfuncs return the same type as the first parameter.
139 if (FT->getReturnType() != FT->getParamType(0))
140 return false;
141
142 switch (Func) {
143 default:
144 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
145 case LibFunc::stpncpy_chk:
146 case LibFunc::strncpy_chk:
147 --NumParams; // fallthrough
148 case LibFunc::stpncpy:
149 case LibFunc::strncpy: {
150 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
151 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
152 return false;
153 break;
154 }
155 case LibFunc::strcpy_chk:
156 case LibFunc::stpcpy_chk:
157 --NumParams; // fallthrough
158 case LibFunc::stpcpy:
159 case LibFunc::strcpy: {
160 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
161 FT->getParamType(0) != PCharTy)
162 return false;
163 break;
164 }
165 case LibFunc::memmove_chk:
166 case LibFunc::memcpy_chk:
167 --NumParams; // fallthrough
168 case LibFunc::memmove:
169 case LibFunc::memcpy: {
170 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
171 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
172 return false;
173 break;
174 }
175 case LibFunc::memset_chk:
176 --NumParams; // fallthrough
177 case LibFunc::memset: {
178 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
179 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
180 return false;
181 break;
182 }
183 }
184 // If this is a fortified libcall, the last parameter is a size_t.
185 if (NumParams == FT->getNumParams() - 1)
186 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
187 return true;
188}
189
Meador Inged589ac62012-10-31 03:33:06 +0000190//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000191// String and Memory Library Call Optimizations
192//===----------------------------------------------------------------------===//
193
Chris Bienemanad070d02014-09-17 20:55:46 +0000194Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
195 Function *Callee = CI->getCalledFunction();
196 // Verify the "strcat" function prototype.
197 FunctionType *FT = Callee->getFunctionType();
198 if (FT->getNumParams() != 2||
199 FT->getReturnType() != B.getInt8PtrTy() ||
200 FT->getParamType(0) != FT->getReturnType() ||
201 FT->getParamType(1) != FT->getReturnType())
202 return nullptr;
203
204 // Extract some information from the instruction
205 Value *Dst = CI->getArgOperand(0);
206 Value *Src = CI->getArgOperand(1);
207
208 // See if we can get the length of the input string.
209 uint64_t Len = GetStringLength(Src);
210 if (Len == 0)
211 return nullptr;
212 --Len; // Unbias length.
213
214 // Handle the simple, do-nothing case: strcat(x, "") -> x
215 if (Len == 0)
216 return Dst;
217
Chris Bienemanad070d02014-09-17 20:55:46 +0000218 return emitStrLenMemCpy(Src, Dst, Len, B);
219}
220
221Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
222 IRBuilder<> &B) {
223 // We need to find the end of the destination string. That's where the
224 // memory is to be moved to. We just generate a call to strlen.
225 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
226 if (!DstLen)
227 return nullptr;
228
229 // Now that we have the destination's length, we must index into the
230 // destination's pointer to get the actual memcpy destination (end of
231 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000232 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000233
234 // We have enough information to now generate the memcpy call to do the
235 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236 B.CreateMemCpy(CpyDst, Src,
237 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000238 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 return Dst;
240}
241
242Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
243 Function *Callee = CI->getCalledFunction();
244 // Verify the "strncat" function prototype.
245 FunctionType *FT = Callee->getFunctionType();
246 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
247 FT->getParamType(0) != FT->getReturnType() ||
248 FT->getParamType(1) != FT->getReturnType() ||
249 !FT->getParamType(2)->isIntegerTy())
250 return nullptr;
251
252 // Extract some information from the instruction
253 Value *Dst = CI->getArgOperand(0);
254 Value *Src = CI->getArgOperand(1);
255 uint64_t Len;
256
257 // We don't do anything if length is not constant
258 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
259 Len = LengthArg->getZExtValue();
260 else
261 return nullptr;
262
263 // See if we can get the length of the input string.
264 uint64_t SrcLen = GetStringLength(Src);
265 if (SrcLen == 0)
266 return nullptr;
267 --SrcLen; // Unbias length.
268
269 // Handle the simple, do-nothing cases:
270 // strncat(x, "", c) -> x
271 // strncat(x, c, 0) -> x
272 if (SrcLen == 0 || Len == 0)
273 return Dst;
274
Chris Bienemanad070d02014-09-17 20:55:46 +0000275 // We don't optimize this case
276 if (Len < SrcLen)
277 return nullptr;
278
279 // strncat(x, s, c) -> strcat(x, s)
280 // s is constant so the strcat can be optimized further
281 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
282}
283
284Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
285 Function *Callee = CI->getCalledFunction();
286 // Verify the "strchr" function prototype.
287 FunctionType *FT = Callee->getFunctionType();
288 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
289 FT->getParamType(0) != FT->getReturnType() ||
290 !FT->getParamType(1)->isIntegerTy(32))
291 return nullptr;
292
293 Value *SrcStr = CI->getArgOperand(0);
294
295 // If the second operand is non-constant, see if we can compute the length
296 // of the input string and turn this into memchr.
297 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
298 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000299 uint64_t Len = GetStringLength(SrcStr);
300 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
301 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000302
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000303 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
304 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
305 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000306 }
307
Chris Bienemanad070d02014-09-17 20:55:46 +0000308 // Otherwise, the character is a constant, see if the first argument is
309 // a string literal. If so, we can constant fold.
310 StringRef Str;
311 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000313 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000314 return nullptr;
315 }
316
317 // Compute the offset, make sure to handle the case when we're searching for
318 // zero (a weird way to spell strlen).
319 size_t I = (0xFF & CharC->getSExtValue()) == 0
320 ? Str.size()
321 : Str.find(CharC->getSExtValue());
322 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
323 return Constant::getNullValue(CI->getType());
324
325 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000326 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000327}
328
329Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
330 Function *Callee = CI->getCalledFunction();
331 // Verify the "strrchr" function prototype.
332 FunctionType *FT = Callee->getFunctionType();
333 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
334 FT->getParamType(0) != FT->getReturnType() ||
335 !FT->getParamType(1)->isIntegerTy(32))
336 return nullptr;
337
338 Value *SrcStr = CI->getArgOperand(0);
339 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
340
341 // Cannot fold anything if we're not looking for a constant.
342 if (!CharC)
343 return nullptr;
344
345 StringRef Str;
346 if (!getConstantStringInfo(SrcStr, Str)) {
347 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 if (CharC->isZero())
349 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000350 return nullptr;
351 }
352
353 // Compute the offset.
354 size_t I = (0xFF & CharC->getSExtValue()) == 0
355 ? Str.size()
356 : Str.rfind(CharC->getSExtValue());
357 if (I == StringRef::npos) // Didn't find the char. Return null.
358 return Constant::getNullValue(CI->getType());
359
360 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000361 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000362}
363
364Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
365 Function *Callee = CI->getCalledFunction();
366 // Verify the "strcmp" function prototype.
367 FunctionType *FT = Callee->getFunctionType();
368 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
369 FT->getParamType(0) != FT->getParamType(1) ||
370 FT->getParamType(0) != B.getInt8PtrTy())
371 return nullptr;
372
373 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
374 if (Str1P == Str2P) // strcmp(x,x) -> 0
375 return ConstantInt::get(CI->getType(), 0);
376
377 StringRef Str1, Str2;
378 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
379 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
380
381 // strcmp(x, y) -> cnst (if both x and y are constant strings)
382 if (HasStr1 && HasStr2)
383 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
384
385 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
386 return B.CreateNeg(
387 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
388
389 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
390 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
391
392 // strcmp(P, "x") -> memcmp(P, "x", 2)
393 uint64_t Len1 = GetStringLength(Str1P);
394 uint64_t Len2 = GetStringLength(Str2P);
395 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000396 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000397 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000398 std::min(Len1, Len2)),
399 B, DL, TLI);
400 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000401
Chris Bienemanad070d02014-09-17 20:55:46 +0000402 return nullptr;
403}
404
405Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
406 Function *Callee = CI->getCalledFunction();
407 // Verify the "strncmp" function prototype.
408 FunctionType *FT = Callee->getFunctionType();
409 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
410 FT->getParamType(0) != FT->getParamType(1) ||
411 FT->getParamType(0) != B.getInt8PtrTy() ||
412 !FT->getParamType(2)->isIntegerTy())
413 return nullptr;
414
415 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
416 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
417 return ConstantInt::get(CI->getType(), 0);
418
419 // Get the length argument if it is constant.
420 uint64_t Length;
421 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
422 Length = LengthArg->getZExtValue();
423 else
424 return nullptr;
425
426 if (Length == 0) // strncmp(x,y,0) -> 0
427 return ConstantInt::get(CI->getType(), 0);
428
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000429 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000430 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
431
432 StringRef Str1, Str2;
433 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
434 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
435
436 // strncmp(x, y) -> cnst (if both x and y are constant strings)
437 if (HasStr1 && HasStr2) {
438 StringRef SubStr1 = Str1.substr(0, Length);
439 StringRef SubStr2 = Str2.substr(0, Length);
440 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
441 }
442
443 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
444 return B.CreateNeg(
445 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
446
447 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
448 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
449
450 return nullptr;
451}
452
453Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
454 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000455
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000456 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000457 return nullptr;
458
459 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
460 if (Dst == Src) // strcpy(x,x) -> x
461 return Src;
462
Chris Bienemanad070d02014-09-17 20:55:46 +0000463 // See if we can get the length of the input string.
464 uint64_t Len = GetStringLength(Src);
465 if (Len == 0)
466 return nullptr;
467
468 // We have enough information to now generate the memcpy call to do the
469 // copy for us. Make a memcpy to copy the nul byte with align = 1.
470 B.CreateMemCpy(Dst, Src,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000471 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000472 return Dst;
473}
474
475Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
476 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000477 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000478 return nullptr;
479
480 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
481 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
482 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000483 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000484 }
485
486 // See if we can get the length of the input string.
487 uint64_t Len = GetStringLength(Src);
488 if (Len == 0)
489 return nullptr;
490
Davide Italianob7487e62015-11-02 23:07:14 +0000491 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000492 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000493 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000494 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000495
496 // We have enough information to now generate the memcpy call to do the
497 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000498 B.CreateMemCpy(Dst, Src, LenV, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000499 return DstEnd;
500}
501
502Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
503 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000504 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000505 return nullptr;
506
507 Value *Dst = CI->getArgOperand(0);
508 Value *Src = CI->getArgOperand(1);
509 Value *LenOp = CI->getArgOperand(2);
510
511 // See if we can get the length of the input string.
512 uint64_t SrcLen = GetStringLength(Src);
513 if (SrcLen == 0)
514 return nullptr;
515 --SrcLen;
516
517 if (SrcLen == 0) {
518 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
519 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000520 return Dst;
521 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000522
Chris Bienemanad070d02014-09-17 20:55:46 +0000523 uint64_t Len;
524 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
525 Len = LengthArg->getZExtValue();
526 else
527 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000528
Chris Bienemanad070d02014-09-17 20:55:46 +0000529 if (Len == 0)
530 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000531
Chris Bienemanad070d02014-09-17 20:55:46 +0000532 // Let strncpy handle the zero padding
533 if (Len > SrcLen + 1)
534 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000535
Davide Italianob7487e62015-11-02 23:07:14 +0000536 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000537 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper67cf9a72015-11-19 05:56:52 +0000538 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000539
Chris Bienemanad070d02014-09-17 20:55:46 +0000540 return Dst;
541}
Meador Inge7fb2f732012-10-13 16:45:32 +0000542
Chris Bienemanad070d02014-09-17 20:55:46 +0000543Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
544 Function *Callee = CI->getCalledFunction();
545 FunctionType *FT = Callee->getFunctionType();
546 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
547 !FT->getReturnType()->isIntegerTy())
548 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000549
Chris Bienemanad070d02014-09-17 20:55:46 +0000550 Value *Src = CI->getArgOperand(0);
551
552 // Constant folding: strlen("xyz") -> 3
553 if (uint64_t Len = GetStringLength(Src))
554 return ConstantInt::get(CI->getType(), Len - 1);
555
556 // strlen(x?"foo":"bars") --> x ? 3 : 4
557 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
558 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
559 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
560 if (LenTrue && LenFalse) {
561 Function *Caller = CI->getParent()->getParent();
562 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
563 SI->getDebugLoc(),
564 "folded strlen(select) to select of constants");
565 return B.CreateSelect(SI->getCondition(),
566 ConstantInt::get(CI->getType(), LenTrue - 1),
567 ConstantInt::get(CI->getType(), LenFalse - 1));
568 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000569 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000570
Chris Bienemanad070d02014-09-17 20:55:46 +0000571 // strlen(x) != 0 --> *x != 0
572 // strlen(x) == 0 --> *x == 0
573 if (isOnlyUsedInZeroEqualityComparison(CI))
574 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000575
Chris Bienemanad070d02014-09-17 20:55:46 +0000576 return nullptr;
577}
Meador Inge17418502012-10-13 16:45:37 +0000578
Chris Bienemanad070d02014-09-17 20:55:46 +0000579Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
580 Function *Callee = CI->getCalledFunction();
581 FunctionType *FT = Callee->getFunctionType();
582 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
583 FT->getParamType(1) != FT->getParamType(0) ||
584 FT->getReturnType() != FT->getParamType(0))
585 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000586
Chris Bienemanad070d02014-09-17 20:55:46 +0000587 StringRef S1, S2;
588 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
589 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000590
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000591 // strpbrk(s, "") -> nullptr
592 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000593 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
594 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000595
Chris Bienemanad070d02014-09-17 20:55:46 +0000596 // Constant folding.
597 if (HasS1 && HasS2) {
598 size_t I = S1.find_first_of(S2);
599 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000600 return Constant::getNullValue(CI->getType());
601
David Blaikie3909da72015-03-30 20:42:56 +0000602 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000603 }
Meador Inge17418502012-10-13 16:45:37 +0000604
Chris Bienemanad070d02014-09-17 20:55:46 +0000605 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000606 if (HasS2 && S2.size() == 1)
607 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000608
609 return nullptr;
610}
611
612Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
613 Function *Callee = CI->getCalledFunction();
614 FunctionType *FT = Callee->getFunctionType();
615 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
616 !FT->getParamType(0)->isPointerTy() ||
617 !FT->getParamType(1)->isPointerTy())
618 return nullptr;
619
620 Value *EndPtr = CI->getArgOperand(1);
621 if (isa<ConstantPointerNull>(EndPtr)) {
622 // With a null EndPtr, this function won't capture the main argument.
623 // It would be readonly too, except that it still may write to errno.
624 CI->addAttribute(1, Attribute::NoCapture);
625 }
626
627 return nullptr;
628}
629
630Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
631 Function *Callee = CI->getCalledFunction();
632 FunctionType *FT = Callee->getFunctionType();
633 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
634 FT->getParamType(1) != FT->getParamType(0) ||
635 !FT->getReturnType()->isIntegerTy())
636 return nullptr;
637
638 StringRef S1, S2;
639 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
640 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
641
642 // strspn(s, "") -> 0
643 // strspn("", s) -> 0
644 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
645 return Constant::getNullValue(CI->getType());
646
647 // Constant folding.
648 if (HasS1 && HasS2) {
649 size_t Pos = S1.find_first_not_of(S2);
650 if (Pos == StringRef::npos)
651 Pos = S1.size();
652 return ConstantInt::get(CI->getType(), Pos);
653 }
654
655 return nullptr;
656}
657
658Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
659 Function *Callee = CI->getCalledFunction();
660 FunctionType *FT = Callee->getFunctionType();
661 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
662 FT->getParamType(1) != FT->getParamType(0) ||
663 !FT->getReturnType()->isIntegerTy())
664 return nullptr;
665
666 StringRef S1, S2;
667 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
668 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
669
670 // strcspn("", s) -> 0
671 if (HasS1 && S1.empty())
672 return Constant::getNullValue(CI->getType());
673
674 // Constant folding.
675 if (HasS1 && HasS2) {
676 size_t Pos = S1.find_first_of(S2);
677 if (Pos == StringRef::npos)
678 Pos = S1.size();
679 return ConstantInt::get(CI->getType(), Pos);
680 }
681
682 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000683 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000684 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
685
686 return nullptr;
687}
688
689Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
690 Function *Callee = CI->getCalledFunction();
691 FunctionType *FT = Callee->getFunctionType();
692 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
693 !FT->getParamType(1)->isPointerTy() ||
694 !FT->getReturnType()->isPointerTy())
695 return nullptr;
696
697 // fold strstr(x, x) -> x.
698 if (CI->getArgOperand(0) == CI->getArgOperand(1))
699 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
700
701 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000702 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000703 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
704 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000706 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
707 StrLen, B, DL, TLI);
708 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000709 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000710 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
711 ICmpInst *Old = cast<ICmpInst>(*UI++);
712 Value *Cmp =
713 B.CreateICmp(Old->getPredicate(), StrNCmp,
714 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
715 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000716 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000717 return CI;
718 }
Meador Inge17418502012-10-13 16:45:37 +0000719
Chris Bienemanad070d02014-09-17 20:55:46 +0000720 // See if either input string is a constant string.
721 StringRef SearchStr, ToFindStr;
722 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
723 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
724
725 // fold strstr(x, "") -> x.
726 if (HasStr2 && ToFindStr.empty())
727 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
728
729 // If both strings are known, constant fold it.
730 if (HasStr1 && HasStr2) {
731 size_t Offset = SearchStr.find(ToFindStr);
732
733 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000734 return Constant::getNullValue(CI->getType());
735
Chris Bienemanad070d02014-09-17 20:55:46 +0000736 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
737 Value *Result = CastToCStr(CI->getArgOperand(0), B);
738 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
739 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000740 }
Meador Inge17418502012-10-13 16:45:37 +0000741
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 // fold strstr(x, "y") -> strchr(x, 'y').
743 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000744 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000745 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
746 }
747 return nullptr;
748}
Meador Inge40b6fac2012-10-15 03:47:37 +0000749
Benjamin Kramer691363e2015-03-21 15:36:21 +0000750Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
751 Function *Callee = CI->getCalledFunction();
752 FunctionType *FT = Callee->getFunctionType();
753 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
754 !FT->getParamType(1)->isIntegerTy(32) ||
755 !FT->getParamType(2)->isIntegerTy() ||
756 !FT->getReturnType()->isPointerTy())
757 return nullptr;
758
759 Value *SrcStr = CI->getArgOperand(0);
760 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
761 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
762
763 // memchr(x, y, 0) -> null
764 if (LenC && LenC->isNullValue())
765 return Constant::getNullValue(CI->getType());
766
Benjamin Kramer7857d722015-03-21 21:09:33 +0000767 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000768 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000769 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000770 return nullptr;
771
772 // Truncate the string to LenC. If Str is smaller than LenC we will still only
773 // scan the string, as reading past the end of it is undefined and we can just
774 // return null if we don't find the char.
775 Str = Str.substr(0, LenC->getZExtValue());
776
Benjamin Kramer7857d722015-03-21 21:09:33 +0000777 // If the char is variable but the input str and length are not we can turn
778 // this memchr call into a simple bit field test. Of course this only works
779 // when the return value is only checked against null.
780 //
781 // It would be really nice to reuse switch lowering here but we can't change
782 // the CFG at this point.
783 //
784 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
785 // after bounds check.
786 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000787 unsigned char Max =
788 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
789 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000790
791 // Make sure the bit field we're about to create fits in a register on the
792 // target.
793 // FIXME: On a 64 bit architecture this prevents us from using the
794 // interesting range of alpha ascii chars. We could do better by emitting
795 // two bitfields or shifting the range by 64 if no lower chars are used.
796 if (!DL.fitsInLegalInteger(Max + 1))
797 return nullptr;
798
799 // For the bit field use a power-of-2 type with at least 8 bits to avoid
800 // creating unnecessary illegal types.
801 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
802
803 // Now build the bit field.
804 APInt Bitfield(Width, 0);
805 for (char C : Str)
806 Bitfield.setBit((unsigned char)C);
807 Value *BitfieldC = B.getInt(Bitfield);
808
809 // First check that the bit field access is within bounds.
810 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
811 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
812 "memchr.bounds");
813
814 // Create code that checks if the given bit is set in the field.
815 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
816 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
817
818 // Finally merge both checks and cast to pointer type. The inttoptr
819 // implicitly zexts the i1 to intptr type.
820 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
821 }
822
823 // Check if all arguments are constants. If so, we can constant fold.
824 if (!CharC)
825 return nullptr;
826
Benjamin Kramer691363e2015-03-21 15:36:21 +0000827 // Compute the offset.
828 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
829 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
830 return Constant::getNullValue(CI->getType());
831
832 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000833 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000834}
835
Chris Bienemanad070d02014-09-17 20:55:46 +0000836Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
837 Function *Callee = CI->getCalledFunction();
838 FunctionType *FT = Callee->getFunctionType();
839 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
840 !FT->getParamType(1)->isPointerTy() ||
841 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000842 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000843
Chris Bienemanad070d02014-09-17 20:55:46 +0000844 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000845
Chris Bienemanad070d02014-09-17 20:55:46 +0000846 if (LHS == RHS) // memcmp(s,s,x) -> 0
847 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000848
Chris Bienemanad070d02014-09-17 20:55:46 +0000849 // Make sure we have a constant length.
850 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
851 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000852 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000853 uint64_t Len = LenC->getZExtValue();
854
855 if (Len == 0) // memcmp(s1,s2,0) -> 0
856 return Constant::getNullValue(CI->getType());
857
858 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
859 if (Len == 1) {
860 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
861 CI->getType(), "lhsv");
862 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
863 CI->getType(), "rhsv");
864 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000865 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000866
Chad Rosierdc655322015-08-28 18:30:18 +0000867 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
868 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
869
870 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
871 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
872
873 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
874 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
875
876 Type *LHSPtrTy =
877 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
878 Type *RHSPtrTy =
879 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
880
881 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
882 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
883
884 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
885 }
886 }
887
Chris Bienemanad070d02014-09-17 20:55:46 +0000888 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
889 StringRef LHSStr, RHSStr;
890 if (getConstantStringInfo(LHS, LHSStr) &&
891 getConstantStringInfo(RHS, RHSStr)) {
892 // Make sure we're not reading out-of-bounds memory.
893 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000894 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000895 // Fold the memcmp and normalize the result. This way we get consistent
896 // results across multiple platforms.
897 uint64_t Ret = 0;
898 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
899 if (Cmp < 0)
900 Ret = -1;
901 else if (Cmp > 0)
902 Ret = 1;
903 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000904 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000905
Chris Bienemanad070d02014-09-17 20:55:46 +0000906 return nullptr;
907}
Meador Inge9a6a1902012-10-31 00:20:56 +0000908
Chris Bienemanad070d02014-09-17 20:55:46 +0000909Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
910 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000911
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000912 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000913 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000914
Chris Bienemanad070d02014-09-17 20:55:46 +0000915 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
916 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000917 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000918 return CI->getArgOperand(0);
919}
Meador Inge05a625a2012-10-31 14:58:26 +0000920
Chris Bienemanad070d02014-09-17 20:55:46 +0000921Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
922 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000923
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000924 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000925 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000926
Chris Bienemanad070d02014-09-17 20:55:46 +0000927 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
928 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +0000929 CI->getArgOperand(2), 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000930 return CI->getArgOperand(0);
931}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000932
Chris Bienemanad070d02014-09-17 20:55:46 +0000933Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
934 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000935
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000936 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000937 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000938
Chris Bienemanad070d02014-09-17 20:55:46 +0000939 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
940 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
941 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
942 return CI->getArgOperand(0);
943}
Meador Inged4825782012-11-11 06:49:03 +0000944
Meador Inge193e0352012-11-13 04:16:17 +0000945//===----------------------------------------------------------------------===//
946// Math Library Optimizations
947//===----------------------------------------------------------------------===//
948
Matthias Braund34e4d22014-12-03 21:46:33 +0000949/// Return a variant of Val with float type.
950/// Currently this works in two cases: If Val is an FPExtension of a float
951/// value to something bigger, simply return the operand.
952/// If Val is a ConstantFP but can be converted to a float ConstantFP without
953/// loss of precision do so.
954static Value *valueHasFloatPrecision(Value *Val) {
955 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
956 Value *Op = Cast->getOperand(0);
957 if (Op->getType()->isFloatTy())
958 return Op;
959 }
960 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
961 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000962 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000963 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000964 &losesInfo);
965 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000966 return ConstantFP::get(Const->getContext(), F);
967 }
968 return nullptr;
969}
970
Meador Inge193e0352012-11-13 04:16:17 +0000971//===----------------------------------------------------------------------===//
972// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
973
Chris Bienemanad070d02014-09-17 20:55:46 +0000974Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
975 bool CheckRetType) {
976 Function *Callee = CI->getCalledFunction();
977 FunctionType *FT = Callee->getFunctionType();
978 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
979 !FT->getParamType(0)->isDoubleTy())
980 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000981
Chris Bienemanad070d02014-09-17 20:55:46 +0000982 if (CheckRetType) {
983 // Check if all the uses for function like 'sin' are converted to float.
984 for (User *U : CI->users()) {
985 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
986 if (!Cast || !Cast->getType()->isFloatTy())
987 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000988 }
Meador Inge193e0352012-11-13 04:16:17 +0000989 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000990
991 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000992 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
993 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000994 return nullptr;
995
996 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +0000997 if (Callee->isIntrinsic()) {
998 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +0000999 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001000 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1001 V = B.CreateCall(F, V);
1002 } else {
1003 // The call is a library call rather than an intrinsic.
1004 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1005 }
1006
Chris Bienemanad070d02014-09-17 20:55:46 +00001007 return B.CreateFPExt(V, B.getDoubleTy());
1008}
Meador Inge193e0352012-11-13 04:16:17 +00001009
Yi Jiang6ab044e2013-12-16 22:42:40 +00001010// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001011Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1012 Function *Callee = CI->getCalledFunction();
1013 FunctionType *FT = Callee->getFunctionType();
1014 // Just make sure this has 2 arguments of the same FP type, which match the
1015 // result type.
1016 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1017 FT->getParamType(0) != FT->getParamType(1) ||
1018 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001019 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001020
Chris Bienemanad070d02014-09-17 20:55:46 +00001021 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001022 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1023 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1024 if (V1 == nullptr)
1025 return nullptr;
1026 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1027 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001028 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001029
1030 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001031 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001032 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001033 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1034 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001035 return B.CreateFPExt(V, B.getDoubleTy());
1036}
1037
1038Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1039 Function *Callee = CI->getCalledFunction();
1040 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001041 StringRef Name = Callee->getName();
1042 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001043 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001044
Chris Bienemanad070d02014-09-17 20:55:46 +00001045 FunctionType *FT = Callee->getFunctionType();
1046 // Just make sure this has 1 argument of FP type, which matches the
1047 // result type.
1048 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1049 !FT->getParamType(0)->isFloatingPointTy())
1050 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001051
Chris Bienemanad070d02014-09-17 20:55:46 +00001052 // cos(-x) -> cos(x)
1053 Value *Op1 = CI->getArgOperand(0);
1054 if (BinaryOperator::isFNeg(Op1)) {
1055 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1056 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1057 }
1058 return Ret;
1059}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001060
Chris Bienemanad070d02014-09-17 20:55:46 +00001061Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1062 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001063 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001064 StringRef Name = Callee->getName();
1065 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001066 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001067
Chris Bienemanad070d02014-09-17 20:55:46 +00001068 FunctionType *FT = Callee->getFunctionType();
1069 // Just make sure this has 2 arguments of the same FP type, which match the
1070 // result type.
1071 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1072 FT->getParamType(0) != FT->getParamType(1) ||
1073 !FT->getParamType(0)->isFloatingPointTy())
1074 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001075
Chris Bienemanad070d02014-09-17 20:55:46 +00001076 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1077 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1078 // pow(1.0, x) -> 1.0
1079 if (Op1C->isExactlyValue(1.0))
1080 return Op1C;
1081 // pow(2.0, x) -> exp2(x)
1082 if (Op1C->isExactlyValue(2.0) &&
1083 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1084 LibFunc::exp2l))
Davide Italianod9f87b42015-11-06 21:05:07 +00001085 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1086 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001087 // pow(10.0, x) -> exp10(x)
1088 if (Op1C->isExactlyValue(10.0) &&
1089 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1090 LibFunc::exp10l))
1091 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1092 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001093 }
1094
Davide Italianoc5cedd12015-11-18 23:21:32 +00001095 bool unsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1096
Davide Italianoc8a79132015-11-03 20:32:23 +00001097 // pow(exp(x), y) -> exp(x*y)
1098 // pow(exp2(x), y) -> exp2(x * y)
1099 // We enable these only under fast-math. Besides rounding
1100 // differences the transformation changes overflow and
1101 // underflow behavior quite dramatically.
1102 // Example: x = 1000, y = 0.001.
1103 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Davide Italianoc5cedd12015-11-18 23:21:32 +00001104 if (unsafeFPMath) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001105 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1106 IRBuilder<>::FastMathFlagGuard Guard(B);
1107 FastMathFlags FMF;
1108 FMF.setUnsafeAlgebra();
1109 B.SetFastMathFlags(FMF);
1110
1111 LibFunc::Func Func;
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001112 Function *OpCCallee = OpC->getCalledFunction();
1113 if (OpCCallee && TLI->getLibFunc(OpCCallee->getName(), Func) &&
1114 TLI->has(Func) && (Func == LibFunc::exp || Func == LibFunc::exp2))
Davide Italianoc8a79132015-11-03 20:32:23 +00001115 return EmitUnaryFloatFnCall(
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001116 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"),
1117 OpCCallee->getName(), B, OpCCallee->getAttributes());
Davide Italianoc8a79132015-11-03 20:32:23 +00001118 }
1119 }
1120
Chris Bienemanad070d02014-09-17 20:55:46 +00001121 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1122 if (!Op2C)
1123 return Ret;
1124
1125 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1126 return ConstantFP::get(CI->getType(), 1.0);
1127
1128 if (Op2C->isExactlyValue(0.5) &&
1129 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1130 LibFunc::sqrtl) &&
1131 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1132 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001133
1134 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1135 if (unsafeFPMath)
1136 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1137 Callee->getAttributes());
1138
Chris Bienemanad070d02014-09-17 20:55:46 +00001139 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1140 // This is faster than calling pow, and still handles negative zero
1141 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001142 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1143 Value *Inf = ConstantFP::getInfinity(CI->getType());
1144 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1145 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1146 Value *FAbs =
1147 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1148 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1149 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1150 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001151 }
1152
Chris Bienemanad070d02014-09-17 20:55:46 +00001153 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1154 return Op1;
1155 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1156 return B.CreateFMul(Op1, Op1, "pow2");
1157 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1158 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1159 return nullptr;
1160}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001161
Chris Bienemanad070d02014-09-17 20:55:46 +00001162Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1163 Function *Callee = CI->getCalledFunction();
1164 Function *Caller = CI->getParent()->getParent();
Chris Bienemanad070d02014-09-17 20:55:46 +00001165 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001166 StringRef Name = Callee->getName();
1167 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001168 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001169
Chris Bienemanad070d02014-09-17 20:55:46 +00001170 FunctionType *FT = Callee->getFunctionType();
1171 // Just make sure this has 1 argument of FP type, which matches the
1172 // result type.
1173 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1174 !FT->getParamType(0)->isFloatingPointTy())
1175 return Ret;
1176
1177 Value *Op = CI->getArgOperand(0);
1178 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1179 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1180 LibFunc::Func LdExp = LibFunc::ldexpl;
1181 if (Op->getType()->isFloatTy())
1182 LdExp = LibFunc::ldexpf;
1183 else if (Op->getType()->isDoubleTy())
1184 LdExp = LibFunc::ldexp;
1185
1186 if (TLI->has(LdExp)) {
1187 Value *LdExpArg = nullptr;
1188 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1189 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1190 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1191 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1192 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1193 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1194 }
1195
1196 if (LdExpArg) {
1197 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1198 if (!Op->getType()->isFloatTy())
1199 One = ConstantExpr::getFPExtend(One, Op->getType());
1200
1201 Module *M = Caller->getParent();
1202 Value *Callee =
1203 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001204 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001205 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001206 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1207 CI->setCallingConv(F->getCallingConv());
1208
1209 return CI;
1210 }
1211 }
1212 return Ret;
1213}
1214
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001215Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1216 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001217 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001218 StringRef Name = Callee->getName();
1219 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001220 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001221
1222 FunctionType *FT = Callee->getFunctionType();
1223 // Make sure this has 1 argument of FP type which matches the result type.
1224 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1225 !FT->getParamType(0)->isFloatingPointTy())
1226 return Ret;
1227
1228 Value *Op = CI->getArgOperand(0);
1229 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1230 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1231 if (I->getOpcode() == Instruction::FMul)
1232 if (I->getOperand(0) == I->getOperand(1))
1233 return Op;
1234 }
1235 return Ret;
1236}
1237
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001238Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1239 // If we can shrink the call to a float function rather than a double
1240 // function, do that first.
1241 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001242 StringRef Name = Callee->getName();
1243 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1244 (Name == "fmax" && hasFloatVersion(Name))) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001245 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1246 if (Ret)
1247 return Ret;
1248 }
1249
1250 // Make sure this has 2 arguments of FP type which match the result type.
1251 FunctionType *FT = Callee->getFunctionType();
1252 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1253 FT->getParamType(0) != FT->getParamType(1) ||
1254 !FT->getParamType(0)->isFloatingPointTy())
1255 return nullptr;
1256
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001257 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001258 FastMathFlags FMF;
1259 Function *F = CI->getParent()->getParent();
Davide Italianoa904e522015-10-29 02:58:44 +00001260 if (canUseUnsafeFPMath(F)) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001261 // Unsafe algebra sets all fast-math-flags to true.
1262 FMF.setUnsafeAlgebra();
1263 } else {
1264 // At a minimum, no-nans-fp-math must be true.
Davide Italianoa904e522015-10-29 02:58:44 +00001265 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001266 if (Attr.getValueAsString() != "true")
1267 return nullptr;
1268 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1269 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001270 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001271 // might be impractical."
1272 FMF.setNoSignedZeros();
1273 FMF.setNoNaNs();
1274 }
1275 B.SetFastMathFlags(FMF);
1276
1277 // We have a relaxed floating-point environment. We can ignore NaN-handling
1278 // and transform to a compare and select. We do not have to consider errno or
1279 // exceptions, because fmin/fmax do not have those.
1280 Value *Op0 = CI->getArgOperand(0);
1281 Value *Op1 = CI->getArgOperand(1);
1282 Value *Cmp = Callee->getName().startswith("fmin") ?
1283 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1284 return B.CreateSelect(Cmp, Op0, Op1);
1285}
1286
Davide Italianob8b71332015-11-29 20:58:04 +00001287Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
1288 Function *Callee = CI->getCalledFunction();
1289 Value *Ret = nullptr;
1290 StringRef Name = Callee->getName();
1291 if (UnsafeFPShrink && hasFloatVersion(Name))
1292 Ret = optimizeUnaryDoubleFP(CI, B, true);
1293 FunctionType *FT = Callee->getFunctionType();
1294
1295 // Just make sure this has 1 argument of FP type, which matches the
1296 // result type.
1297 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1298 !FT->getParamType(0)->isFloatingPointTy())
1299 return Ret;
1300
1301 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1302 return Ret;
1303 Value *Op1 = CI->getArgOperand(0);
1304 auto *OpC = dyn_cast<CallInst>(Op1);
1305 if (!OpC)
1306 return Ret;
1307
1308 // log(pow(x,y)) -> y*log(x)
1309 // This is only applicable to log, log2, log10.
1310 if (Name != "log" && Name != "log2" && Name != "log10")
1311 return Ret;
1312
1313 IRBuilder<>::FastMathFlagGuard Guard(B);
1314 FastMathFlags FMF;
1315 FMF.setUnsafeAlgebra();
1316 B.SetFastMathFlags(FMF);
1317
1318 LibFunc::Func Func;
1319 Function *F = OpC->getCalledFunction();
1320 StringRef FuncName = F->getName();
1321 if ((TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1322 Func == LibFunc::pow) || F->getIntrinsicID() == Intrinsic::pow)
1323 return B.CreateFMul(OpC->getArgOperand(1),
1324 EmitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
1325 Callee->getAttributes()), "mul");
1326 return Ret;
1327}
1328
Sanjay Patelc699a612014-10-16 18:48:17 +00001329Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1330 Function *Callee = CI->getCalledFunction();
1331
1332 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001333 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1334 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001335 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianoa904e522015-10-29 02:58:44 +00001336 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1337 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001338
Sanjay Patelc699a612014-10-16 18:48:17 +00001339 Value *Op = CI->getArgOperand(0);
1340 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1341 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1342 // We're looking for a repeated factor in a multiplication tree,
1343 // so we can do this fold: sqrt(x * x) -> fabs(x);
1344 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1345 Value *Op0 = I->getOperand(0);
1346 Value *Op1 = I->getOperand(1);
1347 Value *RepeatOp = nullptr;
1348 Value *OtherOp = nullptr;
1349 if (Op0 == Op1) {
1350 // Simple match: the operands of the multiply are identical.
1351 RepeatOp = Op0;
1352 } else {
1353 // Look for a more complicated pattern: one of the operands is itself
1354 // a multiply, so search for a common factor in that multiply.
1355 // Note: We don't bother looking any deeper than this first level or for
1356 // variations of this pattern because instcombine's visitFMUL and/or the
1357 // reassociation pass should give us this form.
1358 Value *OtherMul0, *OtherMul1;
1359 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1360 // Pattern: sqrt((x * y) * z)
1361 if (OtherMul0 == OtherMul1) {
1362 // Matched: sqrt((x * x) * z)
1363 RepeatOp = OtherMul0;
1364 OtherOp = Op1;
1365 }
1366 }
1367 }
1368 if (RepeatOp) {
1369 // Fast math flags for any created instructions should match the sqrt
1370 // and multiply.
1371 // FIXME: We're not checking the sqrt because it doesn't have
1372 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001373 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001374 B.SetFastMathFlags(I->getFastMathFlags());
1375 // If we found a repeated factor, hoist it out of the square root and
1376 // replace it with the fabs of that factor.
1377 Module *M = Callee->getParent();
1378 Type *ArgType = Op->getType();
1379 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1380 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1381 if (OtherOp) {
1382 // If we found a non-repeated factor, we still need to get its square
1383 // root. We then multiply that by the value that was simplified out
1384 // of the square root calculation.
1385 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1386 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1387 return B.CreateFMul(FabsCall, SqrtCall);
1388 }
1389 return FabsCall;
1390 }
1391 }
1392 }
1393 return Ret;
1394}
1395
Davide Italiano51507d22015-11-04 23:36:56 +00001396Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1397 Function *Callee = CI->getCalledFunction();
1398 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001399 StringRef Name = Callee->getName();
1400 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001401 Ret = optimizeUnaryDoubleFP(CI, B, true);
1402 FunctionType *FT = Callee->getFunctionType();
1403
1404 // Just make sure this has 1 argument of FP type, which matches the
1405 // result type.
1406 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1407 !FT->getParamType(0)->isFloatingPointTy())
1408 return Ret;
1409
1410 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1411 return Ret;
1412 Value *Op1 = CI->getArgOperand(0);
1413 auto *OpC = dyn_cast<CallInst>(Op1);
1414 if (!OpC)
1415 return Ret;
1416
1417 // tan(atan(x)) -> x
1418 // tanf(atanf(x)) -> x
1419 // tanl(atanl(x)) -> x
1420 LibFunc::Func Func;
1421 Function *F = OpC->getCalledFunction();
Benjamin Kramerfb419e72015-11-26 09:51:17 +00001422 if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
Davide Italiano51507d22015-11-04 23:36:56 +00001423 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1424 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1425 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1426 Ret = OpC->getArgOperand(0);
1427 return Ret;
1428}
1429
Chris Bienemanad070d02014-09-17 20:55:46 +00001430static bool isTrigLibCall(CallInst *CI);
1431static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1432 bool UseFloat, Value *&Sin, Value *&Cos,
1433 Value *&SinCos);
1434
1435Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1436
1437 // Make sure the prototype is as expected, otherwise the rest of the
1438 // function is probably invalid and likely to abort.
1439 if (!isTrigLibCall(CI))
1440 return nullptr;
1441
1442 Value *Arg = CI->getArgOperand(0);
1443 SmallVector<CallInst *, 1> SinCalls;
1444 SmallVector<CallInst *, 1> CosCalls;
1445 SmallVector<CallInst *, 1> SinCosCalls;
1446
1447 bool IsFloat = Arg->getType()->isFloatTy();
1448
1449 // Look for all compatible sinpi, cospi and sincospi calls with the same
1450 // argument. If there are enough (in some sense) we can make the
1451 // substitution.
1452 for (User *U : Arg->users())
1453 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1454 SinCosCalls);
1455
1456 // It's only worthwhile if both sinpi and cospi are actually used.
1457 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1458 return nullptr;
1459
1460 Value *Sin, *Cos, *SinCos;
1461 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1462
1463 replaceTrigInsts(SinCalls, Sin);
1464 replaceTrigInsts(CosCalls, Cos);
1465 replaceTrigInsts(SinCosCalls, SinCos);
1466
1467 return nullptr;
1468}
1469
1470static bool isTrigLibCall(CallInst *CI) {
1471 Function *Callee = CI->getCalledFunction();
1472 FunctionType *FT = Callee->getFunctionType();
1473
1474 // We can only hope to do anything useful if we can ignore things like errno
1475 // and floating-point exceptions.
1476 bool AttributesSafe =
1477 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1478
1479 // Other than that we need float(float) or double(double)
1480 return AttributesSafe && FT->getNumParams() == 1 &&
1481 FT->getReturnType() == FT->getParamType(0) &&
1482 (FT->getParamType(0)->isFloatTy() ||
1483 FT->getParamType(0)->isDoubleTy());
1484}
1485
1486void
1487LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1488 SmallVectorImpl<CallInst *> &SinCalls,
1489 SmallVectorImpl<CallInst *> &CosCalls,
1490 SmallVectorImpl<CallInst *> &SinCosCalls) {
1491 CallInst *CI = dyn_cast<CallInst>(Val);
1492
1493 if (!CI)
1494 return;
1495
1496 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001497 LibFunc::Func Func;
Benjamin Kramer89766e52015-11-28 21:43:12 +00001498 if (!Callee || !TLI->getLibFunc(Callee->getName(), Func) || !TLI->has(Func) ||
1499 !isTrigLibCall(CI))
Chris Bienemanad070d02014-09-17 20:55:46 +00001500 return;
1501
1502 if (IsFloat) {
1503 if (Func == LibFunc::sinpif)
1504 SinCalls.push_back(CI);
1505 else if (Func == LibFunc::cospif)
1506 CosCalls.push_back(CI);
1507 else if (Func == LibFunc::sincospif_stret)
1508 SinCosCalls.push_back(CI);
1509 } else {
1510 if (Func == LibFunc::sinpi)
1511 SinCalls.push_back(CI);
1512 else if (Func == LibFunc::cospi)
1513 CosCalls.push_back(CI);
1514 else if (Func == LibFunc::sincospi_stret)
1515 SinCosCalls.push_back(CI);
1516 }
1517}
1518
1519void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1520 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001521 for (CallInst *C : Calls)
1522 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001523}
1524
1525void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1526 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1527 Type *ArgTy = Arg->getType();
1528 Type *ResTy;
1529 StringRef Name;
1530
1531 Triple T(OrigCallee->getParent()->getTargetTriple());
1532 if (UseFloat) {
1533 Name = "__sincospif_stret";
1534
1535 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1536 // x86_64 can't use {float, float} since that would be returned in both
1537 // xmm0 and xmm1, which isn't what a real struct would do.
1538 ResTy = T.getArch() == Triple::x86_64
1539 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001540 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001541 } else {
1542 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001543 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001544 }
1545
1546 Module *M = OrigCallee->getParent();
1547 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001548 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001549
1550 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1551 // If the argument is an instruction, it must dominate all uses so put our
1552 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001553 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001554 } else {
1555 // Otherwise (e.g. for a constant) the beginning of the function is as
1556 // good a place as any.
1557 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1558 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1559 }
1560
1561 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1562
1563 if (SinCos->getType()->isStructTy()) {
1564 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1565 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1566 } else {
1567 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1568 "sinpi");
1569 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1570 "cospi");
1571 }
1572}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001573
Meador Inge7415f842012-11-25 20:45:27 +00001574//===----------------------------------------------------------------------===//
1575// Integer Library Call Optimizations
1576//===----------------------------------------------------------------------===//
1577
Davide Italiano396f3ee2015-10-31 23:17:45 +00001578static bool checkIntUnaryReturnAndParam(Function *Callee) {
1579 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001580 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1581 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001582}
1583
Chris Bienemanad070d02014-09-17 20:55:46 +00001584Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1585 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001586 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001587 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001588 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001589
Chris Bienemanad070d02014-09-17 20:55:46 +00001590 // Constant fold.
1591 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1592 if (CI->isZero()) // ffs(0) -> 0.
1593 return B.getInt32(0);
1594 // ffs(c) -> cttz(c)+1
1595 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001596 }
Meador Inge7415f842012-11-25 20:45:27 +00001597
Chris Bienemanad070d02014-09-17 20:55:46 +00001598 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1599 Type *ArgType = Op->getType();
1600 Value *F =
1601 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001602 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001603 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1604 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001605
Chris Bienemanad070d02014-09-17 20:55:46 +00001606 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1607 return B.CreateSelect(Cond, V, B.getInt32(0));
1608}
Meador Ingea0b6d872012-11-26 00:24:07 +00001609
Chris Bienemanad070d02014-09-17 20:55:46 +00001610Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1611 Function *Callee = CI->getCalledFunction();
1612 FunctionType *FT = Callee->getFunctionType();
1613 // We require integer(integer) where the types agree.
1614 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1615 FT->getParamType(0) != FT->getReturnType())
1616 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001617
Chris Bienemanad070d02014-09-17 20:55:46 +00001618 // abs(x) -> x >s -1 ? x : -x
1619 Value *Op = CI->getArgOperand(0);
1620 Value *Pos =
1621 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1622 Value *Neg = B.CreateNeg(Op, "neg");
1623 return B.CreateSelect(Pos, Op, Neg);
1624}
Meador Inge9a59ab62012-11-26 02:31:59 +00001625
Chris Bienemanad070d02014-09-17 20:55:46 +00001626Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001627 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001628 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001629
Chris Bienemanad070d02014-09-17 20:55:46 +00001630 // isdigit(c) -> (c-'0') <u 10
1631 Value *Op = CI->getArgOperand(0);
1632 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1633 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1634 return B.CreateZExt(Op, CI->getType());
1635}
Meador Ingea62a39e2012-11-26 03:10:07 +00001636
Chris Bienemanad070d02014-09-17 20:55:46 +00001637Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001638 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001639 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001640
Chris Bienemanad070d02014-09-17 20:55:46 +00001641 // isascii(c) -> c <u 128
1642 Value *Op = CI->getArgOperand(0);
1643 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1644 return B.CreateZExt(Op, CI->getType());
1645}
1646
1647Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001648 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001649 return nullptr;
1650
1651 // toascii(c) -> c & 0x7f
1652 return B.CreateAnd(CI->getArgOperand(0),
1653 ConstantInt::get(CI->getType(), 0x7F));
1654}
Meador Inge604937d2012-11-26 03:38:52 +00001655
Meador Inge08ca1152012-11-26 20:37:20 +00001656//===----------------------------------------------------------------------===//
1657// Formatting and IO Library Call Optimizations
1658//===----------------------------------------------------------------------===//
1659
Chris Bienemanad070d02014-09-17 20:55:46 +00001660static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001661
Chris Bienemanad070d02014-09-17 20:55:46 +00001662Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1663 int StreamArg) {
1664 // Error reporting calls should be cold, mark them as such.
1665 // This applies even to non-builtin calls: it is only a hint and applies to
1666 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001667
Chris Bienemanad070d02014-09-17 20:55:46 +00001668 // This heuristic was suggested in:
1669 // Improving Static Branch Prediction in a Compiler
1670 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1671 // Proceedings of PACT'98, Oct. 1998, IEEE
1672 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001673
Chris Bienemanad070d02014-09-17 20:55:46 +00001674 if (!CI->hasFnAttr(Attribute::Cold) &&
1675 isReportingError(Callee, CI, StreamArg)) {
1676 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1677 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001678
Chris Bienemanad070d02014-09-17 20:55:46 +00001679 return nullptr;
1680}
1681
1682static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001683 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001684 return false;
1685
1686 if (StreamArg < 0)
1687 return true;
1688
1689 // These functions might be considered cold, but only if their stream
1690 // argument is stderr.
1691
1692 if (StreamArg >= (int)CI->getNumArgOperands())
1693 return false;
1694 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1695 if (!LI)
1696 return false;
1697 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1698 if (!GV || !GV->isDeclaration())
1699 return false;
1700 return GV->getName() == "stderr";
1701}
1702
1703Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1704 // Check for a fixed format string.
1705 StringRef FormatStr;
1706 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001707 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001708
Chris Bienemanad070d02014-09-17 20:55:46 +00001709 // Empty format string -> noop.
1710 if (FormatStr.empty()) // Tolerate printf's declared void.
1711 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001712
Chris Bienemanad070d02014-09-17 20:55:46 +00001713 // Do not do any of the following transformations if the printf return value
1714 // is used, in general the printf return value is not compatible with either
1715 // putchar() or puts().
1716 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001717 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001718
1719 // printf("x") -> putchar('x'), even for '%'.
1720 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001721 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001722 if (CI->use_empty() || !Res)
1723 return Res;
1724 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001725 }
1726
Chris Bienemanad070d02014-09-17 20:55:46 +00001727 // printf("foo\n") --> puts("foo")
1728 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1729 FormatStr.find('%') == StringRef::npos) { // No format characters.
1730 // Create a string literal with no \n on it. We expect the constant merge
1731 // pass to be run after this pass, to merge duplicate strings.
1732 FormatStr = FormatStr.drop_back();
1733 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001734 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001735 return (CI->use_empty() || !NewCI)
1736 ? NewCI
1737 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1738 }
Meador Inge08ca1152012-11-26 20:37:20 +00001739
Chris Bienemanad070d02014-09-17 20:55:46 +00001740 // Optimize specific format strings.
1741 // printf("%c", chr) --> putchar(chr)
1742 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1743 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001744 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001745
Chris Bienemanad070d02014-09-17 20:55:46 +00001746 if (CI->use_empty() || !Res)
1747 return Res;
1748 return B.CreateIntCast(Res, CI->getType(), true);
1749 }
1750
1751 // printf("%s\n", str) --> puts(str)
1752 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1753 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001754 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001755 }
1756 return nullptr;
1757}
1758
1759Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1760
1761 Function *Callee = CI->getCalledFunction();
1762 // Require one fixed pointer argument and an integer/void result.
1763 FunctionType *FT = Callee->getFunctionType();
1764 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1765 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1766 return nullptr;
1767
1768 if (Value *V = optimizePrintFString(CI, B)) {
1769 return V;
1770 }
1771
1772 // printf(format, ...) -> iprintf(format, ...) if no floating point
1773 // arguments.
1774 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1775 Module *M = B.GetInsertBlock()->getParent()->getParent();
1776 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001777 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001778 CallInst *New = cast<CallInst>(CI->clone());
1779 New->setCalledFunction(IPrintFFn);
1780 B.Insert(New);
1781 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001782 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001783 return nullptr;
1784}
Meador Inge08ca1152012-11-26 20:37:20 +00001785
Chris Bienemanad070d02014-09-17 20:55:46 +00001786Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1787 // Check for a fixed format string.
1788 StringRef FormatStr;
1789 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001790 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001791
Chris Bienemanad070d02014-09-17 20:55:46 +00001792 // If we just have a format string (nothing else crazy) transform it.
1793 if (CI->getNumArgOperands() == 2) {
1794 // Make sure there's no % in the constant array. We could try to handle
1795 // %% -> % in the future if we cared.
1796 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1797 if (FormatStr[i] == '%')
1798 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001799
Chris Bienemanad070d02014-09-17 20:55:46 +00001800 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001801 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1802 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1803 FormatStr.size() + 1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00001804 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001805 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001806 }
Meador Ingef8e72502012-11-29 15:45:43 +00001807
Chris Bienemanad070d02014-09-17 20:55:46 +00001808 // The remaining optimizations require the format string to be "%s" or "%c"
1809 // and have an extra operand.
1810 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1811 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001812 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001813
Chris Bienemanad070d02014-09-17 20:55:46 +00001814 // Decode the second character of the format string.
1815 if (FormatStr[1] == 'c') {
1816 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1817 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1818 return nullptr;
1819 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1820 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1821 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001822 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001823 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001824
Chris Bienemanad070d02014-09-17 20:55:46 +00001825 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001826 }
1827
Chris Bienemanad070d02014-09-17 20:55:46 +00001828 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001829 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1830 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1831 return nullptr;
1832
1833 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1834 if (!Len)
1835 return nullptr;
1836 Value *IncLen =
1837 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper67cf9a72015-11-19 05:56:52 +00001838 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001839
1840 // The sprintf result is the unincremented number of bytes in the string.
1841 return B.CreateIntCast(Len, CI->getType(), false);
1842 }
1843 return nullptr;
1844}
1845
1846Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1847 Function *Callee = CI->getCalledFunction();
1848 // Require two fixed pointer arguments and an integer result.
1849 FunctionType *FT = Callee->getFunctionType();
1850 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1851 !FT->getParamType(1)->isPointerTy() ||
1852 !FT->getReturnType()->isIntegerTy())
1853 return nullptr;
1854
1855 if (Value *V = optimizeSPrintFString(CI, B)) {
1856 return V;
1857 }
1858
1859 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1860 // point arguments.
1861 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1862 Module *M = B.GetInsertBlock()->getParent()->getParent();
1863 Constant *SIPrintFFn =
1864 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1865 CallInst *New = cast<CallInst>(CI->clone());
1866 New->setCalledFunction(SIPrintFFn);
1867 B.Insert(New);
1868 return New;
1869 }
1870 return nullptr;
1871}
1872
1873Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1874 optimizeErrorReporting(CI, B, 0);
1875
1876 // All the optimizations depend on the format string.
1877 StringRef FormatStr;
1878 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1879 return nullptr;
1880
1881 // Do not do any of the following transformations if the fprintf return
1882 // value is used, in general the fprintf return value is not compatible
1883 // with fwrite(), fputc() or fputs().
1884 if (!CI->use_empty())
1885 return nullptr;
1886
1887 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1888 if (CI->getNumArgOperands() == 2) {
1889 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1890 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1891 return nullptr; // We found a format specifier.
1892
Chris Bienemanad070d02014-09-17 20:55:46 +00001893 return EmitFWrite(
1894 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001895 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001896 CI->getArgOperand(0), B, DL, TLI);
1897 }
1898
1899 // The remaining optimizations require the format string to be "%s" or "%c"
1900 // and have an extra operand.
1901 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1902 CI->getNumArgOperands() < 3)
1903 return nullptr;
1904
1905 // Decode the second character of the format string.
1906 if (FormatStr[1] == 'c') {
1907 // fprintf(F, "%c", chr) --> fputc(chr, F)
1908 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1909 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001910 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001911 }
1912
1913 if (FormatStr[1] == 's') {
1914 // fprintf(F, "%s", str) --> fputs(str, F)
1915 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1916 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001917 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001918 }
1919 return nullptr;
1920}
1921
1922Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1923 Function *Callee = CI->getCalledFunction();
1924 // Require two fixed paramters as pointers and integer result.
1925 FunctionType *FT = Callee->getFunctionType();
1926 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1927 !FT->getParamType(1)->isPointerTy() ||
1928 !FT->getReturnType()->isIntegerTy())
1929 return nullptr;
1930
1931 if (Value *V = optimizeFPrintFString(CI, B)) {
1932 return V;
1933 }
1934
1935 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1936 // floating point arguments.
1937 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1938 Module *M = B.GetInsertBlock()->getParent()->getParent();
1939 Constant *FIPrintFFn =
1940 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1941 CallInst *New = cast<CallInst>(CI->clone());
1942 New->setCalledFunction(FIPrintFFn);
1943 B.Insert(New);
1944 return New;
1945 }
1946 return nullptr;
1947}
1948
1949Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1950 optimizeErrorReporting(CI, B, 3);
1951
1952 Function *Callee = CI->getCalledFunction();
1953 // Require a pointer, an integer, an integer, a pointer, returning integer.
1954 FunctionType *FT = Callee->getFunctionType();
1955 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1956 !FT->getParamType(1)->isIntegerTy() ||
1957 !FT->getParamType(2)->isIntegerTy() ||
1958 !FT->getParamType(3)->isPointerTy() ||
1959 !FT->getReturnType()->isIntegerTy())
1960 return nullptr;
1961
1962 // Get the element size and count.
1963 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1964 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1965 if (!SizeC || !CountC)
1966 return nullptr;
1967 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1968
1969 // If this is writing zero records, remove the call (it's a noop).
1970 if (Bytes == 0)
1971 return ConstantInt::get(CI->getType(), 0);
1972
1973 // If this is writing one byte, turn it into fputc.
1974 // This optimisation is only valid, if the return value is unused.
1975 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1976 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001977 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001978 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1979 }
1980
1981 return nullptr;
1982}
1983
1984Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1985 optimizeErrorReporting(CI, B, 1);
1986
1987 Function *Callee = CI->getCalledFunction();
1988
Chris Bienemanad070d02014-09-17 20:55:46 +00001989 // Require two pointers. Also, we can't optimize if return value is used.
1990 FunctionType *FT = Callee->getFunctionType();
1991 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1992 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1993 return nullptr;
1994
1995 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1996 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1997 if (!Len)
1998 return nullptr;
1999
2000 // Known to have no uses (see above).
2001 return EmitFWrite(
2002 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002003 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00002004 CI->getArgOperand(1), B, DL, TLI);
2005}
2006
2007Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
2008 Function *Callee = CI->getCalledFunction();
2009 // Require one fixed pointer argument and an integer/void result.
2010 FunctionType *FT = Callee->getFunctionType();
2011 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
2012 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
2013 return nullptr;
2014
2015 // Check for a constant string.
2016 StringRef Str;
2017 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
2018 return nullptr;
2019
2020 if (Str.empty() && CI->use_empty()) {
2021 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002022 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00002023 if (CI->use_empty() || !Res)
2024 return Res;
2025 return B.CreateIntCast(Res, CI->getType(), true);
2026 }
2027
2028 return nullptr;
2029}
2030
2031bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002032 LibFunc::Func Func;
2033 SmallString<20> FloatFuncName = FuncName;
2034 FloatFuncName += 'f';
2035 if (TLI->getLibFunc(FloatFuncName, Func))
2036 return TLI->has(Func);
2037 return false;
2038}
Meador Inge7fb2f732012-10-13 16:45:32 +00002039
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002040Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2041 IRBuilder<> &Builder) {
2042 LibFunc::Func Func;
2043 Function *Callee = CI->getCalledFunction();
2044 StringRef FuncName = Callee->getName();
2045
2046 // Check for string/memory library functions.
2047 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2048 // Make sure we never change the calling convention.
2049 assert((ignoreCallingConv(Func) ||
2050 CI->getCallingConv() == llvm::CallingConv::C) &&
2051 "Optimizing string/memory libcall would change the calling convention");
2052 switch (Func) {
2053 case LibFunc::strcat:
2054 return optimizeStrCat(CI, Builder);
2055 case LibFunc::strncat:
2056 return optimizeStrNCat(CI, Builder);
2057 case LibFunc::strchr:
2058 return optimizeStrChr(CI, Builder);
2059 case LibFunc::strrchr:
2060 return optimizeStrRChr(CI, Builder);
2061 case LibFunc::strcmp:
2062 return optimizeStrCmp(CI, Builder);
2063 case LibFunc::strncmp:
2064 return optimizeStrNCmp(CI, Builder);
2065 case LibFunc::strcpy:
2066 return optimizeStrCpy(CI, Builder);
2067 case LibFunc::stpcpy:
2068 return optimizeStpCpy(CI, Builder);
2069 case LibFunc::strncpy:
2070 return optimizeStrNCpy(CI, Builder);
2071 case LibFunc::strlen:
2072 return optimizeStrLen(CI, Builder);
2073 case LibFunc::strpbrk:
2074 return optimizeStrPBrk(CI, Builder);
2075 case LibFunc::strtol:
2076 case LibFunc::strtod:
2077 case LibFunc::strtof:
2078 case LibFunc::strtoul:
2079 case LibFunc::strtoll:
2080 case LibFunc::strtold:
2081 case LibFunc::strtoull:
2082 return optimizeStrTo(CI, Builder);
2083 case LibFunc::strspn:
2084 return optimizeStrSpn(CI, Builder);
2085 case LibFunc::strcspn:
2086 return optimizeStrCSpn(CI, Builder);
2087 case LibFunc::strstr:
2088 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002089 case LibFunc::memchr:
2090 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002091 case LibFunc::memcmp:
2092 return optimizeMemCmp(CI, Builder);
2093 case LibFunc::memcpy:
2094 return optimizeMemCpy(CI, Builder);
2095 case LibFunc::memmove:
2096 return optimizeMemMove(CI, Builder);
2097 case LibFunc::memset:
2098 return optimizeMemSet(CI, Builder);
2099 default:
2100 break;
2101 }
2102 }
2103 return nullptr;
2104}
2105
Chris Bienemanad070d02014-09-17 20:55:46 +00002106Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2107 if (CI->isNoBuiltin())
2108 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002109
Meador Inge20255ef2013-03-12 00:08:29 +00002110 LibFunc::Func Func;
2111 Function *Callee = CI->getCalledFunction();
2112 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002113 IRBuilder<> Builder(CI);
2114 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002115
Sanjay Patela92fa442014-10-22 15:29:23 +00002116 // Command-line parameter overrides function attribute.
2117 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2118 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002119 else if (canUseUnsafeFPMath(Callee))
2120 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002121
Sanjay Patel848309d2014-10-23 21:52:45 +00002122 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002123 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002124 if (!isCallingConvC)
2125 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002126 switch (II->getIntrinsicID()) {
2127 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002128 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002129 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002130 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002131 case Intrinsic::fabs:
2132 return optimizeFabs(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002133 case Intrinsic::log:
2134 return optimizeLog(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002135 case Intrinsic::sqrt:
2136 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002137 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002138 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002139 }
2140 }
2141
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002142 // Also try to simplify calls to fortified library functions.
2143 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2144 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002145 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002146 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2147 // Use an IR Builder from SimplifiedCI if available instead of CI
2148 // to guarantee we reach all uses we might replace later on.
2149 IRBuilder<> TmpBuilder(SimplifiedCI);
2150 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002151 // If we were able to further simplify, remove the now redundant call.
2152 SimplifiedCI->replaceAllUsesWith(V);
2153 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002154 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002155 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002156 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002157 return SimplifiedFortifiedCI;
2158 }
2159
Meador Inge20255ef2013-03-12 00:08:29 +00002160 // Then check for known library functions.
2161 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002162 // We never change the calling convention.
2163 if (!ignoreCallingConv(Func) && !isCallingConvC)
2164 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002165 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2166 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002167 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002168 case LibFunc::cosf:
2169 case LibFunc::cos:
2170 case LibFunc::cosl:
2171 return optimizeCos(CI, Builder);
2172 case LibFunc::sinpif:
2173 case LibFunc::sinpi:
2174 case LibFunc::cospif:
2175 case LibFunc::cospi:
2176 return optimizeSinCosPi(CI, Builder);
2177 case LibFunc::powf:
2178 case LibFunc::pow:
2179 case LibFunc::powl:
2180 return optimizePow(CI, Builder);
2181 case LibFunc::exp2l:
2182 case LibFunc::exp2:
2183 case LibFunc::exp2f:
2184 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002185 case LibFunc::fabsf:
2186 case LibFunc::fabs:
2187 case LibFunc::fabsl:
2188 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002189 case LibFunc::sqrtf:
2190 case LibFunc::sqrt:
2191 case LibFunc::sqrtl:
2192 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002193 case LibFunc::ffs:
2194 case LibFunc::ffsl:
2195 case LibFunc::ffsll:
2196 return optimizeFFS(CI, Builder);
2197 case LibFunc::abs:
2198 case LibFunc::labs:
2199 case LibFunc::llabs:
2200 return optimizeAbs(CI, Builder);
2201 case LibFunc::isdigit:
2202 return optimizeIsDigit(CI, Builder);
2203 case LibFunc::isascii:
2204 return optimizeIsAscii(CI, Builder);
2205 case LibFunc::toascii:
2206 return optimizeToAscii(CI, Builder);
2207 case LibFunc::printf:
2208 return optimizePrintF(CI, Builder);
2209 case LibFunc::sprintf:
2210 return optimizeSPrintF(CI, Builder);
2211 case LibFunc::fprintf:
2212 return optimizeFPrintF(CI, Builder);
2213 case LibFunc::fwrite:
2214 return optimizeFWrite(CI, Builder);
2215 case LibFunc::fputs:
2216 return optimizeFPuts(CI, Builder);
Davide Italianob8b71332015-11-29 20:58:04 +00002217 case LibFunc::log:
2218 case LibFunc::log10:
2219 case LibFunc::log1p:
2220 case LibFunc::log2:
2221 case LibFunc::logb:
2222 return optimizeLog(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002223 case LibFunc::puts:
2224 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002225 case LibFunc::tan:
2226 case LibFunc::tanf:
2227 case LibFunc::tanl:
2228 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002229 case LibFunc::perror:
2230 return optimizeErrorReporting(CI, Builder);
2231 case LibFunc::vfprintf:
2232 case LibFunc::fiprintf:
2233 return optimizeErrorReporting(CI, Builder, 0);
2234 case LibFunc::fputc:
2235 return optimizeErrorReporting(CI, Builder, 1);
2236 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002237 case LibFunc::floor:
2238 case LibFunc::rint:
2239 case LibFunc::round:
2240 case LibFunc::nearbyint:
2241 case LibFunc::trunc:
2242 if (hasFloatVersion(FuncName))
2243 return optimizeUnaryDoubleFP(CI, Builder, false);
2244 return nullptr;
2245 case LibFunc::acos:
2246 case LibFunc::acosh:
2247 case LibFunc::asin:
2248 case LibFunc::asinh:
2249 case LibFunc::atan:
2250 case LibFunc::atanh:
2251 case LibFunc::cbrt:
2252 case LibFunc::cosh:
2253 case LibFunc::exp:
2254 case LibFunc::exp10:
2255 case LibFunc::expm1:
Chris Bienemanad070d02014-09-17 20:55:46 +00002256 case LibFunc::sin:
2257 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002258 case LibFunc::tanh:
2259 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2260 return optimizeUnaryDoubleFP(CI, Builder, true);
2261 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002262 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002263 if (hasFloatVersion(FuncName))
2264 return optimizeBinaryDoubleFP(CI, Builder);
2265 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002266 case LibFunc::fminf:
2267 case LibFunc::fmin:
2268 case LibFunc::fminl:
2269 case LibFunc::fmaxf:
2270 case LibFunc::fmax:
2271 case LibFunc::fmaxl:
2272 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002273 default:
2274 return nullptr;
2275 }
Meador Inge20255ef2013-03-12 00:08:29 +00002276 }
Craig Topperf40110f2014-04-25 05:29:35 +00002277 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002278}
2279
Chandler Carruth92803822015-01-21 02:11:59 +00002280LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002281 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002282 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002283 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002284 Replacer(Replacer) {}
2285
2286void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2287 // Indirect through the replacer used in this instance.
2288 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002289}
2290
Meador Ingedfb08a22013-06-20 19:48:07 +00002291// TODO:
2292// Additional cases that we need to add to this file:
2293//
2294// cbrt:
2295// * cbrt(expN(X)) -> expN(x/3)
2296// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002297// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002298//
2299// exp, expf, expl:
2300// * exp(log(x)) -> x
2301//
2302// log, logf, logl:
2303// * log(exp(x)) -> x
2304// * log(x**y) -> y*log(x)
2305// * log(exp(y)) -> y*log(e)
2306// * log(exp2(y)) -> y*log(2)
2307// * log(exp10(y)) -> y*log(10)
2308// * log(sqrt(x)) -> 0.5*log(x)
2309// * log(pow(x,y)) -> y*log(x)
2310//
2311// lround, lroundf, lroundl:
2312// * lround(cnst) -> cnst'
2313//
2314// pow, powf, powl:
Meador Ingedfb08a22013-06-20 19:48:07 +00002315// * pow(sqrt(x),y) -> pow(x,y*0.5)
2316// * pow(pow(x,y),z)-> pow(x,y*z)
2317//
2318// round, roundf, roundl:
2319// * round(cnst) -> cnst'
2320//
2321// signbit:
2322// * signbit(cnst) -> cnst'
2323// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2324//
2325// sqrt, sqrtf, sqrtl:
2326// * sqrt(expN(x)) -> expN(x*0.5)
2327// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2328// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2329//
Meador Ingedfb08a22013-06-20 19:48:07 +00002330// trunc, truncf, truncl:
2331// * trunc(cnst) -> cnst'
2332//
2333//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002334
2335//===----------------------------------------------------------------------===//
2336// Fortified Library Call Optimizations
2337//===----------------------------------------------------------------------===//
2338
2339bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2340 unsigned ObjSizeOp,
2341 unsigned SizeOp,
2342 bool isString) {
2343 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2344 return true;
2345 if (ConstantInt *ObjSizeCI =
2346 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2347 if (ObjSizeCI->isAllOnesValue())
2348 return true;
2349 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2350 if (OnlyLowerUnknownSize)
2351 return false;
2352 if (isString) {
2353 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2354 // If the length is 0 we don't know how long it is and so we can't
2355 // remove the check.
2356 if (Len == 0)
2357 return false;
2358 return ObjSizeCI->getZExtValue() >= Len;
2359 }
2360 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2361 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2362 }
2363 return false;
2364}
2365
2366Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2367 Function *Callee = CI->getCalledFunction();
2368
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002369 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002370 return nullptr;
2371
2372 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2373 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002374 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002375 return CI->getArgOperand(0);
2376 }
2377 return nullptr;
2378}
2379
2380Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2381 Function *Callee = CI->getCalledFunction();
2382
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002383 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002384 return nullptr;
2385
2386 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2387 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper67cf9a72015-11-19 05:56:52 +00002388 CI->getArgOperand(2), 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002389 return CI->getArgOperand(0);
2390 }
2391 return nullptr;
2392}
2393
2394Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2395 Function *Callee = CI->getCalledFunction();
2396
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002397 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002398 return nullptr;
2399
2400 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2401 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2402 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2403 return CI->getArgOperand(0);
2404 }
2405 return nullptr;
2406}
2407
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002408Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2409 IRBuilder<> &B,
2410 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002411 Function *Callee = CI->getCalledFunction();
2412 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002413 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002414
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002415 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002416 return nullptr;
2417
2418 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2419 *ObjSize = CI->getArgOperand(2);
2420
2421 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002422 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002423 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002424 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002425 }
2426
2427 // If a) we don't have any length information, or b) we know this will
2428 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2429 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2430 // TODO: It might be nice to get a maximum length out of the possible
2431 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002432 if (isFortifiedCallFoldable(CI, 2, 1, true))
2433 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002434
David Blaikie65fab6d2015-04-03 21:32:06 +00002435 if (OnlyLowerUnknownSize)
2436 return nullptr;
2437
2438 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2439 uint64_t Len = GetStringLength(Src);
2440 if (Len == 0)
2441 return nullptr;
2442
2443 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2444 Value *LenV = ConstantInt::get(SizeTTy, Len);
2445 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2446 // If the function was an __stpcpy_chk, and we were able to fold it into
2447 // a __memcpy_chk, we still need to return the correct end pointer.
2448 if (Ret && Func == LibFunc::stpcpy_chk)
2449 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2450 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002451}
2452
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002453Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2454 IRBuilder<> &B,
2455 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002456 Function *Callee = CI->getCalledFunction();
2457 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002458
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002459 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002460 return nullptr;
2461 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002462 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2463 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002464 return Ret;
2465 }
2466 return nullptr;
2467}
2468
2469Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002470 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2471 // Some clang users checked for _chk libcall availability using:
2472 // __has_builtin(__builtin___memcpy_chk)
2473 // When compiling with -fno-builtin, this is always true.
2474 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2475 // end up with fortified libcalls, which isn't acceptable in a freestanding
2476 // environment which only provides their non-fortified counterparts.
2477 //
2478 // Until we change clang and/or teach external users to check for availability
2479 // differently, disregard the "nobuiltin" attribute and TLI::has.
2480 //
2481 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002482
2483 LibFunc::Func Func;
2484 Function *Callee = CI->getCalledFunction();
2485 StringRef FuncName = Callee->getName();
2486 IRBuilder<> Builder(CI);
2487 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2488
2489 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002490 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002491 return nullptr;
2492
2493 // We never change the calling convention.
2494 if (!ignoreCallingConv(Func) && !isCallingConvC)
2495 return nullptr;
2496
2497 switch (Func) {
2498 case LibFunc::memcpy_chk:
2499 return optimizeMemCpyChk(CI, Builder);
2500 case LibFunc::memmove_chk:
2501 return optimizeMemMoveChk(CI, Builder);
2502 case LibFunc::memset_chk:
2503 return optimizeMemSetChk(CI, Builder);
2504 case LibFunc::stpcpy_chk:
2505 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002506 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002507 case LibFunc::stpncpy_chk:
2508 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002509 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002510 default:
2511 break;
2512 }
2513 return nullptr;
2514}
2515
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002516FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2517 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2518 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}