blob: 72abd0b3329222564bfb0b8fe3d391b7ab8bd3c8 [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"
Meador Ingedf796f82012-10-13 16:45:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Diego Novillo7f8af8b2014-05-22 14:19:46 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Function.h"
25#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000026#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Sanjay Patelc699a612014-10-16 18:48:17 +000030#include "llvm/IR/PatternMatch.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000031#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000032#include "llvm/Support/CommandLine.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000033#include "llvm/Analysis/TargetLibraryInfo.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) {
89 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
90 it != e; ++it) {
91 if ((*it)->getType()->isFloatingPointTy())
92 return true;
93 }
94 return false;
95}
96
Benjamin Kramer2702caa2013-08-31 18:19:35 +000097/// \brief Check whether the overloaded unary floating point function
Sanjay Patele24c60e2015-08-12 20:36:18 +000098/// corresponding to \a Ty is available.
Benjamin Kramer2702caa2013-08-31 18:19:35 +000099static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
100 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
101 LibFunc::Func LongDoubleFn) {
102 switch (Ty->getTypeID()) {
103 case Type::FloatTyID:
104 return TLI->has(FloatFn);
105 case Type::DoubleTyID:
106 return TLI->has(DoubleFn);
107 default:
108 return TLI->has(LongDoubleFn);
109 }
110}
111
Davide Italianoa904e522015-10-29 02:58:44 +0000112/// \brief Check whether we can use unsafe floating point math for
113/// the function passed as input.
114static bool canUseUnsafeFPMath(Function *F) {
115
116 // FIXME: For finer-grain optimization, we need intrinsics to have the same
117 // fast-math flag decorations that are applied to FP instructions. For now,
118 // we have to rely on the function-level unsafe-fp-math attribute to do this
Davide Italianoed5cc952015-11-16 16:54:28 +0000119 // optimization because there's no other way to express that the call can be
120 // relaxed.
Davide Italianoa904e522015-10-29 02:58:44 +0000121 if (F->hasFnAttribute("unsafe-fp-math")) {
122 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
123 if (Attr.getValueAsString() == "true")
124 return true;
125 }
126 return false;
127}
128
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000129/// \brief Returns whether \p F matches the signature expected for the
130/// string/memory copying library function \p Func.
131/// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
132/// Their fortified (_chk) counterparts are also accepted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000133static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
134 const DataLayout &DL = F->getParent()->getDataLayout();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000135 FunctionType *FT = F->getFunctionType();
136 LLVMContext &Context = F->getContext();
137 Type *PCharTy = Type::getInt8PtrTy(Context);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000138 Type *SizeTTy = DL.getIntPtrType(Context);
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000139 unsigned NumParams = FT->getNumParams();
140
141 // All string libfuncs return the same type as the first parameter.
142 if (FT->getReturnType() != FT->getParamType(0))
143 return false;
144
145 switch (Func) {
146 default:
147 llvm_unreachable("Can't check signature for non-string-copy libfunc.");
148 case LibFunc::stpncpy_chk:
149 case LibFunc::strncpy_chk:
150 --NumParams; // fallthrough
151 case LibFunc::stpncpy:
152 case LibFunc::strncpy: {
153 if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
154 FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
155 return false;
156 break;
157 }
158 case LibFunc::strcpy_chk:
159 case LibFunc::stpcpy_chk:
160 --NumParams; // fallthrough
161 case LibFunc::stpcpy:
162 case LibFunc::strcpy: {
163 if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
164 FT->getParamType(0) != PCharTy)
165 return false;
166 break;
167 }
168 case LibFunc::memmove_chk:
169 case LibFunc::memcpy_chk:
170 --NumParams; // fallthrough
171 case LibFunc::memmove:
172 case LibFunc::memcpy: {
173 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
174 !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
175 return false;
176 break;
177 }
178 case LibFunc::memset_chk:
179 --NumParams; // fallthrough
180 case LibFunc::memset: {
181 if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
182 !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
183 return false;
184 break;
185 }
186 }
187 // If this is a fortified libcall, the last parameter is a size_t.
188 if (NumParams == FT->getNumParams() - 1)
189 return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
190 return true;
191}
192
Meador Inged589ac62012-10-31 03:33:06 +0000193//===----------------------------------------------------------------------===//
Meador Inge7fb2f732012-10-13 16:45:32 +0000194// String and Memory Library Call Optimizations
195//===----------------------------------------------------------------------===//
196
Chris Bienemanad070d02014-09-17 20:55:46 +0000197Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
198 Function *Callee = CI->getCalledFunction();
199 // Verify the "strcat" function prototype.
200 FunctionType *FT = Callee->getFunctionType();
201 if (FT->getNumParams() != 2||
202 FT->getReturnType() != B.getInt8PtrTy() ||
203 FT->getParamType(0) != FT->getReturnType() ||
204 FT->getParamType(1) != FT->getReturnType())
205 return nullptr;
206
207 // Extract some information from the instruction
208 Value *Dst = CI->getArgOperand(0);
209 Value *Src = CI->getArgOperand(1);
210
211 // See if we can get the length of the input string.
212 uint64_t Len = GetStringLength(Src);
213 if (Len == 0)
214 return nullptr;
215 --Len; // Unbias length.
216
217 // Handle the simple, do-nothing case: strcat(x, "") -> x
218 if (Len == 0)
219 return Dst;
220
Chris Bienemanad070d02014-09-17 20:55:46 +0000221 return emitStrLenMemCpy(Src, Dst, Len, B);
222}
223
224Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
225 IRBuilder<> &B) {
226 // We need to find the end of the destination string. That's where the
227 // memory is to be moved to. We just generate a call to strlen.
228 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
229 if (!DstLen)
230 return nullptr;
231
232 // Now that we have the destination's length, we must index into the
233 // destination's pointer to get the actual memcpy destination (end of
234 // the string .. we're concatenating).
David Blaikie3909da72015-03-30 20:42:56 +0000235 Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000236
237 // We have enough information to now generate the memcpy call to do the
238 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239 B.CreateMemCpy(CpyDst, Src,
240 ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
Pete Cooper72bc23e2015-11-18 22:17:24 +0000241 1, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000242 return Dst;
243}
244
245Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
246 Function *Callee = CI->getCalledFunction();
247 // Verify the "strncat" function prototype.
248 FunctionType *FT = Callee->getFunctionType();
249 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
250 FT->getParamType(0) != FT->getReturnType() ||
251 FT->getParamType(1) != FT->getReturnType() ||
252 !FT->getParamType(2)->isIntegerTy())
253 return nullptr;
254
255 // Extract some information from the instruction
256 Value *Dst = CI->getArgOperand(0);
257 Value *Src = CI->getArgOperand(1);
258 uint64_t Len;
259
260 // We don't do anything if length is not constant
261 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
262 Len = LengthArg->getZExtValue();
263 else
264 return nullptr;
265
266 // See if we can get the length of the input string.
267 uint64_t SrcLen = GetStringLength(Src);
268 if (SrcLen == 0)
269 return nullptr;
270 --SrcLen; // Unbias length.
271
272 // Handle the simple, do-nothing cases:
273 // strncat(x, "", c) -> x
274 // strncat(x, c, 0) -> x
275 if (SrcLen == 0 || Len == 0)
276 return Dst;
277
Chris Bienemanad070d02014-09-17 20:55:46 +0000278 // We don't optimize this case
279 if (Len < SrcLen)
280 return nullptr;
281
282 // strncat(x, s, c) -> strcat(x, s)
283 // s is constant so the strcat can be optimized further
284 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
285}
286
287Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
288 Function *Callee = CI->getCalledFunction();
289 // Verify the "strchr" function prototype.
290 FunctionType *FT = Callee->getFunctionType();
291 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
292 FT->getParamType(0) != FT->getReturnType() ||
293 !FT->getParamType(1)->isIntegerTy(32))
294 return nullptr;
295
296 Value *SrcStr = CI->getArgOperand(0);
297
298 // If the second operand is non-constant, see if we can compute the length
299 // of the input string and turn this into memchr.
300 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
301 if (!CharC) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000302 uint64_t Len = GetStringLength(SrcStr);
303 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
304 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000305
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
307 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
308 B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000309 }
310
Chris Bienemanad070d02014-09-17 20:55:46 +0000311 // Otherwise, the character is a constant, see if the first argument is
312 // a string literal. If so, we can constant fold.
313 StringRef Str;
314 if (!getConstantStringInfo(SrcStr, Str)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000315 if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
David Blaikie3909da72015-03-30 20:42:56 +0000316 return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000317 return nullptr;
318 }
319
320 // Compute the offset, make sure to handle the case when we're searching for
321 // zero (a weird way to spell strlen).
322 size_t I = (0xFF & CharC->getSExtValue()) == 0
323 ? Str.size()
324 : Str.find(CharC->getSExtValue());
325 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
326 return Constant::getNullValue(CI->getType());
327
328 // strchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000329 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000330}
331
332Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
333 Function *Callee = CI->getCalledFunction();
334 // Verify the "strrchr" function prototype.
335 FunctionType *FT = Callee->getFunctionType();
336 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
337 FT->getParamType(0) != FT->getReturnType() ||
338 !FT->getParamType(1)->isIntegerTy(32))
339 return nullptr;
340
341 Value *SrcStr = CI->getArgOperand(0);
342 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
343
344 // Cannot fold anything if we're not looking for a constant.
345 if (!CharC)
346 return nullptr;
347
348 StringRef Str;
349 if (!getConstantStringInfo(SrcStr, Str)) {
350 // strrchr(s, 0) -> strchr(s, 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000351 if (CharC->isZero())
352 return EmitStrChr(SrcStr, '\0', B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000353 return nullptr;
354 }
355
356 // Compute the offset.
357 size_t I = (0xFF & CharC->getSExtValue()) == 0
358 ? Str.size()
359 : Str.rfind(CharC->getSExtValue());
360 if (I == StringRef::npos) // Didn't find the char. Return null.
361 return Constant::getNullValue(CI->getType());
362
363 // strrchr(s+n,c) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000364 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
Chris Bienemanad070d02014-09-17 20:55:46 +0000365}
366
367Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
368 Function *Callee = CI->getCalledFunction();
369 // Verify the "strcmp" function prototype.
370 FunctionType *FT = Callee->getFunctionType();
371 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
372 FT->getParamType(0) != FT->getParamType(1) ||
373 FT->getParamType(0) != B.getInt8PtrTy())
374 return nullptr;
375
376 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
377 if (Str1P == Str2P) // strcmp(x,x) -> 0
378 return ConstantInt::get(CI->getType(), 0);
379
380 StringRef Str1, Str2;
381 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
382 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
383
384 // strcmp(x, y) -> cnst (if both x and y are constant strings)
385 if (HasStr1 && HasStr2)
386 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
387
388 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
389 return B.CreateNeg(
390 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
391
392 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
393 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
394
395 // strcmp(P, "x") -> memcmp(P, "x", 2)
396 uint64_t Len1 = GetStringLength(Str1P);
397 uint64_t Len2 = GetStringLength(Str2P);
398 if (Len1 && Len2) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000399 return EmitMemCmp(Str1P, Str2P,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
Chris Bienemanad070d02014-09-17 20:55:46 +0000401 std::min(Len1, Len2)),
402 B, DL, TLI);
403 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000404
Chris Bienemanad070d02014-09-17 20:55:46 +0000405 return nullptr;
406}
407
408Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
409 Function *Callee = CI->getCalledFunction();
410 // Verify the "strncmp" function prototype.
411 FunctionType *FT = Callee->getFunctionType();
412 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
413 FT->getParamType(0) != FT->getParamType(1) ||
414 FT->getParamType(0) != B.getInt8PtrTy() ||
415 !FT->getParamType(2)->isIntegerTy())
416 return nullptr;
417
418 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
419 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
420 return ConstantInt::get(CI->getType(), 0);
421
422 // Get the length argument if it is constant.
423 uint64_t Length;
424 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
425 Length = LengthArg->getZExtValue();
426 else
427 return nullptr;
428
429 if (Length == 0) // strncmp(x,y,0) -> 0
430 return ConstantInt::get(CI->getType(), 0);
431
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000432 if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Chris Bienemanad070d02014-09-17 20:55:46 +0000433 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
434
435 StringRef Str1, Str2;
436 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
437 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
438
439 // strncmp(x, y) -> cnst (if both x and y are constant strings)
440 if (HasStr1 && HasStr2) {
441 StringRef SubStr1 = Str1.substr(0, Length);
442 StringRef SubStr2 = Str2.substr(0, Length);
443 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
444 }
445
446 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
447 return B.CreateNeg(
448 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
449
450 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
451 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
452
453 return nullptr;
454}
455
456Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
457 Function *Callee = CI->getCalledFunction();
Ahmed Bougachab7d8afb2015-01-12 17:18:19 +0000458
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000459 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000460 return nullptr;
461
462 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
463 if (Dst == Src) // strcpy(x,x) -> x
464 return Src;
465
Chris Bienemanad070d02014-09-17 20:55:46 +0000466 // See if we can get the length of the input string.
467 uint64_t Len = GetStringLength(Src);
468 if (Len == 0)
469 return nullptr;
470
471 // We have enough information to now generate the memcpy call to do the
472 // copy for us. Make a memcpy to copy the nul byte with align = 1.
473 B.CreateMemCpy(Dst, Src,
Pete Cooper72bc23e2015-11-18 22:17:24 +0000474 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1,
475 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000476 return Dst;
477}
478
479Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
480 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000481 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000482 return nullptr;
483
484 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
485 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
486 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +0000487 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000488 }
489
490 // See if we can get the length of the input string.
491 uint64_t Len = GetStringLength(Src);
492 if (Len == 0)
493 return nullptr;
494
Davide Italianob7487e62015-11-02 23:07:14 +0000495 Type *PT = Callee->getFunctionType()->getParamType(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000496 Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
Chris Bienemanad070d02014-09-17 20:55:46 +0000497 Value *DstEnd =
David Blaikie3909da72015-03-30 20:42:56 +0000498 B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
Chris Bienemanad070d02014-09-17 20:55:46 +0000499
500 // We have enough information to now generate the memcpy call to do the
501 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Pete Cooper72bc23e2015-11-18 22:17:24 +0000502 B.CreateMemCpy(Dst, Src, LenV, 1, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000503 return DstEnd;
504}
505
506Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
507 Function *Callee = CI->getCalledFunction();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000508 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
Chris Bienemanad070d02014-09-17 20:55:46 +0000509 return nullptr;
510
511 Value *Dst = CI->getArgOperand(0);
512 Value *Src = CI->getArgOperand(1);
513 Value *LenOp = CI->getArgOperand(2);
514
515 // See if we can get the length of the input string.
516 uint64_t SrcLen = GetStringLength(Src);
517 if (SrcLen == 0)
518 return nullptr;
519 --SrcLen;
520
521 if (SrcLen == 0) {
522 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
523 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000524 return Dst;
525 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000526
Chris Bienemanad070d02014-09-17 20:55:46 +0000527 uint64_t Len;
528 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
529 Len = LengthArg->getZExtValue();
530 else
531 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000532
Chris Bienemanad070d02014-09-17 20:55:46 +0000533 if (Len == 0)
534 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000535
Chris Bienemanad070d02014-09-17 20:55:46 +0000536 // Let strncpy handle the zero padding
537 if (Len > SrcLen + 1)
538 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000539
Davide Italianob7487e62015-11-02 23:07:14 +0000540 Type *PT = Callee->getFunctionType()->getParamType(0);
Chris Bienemanad070d02014-09-17 20:55:46 +0000541 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Pete Cooper72bc23e2015-11-18 22:17:24 +0000542 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000543
Chris Bienemanad070d02014-09-17 20:55:46 +0000544 return Dst;
545}
Meador Inge7fb2f732012-10-13 16:45:32 +0000546
Chris Bienemanad070d02014-09-17 20:55:46 +0000547Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
548 Function *Callee = CI->getCalledFunction();
549 FunctionType *FT = Callee->getFunctionType();
550 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
551 !FT->getReturnType()->isIntegerTy())
552 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000553
Chris Bienemanad070d02014-09-17 20:55:46 +0000554 Value *Src = CI->getArgOperand(0);
555
556 // Constant folding: strlen("xyz") -> 3
557 if (uint64_t Len = GetStringLength(Src))
558 return ConstantInt::get(CI->getType(), Len - 1);
559
560 // strlen(x?"foo":"bars") --> x ? 3 : 4
561 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
562 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
563 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
564 if (LenTrue && LenFalse) {
565 Function *Caller = CI->getParent()->getParent();
566 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
567 SI->getDebugLoc(),
568 "folded strlen(select) to select of constants");
569 return B.CreateSelect(SI->getCondition(),
570 ConstantInt::get(CI->getType(), LenTrue - 1),
571 ConstantInt::get(CI->getType(), LenFalse - 1));
572 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000573 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000574
Chris Bienemanad070d02014-09-17 20:55:46 +0000575 // strlen(x) != 0 --> *x != 0
576 // strlen(x) == 0 --> *x == 0
577 if (isOnlyUsedInZeroEqualityComparison(CI))
578 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000579
Chris Bienemanad070d02014-09-17 20:55:46 +0000580 return nullptr;
581}
Meador Inge17418502012-10-13 16:45:37 +0000582
Chris Bienemanad070d02014-09-17 20:55:46 +0000583Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
584 Function *Callee = CI->getCalledFunction();
585 FunctionType *FT = Callee->getFunctionType();
586 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
587 FT->getParamType(1) != FT->getParamType(0) ||
588 FT->getReturnType() != FT->getParamType(0))
589 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000590
Chris Bienemanad070d02014-09-17 20:55:46 +0000591 StringRef S1, S2;
592 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
593 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000594
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000595 // strpbrk(s, "") -> nullptr
596 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000597 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
598 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000599
Chris Bienemanad070d02014-09-17 20:55:46 +0000600 // Constant folding.
601 if (HasS1 && HasS2) {
602 size_t I = S1.find_first_of(S2);
603 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000604 return Constant::getNullValue(CI->getType());
605
David Blaikie3909da72015-03-30 20:42:56 +0000606 return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000607 }
Meador Inge17418502012-10-13 16:45:37 +0000608
Chris Bienemanad070d02014-09-17 20:55:46 +0000609 // strpbrk(s, "a") -> strchr(s, 'a')
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000610 if (HasS2 && S2.size() == 1)
611 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000612
613 return nullptr;
614}
615
616Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
617 Function *Callee = CI->getCalledFunction();
618 FunctionType *FT = Callee->getFunctionType();
619 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
620 !FT->getParamType(0)->isPointerTy() ||
621 !FT->getParamType(1)->isPointerTy())
622 return nullptr;
623
624 Value *EndPtr = CI->getArgOperand(1);
625 if (isa<ConstantPointerNull>(EndPtr)) {
626 // With a null EndPtr, this function won't capture the main argument.
627 // It would be readonly too, except that it still may write to errno.
628 CI->addAttribute(1, Attribute::NoCapture);
629 }
630
631 return nullptr;
632}
633
634Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
635 Function *Callee = CI->getCalledFunction();
636 FunctionType *FT = Callee->getFunctionType();
637 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
638 FT->getParamType(1) != FT->getParamType(0) ||
639 !FT->getReturnType()->isIntegerTy())
640 return nullptr;
641
642 StringRef S1, S2;
643 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
644 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
645
646 // strspn(s, "") -> 0
647 // strspn("", s) -> 0
648 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
649 return Constant::getNullValue(CI->getType());
650
651 // Constant folding.
652 if (HasS1 && HasS2) {
653 size_t Pos = S1.find_first_not_of(S2);
654 if (Pos == StringRef::npos)
655 Pos = S1.size();
656 return ConstantInt::get(CI->getType(), Pos);
657 }
658
659 return nullptr;
660}
661
662Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
663 Function *Callee = CI->getCalledFunction();
664 FunctionType *FT = Callee->getFunctionType();
665 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
666 FT->getParamType(1) != FT->getParamType(0) ||
667 !FT->getReturnType()->isIntegerTy())
668 return nullptr;
669
670 StringRef S1, S2;
671 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
672 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
673
674 // strcspn("", s) -> 0
675 if (HasS1 && S1.empty())
676 return Constant::getNullValue(CI->getType());
677
678 // Constant folding.
679 if (HasS1 && HasS2) {
680 size_t Pos = S1.find_first_of(S2);
681 if (Pos == StringRef::npos)
682 Pos = S1.size();
683 return ConstantInt::get(CI->getType(), Pos);
684 }
685
686 // strcspn(s, "") -> strlen(s)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000687 if (HasS2 && S2.empty())
Chris Bienemanad070d02014-09-17 20:55:46 +0000688 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
689
690 return nullptr;
691}
692
693Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
694 Function *Callee = CI->getCalledFunction();
695 FunctionType *FT = Callee->getFunctionType();
696 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
697 !FT->getParamType(1)->isPointerTy() ||
698 !FT->getReturnType()->isPointerTy())
699 return nullptr;
700
701 // fold strstr(x, x) -> x.
702 if (CI->getArgOperand(0) == CI->getArgOperand(1))
703 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
704
705 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000706 if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Chris Bienemanad070d02014-09-17 20:55:46 +0000707 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
708 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000709 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000710 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
711 StrLen, B, DL, TLI);
712 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000713 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000714 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
715 ICmpInst *Old = cast<ICmpInst>(*UI++);
716 Value *Cmp =
717 B.CreateICmp(Old->getPredicate(), StrNCmp,
718 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
719 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000720 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 return CI;
722 }
Meador Inge17418502012-10-13 16:45:37 +0000723
Chris Bienemanad070d02014-09-17 20:55:46 +0000724 // See if either input string is a constant string.
725 StringRef SearchStr, ToFindStr;
726 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
727 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
728
729 // fold strstr(x, "") -> x.
730 if (HasStr2 && ToFindStr.empty())
731 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
732
733 // If both strings are known, constant fold it.
734 if (HasStr1 && HasStr2) {
735 size_t Offset = SearchStr.find(ToFindStr);
736
737 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000738 return Constant::getNullValue(CI->getType());
739
Chris Bienemanad070d02014-09-17 20:55:46 +0000740 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
741 Value *Result = CastToCStr(CI->getArgOperand(0), B);
742 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
743 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000744 }
Meador Inge17418502012-10-13 16:45:37 +0000745
Chris Bienemanad070d02014-09-17 20:55:46 +0000746 // fold strstr(x, "y") -> strchr(x, 'y').
747 if (HasStr2 && ToFindStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000748 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +0000749 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
750 }
751 return nullptr;
752}
Meador Inge40b6fac2012-10-15 03:47:37 +0000753
Benjamin Kramer691363e2015-03-21 15:36:21 +0000754Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
755 Function *Callee = CI->getCalledFunction();
756 FunctionType *FT = Callee->getFunctionType();
757 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
758 !FT->getParamType(1)->isIntegerTy(32) ||
759 !FT->getParamType(2)->isIntegerTy() ||
760 !FT->getReturnType()->isPointerTy())
761 return nullptr;
762
763 Value *SrcStr = CI->getArgOperand(0);
764 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
765 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
766
767 // memchr(x, y, 0) -> null
768 if (LenC && LenC->isNullValue())
769 return Constant::getNullValue(CI->getType());
770
Benjamin Kramer7857d722015-03-21 21:09:33 +0000771 // From now on we need at least constant length and string.
Benjamin Kramer691363e2015-03-21 15:36:21 +0000772 StringRef Str;
Benjamin Kramer7857d722015-03-21 21:09:33 +0000773 if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
Benjamin Kramer691363e2015-03-21 15:36:21 +0000774 return nullptr;
775
776 // Truncate the string to LenC. If Str is smaller than LenC we will still only
777 // scan the string, as reading past the end of it is undefined and we can just
778 // return null if we don't find the char.
779 Str = Str.substr(0, LenC->getZExtValue());
780
Benjamin Kramer7857d722015-03-21 21:09:33 +0000781 // If the char is variable but the input str and length are not we can turn
782 // this memchr call into a simple bit field test. Of course this only works
783 // when the return value is only checked against null.
784 //
785 // It would be really nice to reuse switch lowering here but we can't change
786 // the CFG at this point.
787 //
788 // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
789 // after bounds check.
790 if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
Benjamin Kramerd6aa0ec2015-03-21 22:04:26 +0000791 unsigned char Max =
792 *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
793 reinterpret_cast<const unsigned char *>(Str.end()));
Benjamin Kramer7857d722015-03-21 21:09:33 +0000794
795 // Make sure the bit field we're about to create fits in a register on the
796 // target.
797 // FIXME: On a 64 bit architecture this prevents us from using the
798 // interesting range of alpha ascii chars. We could do better by emitting
799 // two bitfields or shifting the range by 64 if no lower chars are used.
800 if (!DL.fitsInLegalInteger(Max + 1))
801 return nullptr;
802
803 // For the bit field use a power-of-2 type with at least 8 bits to avoid
804 // creating unnecessary illegal types.
805 unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
806
807 // Now build the bit field.
808 APInt Bitfield(Width, 0);
809 for (char C : Str)
810 Bitfield.setBit((unsigned char)C);
811 Value *BitfieldC = B.getInt(Bitfield);
812
813 // First check that the bit field access is within bounds.
814 Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
815 Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
816 "memchr.bounds");
817
818 // Create code that checks if the given bit is set in the field.
819 Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
820 Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
821
822 // Finally merge both checks and cast to pointer type. The inttoptr
823 // implicitly zexts the i1 to intptr type.
824 return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
825 }
826
827 // Check if all arguments are constants. If so, we can constant fold.
828 if (!CharC)
829 return nullptr;
830
Benjamin Kramer691363e2015-03-21 15:36:21 +0000831 // Compute the offset.
832 size_t I = Str.find(CharC->getSExtValue() & 0xFF);
833 if (I == StringRef::npos) // Didn't find the char. memchr returns null.
834 return Constant::getNullValue(CI->getType());
835
836 // memchr(s+n,c,l) -> gep(s+n+i,c)
David Blaikie3909da72015-03-30 20:42:56 +0000837 return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
Benjamin Kramer691363e2015-03-21 15:36:21 +0000838}
839
Chris Bienemanad070d02014-09-17 20:55:46 +0000840Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
841 Function *Callee = CI->getCalledFunction();
842 FunctionType *FT = Callee->getFunctionType();
843 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
844 !FT->getParamType(1)->isPointerTy() ||
845 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000846 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000847
Chris Bienemanad070d02014-09-17 20:55:46 +0000848 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000849
Chris Bienemanad070d02014-09-17 20:55:46 +0000850 if (LHS == RHS) // memcmp(s,s,x) -> 0
851 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000852
Chris Bienemanad070d02014-09-17 20:55:46 +0000853 // Make sure we have a constant length.
854 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
855 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000856 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000857 uint64_t Len = LenC->getZExtValue();
858
859 if (Len == 0) // memcmp(s1,s2,0) -> 0
860 return Constant::getNullValue(CI->getType());
861
862 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
863 if (Len == 1) {
864 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
865 CI->getType(), "lhsv");
866 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
867 CI->getType(), "rhsv");
868 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000869 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000870
Chad Rosierdc655322015-08-28 18:30:18 +0000871 // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
872 if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
873
874 IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
875 unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
876
877 if (getKnownAlignment(LHS, DL, CI) >= PrefAlignment &&
878 getKnownAlignment(RHS, DL, CI) >= PrefAlignment) {
879
880 Type *LHSPtrTy =
881 IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
882 Type *RHSPtrTy =
883 IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
884
885 Value *LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy, "lhsc"), "lhsv");
886 Value *RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy, "rhsc"), "rhsv");
887
888 return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
889 }
890 }
891
Chris Bienemanad070d02014-09-17 20:55:46 +0000892 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
893 StringRef LHSStr, RHSStr;
894 if (getConstantStringInfo(LHS, LHSStr) &&
895 getConstantStringInfo(RHS, RHSStr)) {
896 // Make sure we're not reading out-of-bounds memory.
897 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000898 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000899 // Fold the memcmp and normalize the result. This way we get consistent
900 // results across multiple platforms.
901 uint64_t Ret = 0;
902 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
903 if (Cmp < 0)
904 Ret = -1;
905 else if (Cmp > 0)
906 Ret = 1;
907 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000908 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000909
Chris Bienemanad070d02014-09-17 20:55:46 +0000910 return nullptr;
911}
Meador Inge9a6a1902012-10-31 00:20:56 +0000912
Chris Bienemanad070d02014-09-17 20:55:46 +0000913Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
914 Function *Callee = CI->getCalledFunction();
Meador Inged589ac62012-10-31 03:33:06 +0000915
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000916 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
Craig Topperf40110f2014-04-25 05:29:35 +0000917 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000918
Chris Bienemanad070d02014-09-17 20:55:46 +0000919 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
920 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper72bc23e2015-11-18 22:17:24 +0000921 CI->getArgOperand(2), 1, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000922 return CI->getArgOperand(0);
923}
Meador Inge05a625a2012-10-31 14:58:26 +0000924
Chris Bienemanad070d02014-09-17 20:55:46 +0000925Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
926 Function *Callee = CI->getCalledFunction();
Meador Inge05a625a2012-10-31 14:58:26 +0000927
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
Craig Topperf40110f2014-04-25 05:29:35 +0000929 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +0000930
Chris Bienemanad070d02014-09-17 20:55:46 +0000931 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
932 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper72bc23e2015-11-18 22:17:24 +0000933 CI->getArgOperand(2), 1, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +0000934 return CI->getArgOperand(0);
935}
Meador Ingebcd88ef72012-11-10 15:16:48 +0000936
Chris Bienemanad070d02014-09-17 20:55:46 +0000937Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
938 Function *Callee = CI->getCalledFunction();
Meador Ingebcd88ef72012-11-10 15:16:48 +0000939
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
Craig Topperf40110f2014-04-25 05:29:35 +0000941 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +0000942
Chris Bienemanad070d02014-09-17 20:55:46 +0000943 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
944 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
945 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
946 return CI->getArgOperand(0);
947}
Meador Inged4825782012-11-11 06:49:03 +0000948
Meador Inge193e0352012-11-13 04:16:17 +0000949//===----------------------------------------------------------------------===//
950// Math Library Optimizations
951//===----------------------------------------------------------------------===//
952
Matthias Braund34e4d22014-12-03 21:46:33 +0000953/// Return a variant of Val with float type.
954/// Currently this works in two cases: If Val is an FPExtension of a float
955/// value to something bigger, simply return the operand.
956/// If Val is a ConstantFP but can be converted to a float ConstantFP without
957/// loss of precision do so.
958static Value *valueHasFloatPrecision(Value *Val) {
959 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
960 Value *Op = Cast->getOperand(0);
961 if (Op->getType()->isFloatTy())
962 return Op;
963 }
964 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
965 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +0000966 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +0000967 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +0000968 &losesInfo);
969 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +0000970 return ConstantFP::get(Const->getContext(), F);
971 }
972 return nullptr;
973}
974
Meador Inge193e0352012-11-13 04:16:17 +0000975//===----------------------------------------------------------------------===//
976// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
977
Chris Bienemanad070d02014-09-17 20:55:46 +0000978Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
979 bool CheckRetType) {
980 Function *Callee = CI->getCalledFunction();
981 FunctionType *FT = Callee->getFunctionType();
982 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
983 !FT->getParamType(0)->isDoubleTy())
984 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000985
Chris Bienemanad070d02014-09-17 20:55:46 +0000986 if (CheckRetType) {
987 // Check if all the uses for function like 'sin' are converted to float.
988 for (User *U : CI->users()) {
989 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
990 if (!Cast || !Cast->getType()->isFloatTy())
991 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +0000992 }
Meador Inge193e0352012-11-13 04:16:17 +0000993 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000994
995 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +0000996 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
997 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +0000998 return nullptr;
999
1000 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001001 if (Callee->isIntrinsic()) {
1002 Module *M = CI->getParent()->getParent()->getParent();
Pete Cooper9e1d3352015-05-20 17:16:39 +00001003 Intrinsic::ID IID = Callee->getIntrinsicID();
Sanjay Patel848309d2014-10-23 21:52:45 +00001004 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1005 V = B.CreateCall(F, V);
1006 } else {
1007 // The call is a library call rather than an intrinsic.
1008 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1009 }
1010
Chris Bienemanad070d02014-09-17 20:55:46 +00001011 return B.CreateFPExt(V, B.getDoubleTy());
1012}
Meador Inge193e0352012-11-13 04:16:17 +00001013
Yi Jiang6ab044e2013-12-16 22:42:40 +00001014// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001015Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1016 Function *Callee = CI->getCalledFunction();
1017 FunctionType *FT = Callee->getFunctionType();
1018 // Just make sure this has 2 arguments of the same FP type, which match the
1019 // result type.
1020 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1021 FT->getParamType(0) != FT->getParamType(1) ||
1022 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001023 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001024
Chris Bienemanad070d02014-09-17 20:55:46 +00001025 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001026 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1027 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1028 if (V1 == nullptr)
1029 return nullptr;
1030 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1031 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001032 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001033
1034 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001035 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001036 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001037 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1038 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001039 return B.CreateFPExt(V, B.getDoubleTy());
1040}
1041
1042Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1043 Function *Callee = CI->getCalledFunction();
1044 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001045 StringRef Name = Callee->getName();
1046 if (UnsafeFPShrink && Name == "cos" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001047 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001048
Chris Bienemanad070d02014-09-17 20:55:46 +00001049 FunctionType *FT = Callee->getFunctionType();
1050 // Just make sure this has 1 argument of FP type, which matches the
1051 // result type.
1052 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1053 !FT->getParamType(0)->isFloatingPointTy())
1054 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001055
Chris Bienemanad070d02014-09-17 20:55:46 +00001056 // cos(-x) -> cos(x)
1057 Value *Op1 = CI->getArgOperand(0);
1058 if (BinaryOperator::isFNeg(Op1)) {
1059 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1060 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1061 }
1062 return Ret;
1063}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001064
Chris Bienemanad070d02014-09-17 20:55:46 +00001065Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1066 Function *Callee = CI->getCalledFunction();
Chris Bienemanad070d02014-09-17 20:55:46 +00001067 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001068 StringRef Name = Callee->getName();
1069 if (UnsafeFPShrink && Name == "pow" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001070 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001071
Chris Bienemanad070d02014-09-17 20:55:46 +00001072 FunctionType *FT = Callee->getFunctionType();
1073 // Just make sure this has 2 arguments of the same FP type, which match the
1074 // result type.
1075 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1076 FT->getParamType(0) != FT->getParamType(1) ||
1077 !FT->getParamType(0)->isFloatingPointTy())
1078 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001079
Chris Bienemanad070d02014-09-17 20:55:46 +00001080 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1081 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1082 // pow(1.0, x) -> 1.0
1083 if (Op1C->isExactlyValue(1.0))
1084 return Op1C;
1085 // pow(2.0, x) -> exp2(x)
1086 if (Op1C->isExactlyValue(2.0) &&
1087 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1088 LibFunc::exp2l))
Davide Italianod9f87b42015-11-06 21:05:07 +00001089 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp2), B,
1090 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001091 // pow(10.0, x) -> exp10(x)
1092 if (Op1C->isExactlyValue(10.0) &&
1093 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1094 LibFunc::exp10l))
1095 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1096 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001097 }
1098
Davide Italianoc5cedd12015-11-18 23:21:32 +00001099 bool unsafeFPMath = canUseUnsafeFPMath(CI->getParent()->getParent());
1100
Davide Italianoc8a79132015-11-03 20:32:23 +00001101 // pow(exp(x), y) -> exp(x*y)
1102 // pow(exp2(x), y) -> exp2(x * y)
1103 // We enable these only under fast-math. Besides rounding
1104 // differences the transformation changes overflow and
1105 // underflow behavior quite dramatically.
1106 // Example: x = 1000, y = 0.001.
1107 // pow(exp(x), y) = pow(inf, 0.001) = inf, whereas exp(x*y) = exp(1).
Davide Italianoc5cedd12015-11-18 23:21:32 +00001108 if (unsafeFPMath) {
Davide Italianoc8a79132015-11-03 20:32:23 +00001109 if (auto *OpC = dyn_cast<CallInst>(Op1)) {
1110 IRBuilder<>::FastMathFlagGuard Guard(B);
1111 FastMathFlags FMF;
1112 FMF.setUnsafeAlgebra();
1113 B.SetFastMathFlags(FMF);
1114
1115 LibFunc::Func Func;
1116 Function *Callee = OpC->getCalledFunction();
1117 StringRef FuncName = Callee->getName();
1118
1119 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1120 (Func == LibFunc::exp || Func == LibFunc::exp2))
1121 return EmitUnaryFloatFnCall(
1122 B.CreateFMul(OpC->getArgOperand(0), Op2, "mul"), FuncName, B,
1123 Callee->getAttributes());
1124 }
1125 }
1126
Chris Bienemanad070d02014-09-17 20:55:46 +00001127 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1128 if (!Op2C)
1129 return Ret;
1130
1131 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1132 return ConstantFP::get(CI->getType(), 1.0);
1133
1134 if (Op2C->isExactlyValue(0.5) &&
1135 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1136 LibFunc::sqrtl) &&
1137 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1138 LibFunc::fabsl)) {
Davide Italianoc5cedd12015-11-18 23:21:32 +00001139
1140 // In -ffast-math, pow(x, 0.5) -> sqrt(x).
1141 if (unsafeFPMath)
1142 return EmitUnaryFloatFnCall(Op1, TLI->getName(LibFunc::sqrt), B,
1143 Callee->getAttributes());
1144
Chris Bienemanad070d02014-09-17 20:55:46 +00001145 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1146 // This is faster than calling pow, and still handles negative zero
1147 // and negative infinity correctly.
Chris Bienemanad070d02014-09-17 20:55:46 +00001148 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1149 Value *Inf = ConstantFP::getInfinity(CI->getType());
1150 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1151 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1152 Value *FAbs =
1153 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1154 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1155 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1156 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001157 }
1158
Chris Bienemanad070d02014-09-17 20:55:46 +00001159 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1160 return Op1;
1161 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1162 return B.CreateFMul(Op1, Op1, "pow2");
1163 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1164 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1165 return nullptr;
1166}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001167
Chris Bienemanad070d02014-09-17 20:55:46 +00001168Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1169 Function *Callee = CI->getCalledFunction();
1170 Function *Caller = CI->getParent()->getParent();
Chris Bienemanad070d02014-09-17 20:55:46 +00001171 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001172 StringRef Name = Callee->getName();
1173 if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
Chris Bienemanad070d02014-09-17 20:55:46 +00001174 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001175
Chris Bienemanad070d02014-09-17 20:55:46 +00001176 FunctionType *FT = Callee->getFunctionType();
1177 // Just make sure this has 1 argument of FP type, which matches the
1178 // result type.
1179 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1180 !FT->getParamType(0)->isFloatingPointTy())
1181 return Ret;
1182
1183 Value *Op = CI->getArgOperand(0);
1184 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1185 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1186 LibFunc::Func LdExp = LibFunc::ldexpl;
1187 if (Op->getType()->isFloatTy())
1188 LdExp = LibFunc::ldexpf;
1189 else if (Op->getType()->isDoubleTy())
1190 LdExp = LibFunc::ldexp;
1191
1192 if (TLI->has(LdExp)) {
1193 Value *LdExpArg = nullptr;
1194 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1195 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1196 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1197 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1198 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1199 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1200 }
1201
1202 if (LdExpArg) {
1203 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1204 if (!Op->getType()->isFloatTy())
1205 One = ConstantExpr::getFPExtend(One, Op->getType());
1206
1207 Module *M = Caller->getParent();
1208 Value *Callee =
1209 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001210 Op->getType(), B.getInt32Ty(), nullptr);
David Blaikieff6409d2015-05-18 22:13:54 +00001211 CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
Chris Bienemanad070d02014-09-17 20:55:46 +00001212 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1213 CI->setCallingConv(F->getCallingConv());
1214
1215 return CI;
1216 }
1217 }
1218 return Ret;
1219}
1220
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001221Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1222 Function *Callee = CI->getCalledFunction();
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001223 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001224 StringRef Name = Callee->getName();
1225 if (Name == "fabs" && hasFloatVersion(Name))
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001226 Ret = optimizeUnaryDoubleFP(CI, B, false);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001227
1228 FunctionType *FT = Callee->getFunctionType();
1229 // Make sure this has 1 argument of FP type which matches the result type.
1230 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1231 !FT->getParamType(0)->isFloatingPointTy())
1232 return Ret;
1233
1234 Value *Op = CI->getArgOperand(0);
1235 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1236 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1237 if (I->getOpcode() == Instruction::FMul)
1238 if (I->getOperand(0) == I->getOperand(1))
1239 return Op;
1240 }
1241 return Ret;
1242}
1243
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001244Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
1245 // If we can shrink the call to a float function rather than a double
1246 // function, do that first.
1247 Function *Callee = CI->getCalledFunction();
Davide Italianoa3458772015-11-05 19:18:23 +00001248 StringRef Name = Callee->getName();
1249 if ((Name == "fmin" && hasFloatVersion(Name)) ||
1250 (Name == "fmax" && hasFloatVersion(Name))) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001251 Value *Ret = optimizeBinaryDoubleFP(CI, B);
1252 if (Ret)
1253 return Ret;
1254 }
1255
1256 // Make sure this has 2 arguments of FP type which match the result type.
1257 FunctionType *FT = Callee->getFunctionType();
1258 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1259 FT->getParamType(0) != FT->getParamType(1) ||
1260 !FT->getParamType(0)->isFloatingPointTy())
1261 return nullptr;
1262
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001263 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001264 FastMathFlags FMF;
1265 Function *F = CI->getParent()->getParent();
Davide Italianoa904e522015-10-29 02:58:44 +00001266 if (canUseUnsafeFPMath(F)) {
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001267 // Unsafe algebra sets all fast-math-flags to true.
1268 FMF.setUnsafeAlgebra();
1269 } else {
1270 // At a minimum, no-nans-fp-math must be true.
Davide Italianoa904e522015-10-29 02:58:44 +00001271 Attribute Attr = F->getFnAttribute("no-nans-fp-math");
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001272 if (Attr.getValueAsString() != "true")
1273 return nullptr;
1274 // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
1275 // "Ideally, fmax would be sensitive to the sign of zero, for example
NAKAMURA Takumi0d725392015-09-07 00:26:54 +00001276 // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00001277 // might be impractical."
1278 FMF.setNoSignedZeros();
1279 FMF.setNoNaNs();
1280 }
1281 B.SetFastMathFlags(FMF);
1282
1283 // We have a relaxed floating-point environment. We can ignore NaN-handling
1284 // and transform to a compare and select. We do not have to consider errno or
1285 // exceptions, because fmin/fmax do not have those.
1286 Value *Op0 = CI->getArgOperand(0);
1287 Value *Op1 = CI->getArgOperand(1);
1288 Value *Cmp = Callee->getName().startswith("fmin") ?
1289 B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
1290 return B.CreateSelect(Cmp, Op0, Op1);
1291}
1292
Sanjay Patelc699a612014-10-16 18:48:17 +00001293Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1294 Function *Callee = CI->getCalledFunction();
1295
1296 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001297 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1298 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001299 Ret = optimizeUnaryDoubleFP(CI, B, true);
Davide Italianoa904e522015-10-29 02:58:44 +00001300 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1301 return Ret;
Sanjay Patelc699a612014-10-16 18:48:17 +00001302
Sanjay Patelc699a612014-10-16 18:48:17 +00001303 Value *Op = CI->getArgOperand(0);
1304 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1305 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1306 // We're looking for a repeated factor in a multiplication tree,
1307 // so we can do this fold: sqrt(x * x) -> fabs(x);
1308 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1309 Value *Op0 = I->getOperand(0);
1310 Value *Op1 = I->getOperand(1);
1311 Value *RepeatOp = nullptr;
1312 Value *OtherOp = nullptr;
1313 if (Op0 == Op1) {
1314 // Simple match: the operands of the multiply are identical.
1315 RepeatOp = Op0;
1316 } else {
1317 // Look for a more complicated pattern: one of the operands is itself
1318 // a multiply, so search for a common factor in that multiply.
1319 // Note: We don't bother looking any deeper than this first level or for
1320 // variations of this pattern because instcombine's visitFMUL and/or the
1321 // reassociation pass should give us this form.
1322 Value *OtherMul0, *OtherMul1;
1323 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1324 // Pattern: sqrt((x * y) * z)
1325 if (OtherMul0 == OtherMul1) {
1326 // Matched: sqrt((x * x) * z)
1327 RepeatOp = OtherMul0;
1328 OtherOp = Op1;
1329 }
1330 }
1331 }
1332 if (RepeatOp) {
1333 // Fast math flags for any created instructions should match the sqrt
1334 // and multiply.
1335 // FIXME: We're not checking the sqrt because it doesn't have
1336 // fast-math-flags (see earlier comment).
Benjamin Kramerbb70d752015-08-16 21:16:37 +00001337 IRBuilder<>::FastMathFlagGuard Guard(B);
Sanjay Patelc699a612014-10-16 18:48:17 +00001338 B.SetFastMathFlags(I->getFastMathFlags());
1339 // If we found a repeated factor, hoist it out of the square root and
1340 // replace it with the fabs of that factor.
1341 Module *M = Callee->getParent();
1342 Type *ArgType = Op->getType();
1343 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1344 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1345 if (OtherOp) {
1346 // If we found a non-repeated factor, we still need to get its square
1347 // root. We then multiply that by the value that was simplified out
1348 // of the square root calculation.
1349 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1350 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1351 return B.CreateFMul(FabsCall, SqrtCall);
1352 }
1353 return FabsCall;
1354 }
1355 }
1356 }
1357 return Ret;
1358}
1359
Davide Italiano51507d22015-11-04 23:36:56 +00001360Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
1361 Function *Callee = CI->getCalledFunction();
1362 Value *Ret = nullptr;
Davide Italianoa3458772015-11-05 19:18:23 +00001363 StringRef Name = Callee->getName();
1364 if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
Davide Italiano51507d22015-11-04 23:36:56 +00001365 Ret = optimizeUnaryDoubleFP(CI, B, true);
1366 FunctionType *FT = Callee->getFunctionType();
1367
1368 // Just make sure this has 1 argument of FP type, which matches the
1369 // result type.
1370 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1371 !FT->getParamType(0)->isFloatingPointTy())
1372 return Ret;
1373
1374 if (!canUseUnsafeFPMath(CI->getParent()->getParent()))
1375 return Ret;
1376 Value *Op1 = CI->getArgOperand(0);
1377 auto *OpC = dyn_cast<CallInst>(Op1);
1378 if (!OpC)
1379 return Ret;
1380
1381 // tan(atan(x)) -> x
1382 // tanf(atanf(x)) -> x
1383 // tanl(atanl(x)) -> x
1384 LibFunc::Func Func;
1385 Function *F = OpC->getCalledFunction();
1386 StringRef FuncName = F->getName();
1387 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func) &&
1388 ((Func == LibFunc::atan && Callee->getName() == "tan") ||
1389 (Func == LibFunc::atanf && Callee->getName() == "tanf") ||
1390 (Func == LibFunc::atanl && Callee->getName() == "tanl")))
1391 Ret = OpC->getArgOperand(0);
1392 return Ret;
1393}
1394
Chris Bienemanad070d02014-09-17 20:55:46 +00001395static bool isTrigLibCall(CallInst *CI);
1396static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1397 bool UseFloat, Value *&Sin, Value *&Cos,
1398 Value *&SinCos);
1399
1400Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1401
1402 // Make sure the prototype is as expected, otherwise the rest of the
1403 // function is probably invalid and likely to abort.
1404 if (!isTrigLibCall(CI))
1405 return nullptr;
1406
1407 Value *Arg = CI->getArgOperand(0);
1408 SmallVector<CallInst *, 1> SinCalls;
1409 SmallVector<CallInst *, 1> CosCalls;
1410 SmallVector<CallInst *, 1> SinCosCalls;
1411
1412 bool IsFloat = Arg->getType()->isFloatTy();
1413
1414 // Look for all compatible sinpi, cospi and sincospi calls with the same
1415 // argument. If there are enough (in some sense) we can make the
1416 // substitution.
1417 for (User *U : Arg->users())
1418 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1419 SinCosCalls);
1420
1421 // It's only worthwhile if both sinpi and cospi are actually used.
1422 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1423 return nullptr;
1424
1425 Value *Sin, *Cos, *SinCos;
1426 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1427
1428 replaceTrigInsts(SinCalls, Sin);
1429 replaceTrigInsts(CosCalls, Cos);
1430 replaceTrigInsts(SinCosCalls, SinCos);
1431
1432 return nullptr;
1433}
1434
1435static bool isTrigLibCall(CallInst *CI) {
1436 Function *Callee = CI->getCalledFunction();
1437 FunctionType *FT = Callee->getFunctionType();
1438
1439 // We can only hope to do anything useful if we can ignore things like errno
1440 // and floating-point exceptions.
1441 bool AttributesSafe =
1442 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1443
1444 // Other than that we need float(float) or double(double)
1445 return AttributesSafe && FT->getNumParams() == 1 &&
1446 FT->getReturnType() == FT->getParamType(0) &&
1447 (FT->getParamType(0)->isFloatTy() ||
1448 FT->getParamType(0)->isDoubleTy());
1449}
1450
1451void
1452LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1453 SmallVectorImpl<CallInst *> &SinCalls,
1454 SmallVectorImpl<CallInst *> &CosCalls,
1455 SmallVectorImpl<CallInst *> &SinCosCalls) {
1456 CallInst *CI = dyn_cast<CallInst>(Val);
1457
1458 if (!CI)
1459 return;
1460
1461 Function *Callee = CI->getCalledFunction();
1462 StringRef FuncName = Callee->getName();
1463 LibFunc::Func Func;
1464 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1465 return;
1466
1467 if (IsFloat) {
1468 if (Func == LibFunc::sinpif)
1469 SinCalls.push_back(CI);
1470 else if (Func == LibFunc::cospif)
1471 CosCalls.push_back(CI);
1472 else if (Func == LibFunc::sincospif_stret)
1473 SinCosCalls.push_back(CI);
1474 } else {
1475 if (Func == LibFunc::sinpi)
1476 SinCalls.push_back(CI);
1477 else if (Func == LibFunc::cospi)
1478 CosCalls.push_back(CI);
1479 else if (Func == LibFunc::sincospi_stret)
1480 SinCosCalls.push_back(CI);
1481 }
1482}
1483
1484void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1485 Value *Res) {
Davide Italianoc6926882015-10-27 04:17:51 +00001486 for (CallInst *C : Calls)
1487 replaceAllUsesWith(C, Res);
Chris Bienemanad070d02014-09-17 20:55:46 +00001488}
1489
1490void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1491 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1492 Type *ArgTy = Arg->getType();
1493 Type *ResTy;
1494 StringRef Name;
1495
1496 Triple T(OrigCallee->getParent()->getTargetTriple());
1497 if (UseFloat) {
1498 Name = "__sincospif_stret";
1499
1500 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1501 // x86_64 can't use {float, float} since that would be returned in both
1502 // xmm0 and xmm1, which isn't what a real struct would do.
1503 ResTy = T.getArch() == Triple::x86_64
1504 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001505 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001506 } else {
1507 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001508 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001509 }
1510
1511 Module *M = OrigCallee->getParent();
1512 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001513 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001514
1515 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1516 // If the argument is an instruction, it must dominate all uses so put our
1517 // sincos call there.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001518 B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
Chris Bienemanad070d02014-09-17 20:55:46 +00001519 } else {
1520 // Otherwise (e.g. for a constant) the beginning of the function is as
1521 // good a place as any.
1522 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1523 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1524 }
1525
1526 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1527
1528 if (SinCos->getType()->isStructTy()) {
1529 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1530 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1531 } else {
1532 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1533 "sinpi");
1534 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1535 "cospi");
1536 }
1537}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001538
Meador Inge7415f842012-11-25 20:45:27 +00001539//===----------------------------------------------------------------------===//
1540// Integer Library Call Optimizations
1541//===----------------------------------------------------------------------===//
1542
Davide Italiano396f3ee2015-10-31 23:17:45 +00001543static bool checkIntUnaryReturnAndParam(Function *Callee) {
1544 FunctionType *FT = Callee->getFunctionType();
Davide Italiano5cdf9152015-11-01 00:09:16 +00001545 return FT->getNumParams() == 1 && FT->getReturnType()->isIntegerTy(32) &&
1546 FT->getParamType(0)->isIntegerTy();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001547}
1548
Chris Bienemanad070d02014-09-17 20:55:46 +00001549Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1550 Function *Callee = CI->getCalledFunction();
Davide Italiano396f3ee2015-10-31 23:17:45 +00001551 if (!checkIntUnaryReturnAndParam(Callee))
Chris Bienemanad070d02014-09-17 20:55:46 +00001552 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001553 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001554
Chris Bienemanad070d02014-09-17 20:55:46 +00001555 // Constant fold.
1556 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1557 if (CI->isZero()) // ffs(0) -> 0.
1558 return B.getInt32(0);
1559 // ffs(c) -> cttz(c)+1
1560 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001561 }
Meador Inge7415f842012-11-25 20:45:27 +00001562
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1564 Type *ArgType = Op->getType();
1565 Value *F =
1566 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
Davide Italianoa1953862015-08-13 20:34:26 +00001567 Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
Chris Bienemanad070d02014-09-17 20:55:46 +00001568 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1569 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001570
Chris Bienemanad070d02014-09-17 20:55:46 +00001571 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1572 return B.CreateSelect(Cond, V, B.getInt32(0));
1573}
Meador Ingea0b6d872012-11-26 00:24:07 +00001574
Chris Bienemanad070d02014-09-17 20:55:46 +00001575Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1576 Function *Callee = CI->getCalledFunction();
1577 FunctionType *FT = Callee->getFunctionType();
1578 // We require integer(integer) where the types agree.
1579 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1580 FT->getParamType(0) != FT->getReturnType())
1581 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001582
Chris Bienemanad070d02014-09-17 20:55:46 +00001583 // abs(x) -> x >s -1 ? x : -x
1584 Value *Op = CI->getArgOperand(0);
1585 Value *Pos =
1586 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1587 Value *Neg = B.CreateNeg(Op, "neg");
1588 return B.CreateSelect(Pos, Op, Neg);
1589}
Meador Inge9a59ab62012-11-26 02:31:59 +00001590
Chris Bienemanad070d02014-09-17 20:55:46 +00001591Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001592 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001593 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001594
Chris Bienemanad070d02014-09-17 20:55:46 +00001595 // isdigit(c) -> (c-'0') <u 10
1596 Value *Op = CI->getArgOperand(0);
1597 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1598 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1599 return B.CreateZExt(Op, CI->getType());
1600}
Meador Ingea62a39e2012-11-26 03:10:07 +00001601
Chris Bienemanad070d02014-09-17 20:55:46 +00001602Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001603 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001604 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001605
Chris Bienemanad070d02014-09-17 20:55:46 +00001606 // isascii(c) -> c <u 128
1607 Value *Op = CI->getArgOperand(0);
1608 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1609 return B.CreateZExt(Op, CI->getType());
1610}
1611
1612Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
Davide Italiano396f3ee2015-10-31 23:17:45 +00001613 if (!checkIntUnaryReturnAndParam(CI->getCalledFunction()))
Chris Bienemanad070d02014-09-17 20:55:46 +00001614 return nullptr;
1615
1616 // toascii(c) -> c & 0x7f
1617 return B.CreateAnd(CI->getArgOperand(0),
1618 ConstantInt::get(CI->getType(), 0x7F));
1619}
Meador Inge604937d2012-11-26 03:38:52 +00001620
Meador Inge08ca1152012-11-26 20:37:20 +00001621//===----------------------------------------------------------------------===//
1622// Formatting and IO Library Call Optimizations
1623//===----------------------------------------------------------------------===//
1624
Chris Bienemanad070d02014-09-17 20:55:46 +00001625static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001626
Chris Bienemanad070d02014-09-17 20:55:46 +00001627Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1628 int StreamArg) {
1629 // Error reporting calls should be cold, mark them as such.
1630 // This applies even to non-builtin calls: it is only a hint and applies to
1631 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001632
Chris Bienemanad070d02014-09-17 20:55:46 +00001633 // This heuristic was suggested in:
1634 // Improving Static Branch Prediction in a Compiler
1635 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1636 // Proceedings of PACT'98, Oct. 1998, IEEE
1637 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001638
Chris Bienemanad070d02014-09-17 20:55:46 +00001639 if (!CI->hasFnAttr(Attribute::Cold) &&
1640 isReportingError(Callee, CI, StreamArg)) {
1641 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1642 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001643
Chris Bienemanad070d02014-09-17 20:55:46 +00001644 return nullptr;
1645}
1646
1647static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
Davide Italianoe84d4da2015-11-02 22:33:26 +00001648 if (!ColdErrorCalls || !Callee || !Callee->isDeclaration())
Chris Bienemanad070d02014-09-17 20:55:46 +00001649 return false;
1650
1651 if (StreamArg < 0)
1652 return true;
1653
1654 // These functions might be considered cold, but only if their stream
1655 // argument is stderr.
1656
1657 if (StreamArg >= (int)CI->getNumArgOperands())
1658 return false;
1659 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1660 if (!LI)
1661 return false;
1662 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1663 if (!GV || !GV->isDeclaration())
1664 return false;
1665 return GV->getName() == "stderr";
1666}
1667
1668Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1669 // Check for a fixed format string.
1670 StringRef FormatStr;
1671 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001672 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001673
Chris Bienemanad070d02014-09-17 20:55:46 +00001674 // Empty format string -> noop.
1675 if (FormatStr.empty()) // Tolerate printf's declared void.
1676 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001677
Chris Bienemanad070d02014-09-17 20:55:46 +00001678 // Do not do any of the following transformations if the printf return value
1679 // is used, in general the printf return value is not compatible with either
1680 // putchar() or puts().
1681 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001682 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001683
1684 // printf("x") -> putchar('x'), even for '%'.
1685 if (FormatStr.size() == 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001686 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001687 if (CI->use_empty() || !Res)
1688 return Res;
1689 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001690 }
1691
Chris Bienemanad070d02014-09-17 20:55:46 +00001692 // printf("foo\n") --> puts("foo")
1693 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1694 FormatStr.find('%') == StringRef::npos) { // No format characters.
1695 // Create a string literal with no \n on it. We expect the constant merge
1696 // pass to be run after this pass, to merge duplicate strings.
1697 FormatStr = FormatStr.drop_back();
1698 Value *GV = B.CreateGlobalString(FormatStr, "str");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001699 Value *NewCI = EmitPutS(GV, B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001700 return (CI->use_empty() || !NewCI)
1701 ? NewCI
1702 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1703 }
Meador Inge08ca1152012-11-26 20:37:20 +00001704
Chris Bienemanad070d02014-09-17 20:55:46 +00001705 // Optimize specific format strings.
1706 // printf("%c", chr) --> putchar(chr)
1707 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1708 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001709 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001710
Chris Bienemanad070d02014-09-17 20:55:46 +00001711 if (CI->use_empty() || !Res)
1712 return Res;
1713 return B.CreateIntCast(Res, CI->getType(), true);
1714 }
1715
1716 // printf("%s\n", str) --> puts(str)
1717 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1718 CI->getArgOperand(1)->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001719 return EmitPutS(CI->getArgOperand(1), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001720 }
1721 return nullptr;
1722}
1723
1724Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1725
1726 Function *Callee = CI->getCalledFunction();
1727 // Require one fixed pointer argument and an integer/void result.
1728 FunctionType *FT = Callee->getFunctionType();
1729 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1730 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1731 return nullptr;
1732
1733 if (Value *V = optimizePrintFString(CI, B)) {
1734 return V;
1735 }
1736
1737 // printf(format, ...) -> iprintf(format, ...) if no floating point
1738 // arguments.
1739 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1740 Module *M = B.GetInsertBlock()->getParent()->getParent();
1741 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001742 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 CallInst *New = cast<CallInst>(CI->clone());
1744 New->setCalledFunction(IPrintFFn);
1745 B.Insert(New);
1746 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001747 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001748 return nullptr;
1749}
Meador Inge08ca1152012-11-26 20:37:20 +00001750
Chris Bienemanad070d02014-09-17 20:55:46 +00001751Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1752 // Check for a fixed format string.
1753 StringRef FormatStr;
1754 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001755 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001756
Chris Bienemanad070d02014-09-17 20:55:46 +00001757 // If we just have a format string (nothing else crazy) transform it.
1758 if (CI->getNumArgOperands() == 2) {
1759 // Make sure there's no % in the constant array. We could try to handle
1760 // %% -> % in the future if we cared.
1761 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1762 if (FormatStr[i] == '%')
1763 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001764
Chris Bienemanad070d02014-09-17 20:55:46 +00001765 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001766 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1767 ConstantInt::get(DL.getIntPtrType(CI->getContext()),
1768 FormatStr.size() + 1),
Pete Cooper72bc23e2015-11-18 22:17:24 +00001769 1, 1); // Copy the null byte.
Chris Bienemanad070d02014-09-17 20:55:46 +00001770 return ConstantInt::get(CI->getType(), FormatStr.size());
Meador Ingef8e72502012-11-29 15:45:43 +00001771 }
Meador Ingef8e72502012-11-29 15:45:43 +00001772
Chris Bienemanad070d02014-09-17 20:55:46 +00001773 // The remaining optimizations require the format string to be "%s" or "%c"
1774 // and have an extra operand.
1775 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1776 CI->getNumArgOperands() < 3)
Craig Topperf40110f2014-04-25 05:29:35 +00001777 return nullptr;
Meador Inge75798bb2012-11-29 19:15:17 +00001778
Chris Bienemanad070d02014-09-17 20:55:46 +00001779 // Decode the second character of the format string.
1780 if (FormatStr[1] == 'c') {
1781 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1782 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1783 return nullptr;
1784 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1785 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1786 B.CreateStore(V, Ptr);
David Blaikie3909da72015-03-30 20:42:56 +00001787 Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
Chris Bienemanad070d02014-09-17 20:55:46 +00001788 B.CreateStore(B.getInt8(0), Ptr);
Meador Ingedf796f82012-10-13 16:45:24 +00001789
Chris Bienemanad070d02014-09-17 20:55:46 +00001790 return ConstantInt::get(CI->getType(), 1);
Meador Ingedf796f82012-10-13 16:45:24 +00001791 }
1792
Chris Bienemanad070d02014-09-17 20:55:46 +00001793 if (FormatStr[1] == 's') {
Chris Bienemanad070d02014-09-17 20:55:46 +00001794 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1795 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1796 return nullptr;
1797
1798 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1799 if (!Len)
1800 return nullptr;
1801 Value *IncLen =
1802 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
Pete Cooper72bc23e2015-11-18 22:17:24 +00001803 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1, 1);
Chris Bienemanad070d02014-09-17 20:55:46 +00001804
1805 // The sprintf result is the unincremented number of bytes in the string.
1806 return B.CreateIntCast(Len, CI->getType(), false);
1807 }
1808 return nullptr;
1809}
1810
1811Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1812 Function *Callee = CI->getCalledFunction();
1813 // Require two fixed pointer arguments and an integer result.
1814 FunctionType *FT = Callee->getFunctionType();
1815 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1816 !FT->getParamType(1)->isPointerTy() ||
1817 !FT->getReturnType()->isIntegerTy())
1818 return nullptr;
1819
1820 if (Value *V = optimizeSPrintFString(CI, B)) {
1821 return V;
1822 }
1823
1824 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1825 // point arguments.
1826 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1827 Module *M = B.GetInsertBlock()->getParent()->getParent();
1828 Constant *SIPrintFFn =
1829 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1830 CallInst *New = cast<CallInst>(CI->clone());
1831 New->setCalledFunction(SIPrintFFn);
1832 B.Insert(New);
1833 return New;
1834 }
1835 return nullptr;
1836}
1837
1838Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1839 optimizeErrorReporting(CI, B, 0);
1840
1841 // All the optimizations depend on the format string.
1842 StringRef FormatStr;
1843 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1844 return nullptr;
1845
1846 // Do not do any of the following transformations if the fprintf return
1847 // value is used, in general the fprintf return value is not compatible
1848 // with fwrite(), fputc() or fputs().
1849 if (!CI->use_empty())
1850 return nullptr;
1851
1852 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1853 if (CI->getNumArgOperands() == 2) {
1854 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1855 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1856 return nullptr; // We found a format specifier.
1857
Chris Bienemanad070d02014-09-17 20:55:46 +00001858 return EmitFWrite(
1859 CI->getArgOperand(1),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001860 ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
Chris Bienemanad070d02014-09-17 20:55:46 +00001861 CI->getArgOperand(0), B, DL, TLI);
1862 }
1863
1864 // The remaining optimizations require the format string to be "%s" or "%c"
1865 // and have an extra operand.
1866 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1867 CI->getNumArgOperands() < 3)
1868 return nullptr;
1869
1870 // Decode the second character of the format string.
1871 if (FormatStr[1] == 'c') {
1872 // fprintf(F, "%c", chr) --> fputc(chr, F)
1873 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1874 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001875 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001876 }
1877
1878 if (FormatStr[1] == 's') {
1879 // fprintf(F, "%s", str) --> fputs(str, F)
1880 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1881 return nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001882 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001883 }
1884 return nullptr;
1885}
1886
1887Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1888 Function *Callee = CI->getCalledFunction();
1889 // Require two fixed paramters as pointers and integer result.
1890 FunctionType *FT = Callee->getFunctionType();
1891 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1892 !FT->getParamType(1)->isPointerTy() ||
1893 !FT->getReturnType()->isIntegerTy())
1894 return nullptr;
1895
1896 if (Value *V = optimizeFPrintFString(CI, B)) {
1897 return V;
1898 }
1899
1900 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1901 // floating point arguments.
1902 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1903 Module *M = B.GetInsertBlock()->getParent()->getParent();
1904 Constant *FIPrintFFn =
1905 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1906 CallInst *New = cast<CallInst>(CI->clone());
1907 New->setCalledFunction(FIPrintFFn);
1908 B.Insert(New);
1909 return New;
1910 }
1911 return nullptr;
1912}
1913
1914Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1915 optimizeErrorReporting(CI, B, 3);
1916
1917 Function *Callee = CI->getCalledFunction();
1918 // Require a pointer, an integer, an integer, a pointer, returning integer.
1919 FunctionType *FT = Callee->getFunctionType();
1920 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1921 !FT->getParamType(1)->isIntegerTy() ||
1922 !FT->getParamType(2)->isIntegerTy() ||
1923 !FT->getParamType(3)->isPointerTy() ||
1924 !FT->getReturnType()->isIntegerTy())
1925 return nullptr;
1926
1927 // Get the element size and count.
1928 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1929 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1930 if (!SizeC || !CountC)
1931 return nullptr;
1932 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1933
1934 // If this is writing zero records, remove the call (it's a noop).
1935 if (Bytes == 0)
1936 return ConstantInt::get(CI->getType(), 0);
1937
1938 // If this is writing one byte, turn it into fputc.
1939 // This optimisation is only valid, if the return value is unused.
1940 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1941 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001942 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001943 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1944 }
1945
1946 return nullptr;
1947}
1948
1949Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1950 optimizeErrorReporting(CI, B, 1);
1951
1952 Function *Callee = CI->getCalledFunction();
1953
Chris Bienemanad070d02014-09-17 20:55:46 +00001954 // Require two pointers. Also, we can't optimize if return value is used.
1955 FunctionType *FT = Callee->getFunctionType();
1956 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1957 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1958 return nullptr;
1959
1960 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1961 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1962 if (!Len)
1963 return nullptr;
1964
1965 // Known to have no uses (see above).
1966 return EmitFWrite(
1967 CI->getArgOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001968 ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
Chris Bienemanad070d02014-09-17 20:55:46 +00001969 CI->getArgOperand(1), B, DL, TLI);
1970}
1971
1972Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1973 Function *Callee = CI->getCalledFunction();
1974 // Require one fixed pointer argument and an integer/void result.
1975 FunctionType *FT = Callee->getFunctionType();
1976 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1977 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1978 return nullptr;
1979
1980 // Check for a constant string.
1981 StringRef Str;
1982 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1983 return nullptr;
1984
1985 if (Str.empty() && CI->use_empty()) {
1986 // puts("") -> putchar('\n')
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001987 Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
Chris Bienemanad070d02014-09-17 20:55:46 +00001988 if (CI->use_empty() || !Res)
1989 return Res;
1990 return B.CreateIntCast(Res, CI->getType(), true);
1991 }
1992
1993 return nullptr;
1994}
1995
1996bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00001997 LibFunc::Func Func;
1998 SmallString<20> FloatFuncName = FuncName;
1999 FloatFuncName += 'f';
2000 if (TLI->getLibFunc(FloatFuncName, Func))
2001 return TLI->has(Func);
2002 return false;
2003}
Meador Inge7fb2f732012-10-13 16:45:32 +00002004
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002005Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
2006 IRBuilder<> &Builder) {
2007 LibFunc::Func Func;
2008 Function *Callee = CI->getCalledFunction();
2009 StringRef FuncName = Callee->getName();
2010
2011 // Check for string/memory library functions.
2012 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2013 // Make sure we never change the calling convention.
2014 assert((ignoreCallingConv(Func) ||
2015 CI->getCallingConv() == llvm::CallingConv::C) &&
2016 "Optimizing string/memory libcall would change the calling convention");
2017 switch (Func) {
2018 case LibFunc::strcat:
2019 return optimizeStrCat(CI, Builder);
2020 case LibFunc::strncat:
2021 return optimizeStrNCat(CI, Builder);
2022 case LibFunc::strchr:
2023 return optimizeStrChr(CI, Builder);
2024 case LibFunc::strrchr:
2025 return optimizeStrRChr(CI, Builder);
2026 case LibFunc::strcmp:
2027 return optimizeStrCmp(CI, Builder);
2028 case LibFunc::strncmp:
2029 return optimizeStrNCmp(CI, Builder);
2030 case LibFunc::strcpy:
2031 return optimizeStrCpy(CI, Builder);
2032 case LibFunc::stpcpy:
2033 return optimizeStpCpy(CI, Builder);
2034 case LibFunc::strncpy:
2035 return optimizeStrNCpy(CI, Builder);
2036 case LibFunc::strlen:
2037 return optimizeStrLen(CI, Builder);
2038 case LibFunc::strpbrk:
2039 return optimizeStrPBrk(CI, Builder);
2040 case LibFunc::strtol:
2041 case LibFunc::strtod:
2042 case LibFunc::strtof:
2043 case LibFunc::strtoul:
2044 case LibFunc::strtoll:
2045 case LibFunc::strtold:
2046 case LibFunc::strtoull:
2047 return optimizeStrTo(CI, Builder);
2048 case LibFunc::strspn:
2049 return optimizeStrSpn(CI, Builder);
2050 case LibFunc::strcspn:
2051 return optimizeStrCSpn(CI, Builder);
2052 case LibFunc::strstr:
2053 return optimizeStrStr(CI, Builder);
Benjamin Kramer691363e2015-03-21 15:36:21 +00002054 case LibFunc::memchr:
2055 return optimizeMemChr(CI, Builder);
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002056 case LibFunc::memcmp:
2057 return optimizeMemCmp(CI, Builder);
2058 case LibFunc::memcpy:
2059 return optimizeMemCpy(CI, Builder);
2060 case LibFunc::memmove:
2061 return optimizeMemMove(CI, Builder);
2062 case LibFunc::memset:
2063 return optimizeMemSet(CI, Builder);
2064 default:
2065 break;
2066 }
2067 }
2068 return nullptr;
2069}
2070
Chris Bienemanad070d02014-09-17 20:55:46 +00002071Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2072 if (CI->isNoBuiltin())
2073 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002074
Meador Inge20255ef2013-03-12 00:08:29 +00002075 LibFunc::Func Func;
2076 Function *Callee = CI->getCalledFunction();
2077 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002078 IRBuilder<> Builder(CI);
2079 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002080
Sanjay Patela92fa442014-10-22 15:29:23 +00002081 // Command-line parameter overrides function attribute.
2082 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2083 UnsafeFPShrink = EnableUnsafeFPShrink;
Davide Italianoa904e522015-10-29 02:58:44 +00002084 else if (canUseUnsafeFPMath(Callee))
2085 UnsafeFPShrink = true;
Sanjay Patela92fa442014-10-22 15:29:23 +00002086
Sanjay Patel848309d2014-10-23 21:52:45 +00002087 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002088 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002089 if (!isCallingConvC)
2090 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002091 switch (II->getIntrinsicID()) {
2092 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002093 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002094 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002095 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002096 case Intrinsic::fabs:
2097 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002098 case Intrinsic::sqrt:
2099 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002100 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002101 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002102 }
2103 }
2104
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002105 // Also try to simplify calls to fortified library functions.
2106 if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
2107 // Try to further simplify the result.
Ahmed Bougacha71d7b182015-01-14 00:55:05 +00002108 CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002109 if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
2110 // Use an IR Builder from SimplifiedCI if available instead of CI
2111 // to guarantee we reach all uses we might replace later on.
2112 IRBuilder<> TmpBuilder(SimplifiedCI);
2113 if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002114 // If we were able to further simplify, remove the now redundant call.
2115 SimplifiedCI->replaceAllUsesWith(V);
2116 SimplifiedCI->eraseFromParent();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002117 return V;
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002118 }
Bruno Cardoso Lopesb491a2d2015-10-01 22:43:53 +00002119 }
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002120 return SimplifiedFortifiedCI;
2121 }
2122
Meador Inge20255ef2013-03-12 00:08:29 +00002123 // Then check for known library functions.
2124 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002125 // We never change the calling convention.
2126 if (!ignoreCallingConv(Func) && !isCallingConvC)
2127 return nullptr;
Ahmed Bougacha6722f5e2015-01-12 17:20:06 +00002128 if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
2129 return V;
Meador Inge20255ef2013-03-12 00:08:29 +00002130 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002131 case LibFunc::cosf:
2132 case LibFunc::cos:
2133 case LibFunc::cosl:
2134 return optimizeCos(CI, Builder);
2135 case LibFunc::sinpif:
2136 case LibFunc::sinpi:
2137 case LibFunc::cospif:
2138 case LibFunc::cospi:
2139 return optimizeSinCosPi(CI, Builder);
2140 case LibFunc::powf:
2141 case LibFunc::pow:
2142 case LibFunc::powl:
2143 return optimizePow(CI, Builder);
2144 case LibFunc::exp2l:
2145 case LibFunc::exp2:
2146 case LibFunc::exp2f:
2147 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002148 case LibFunc::fabsf:
2149 case LibFunc::fabs:
2150 case LibFunc::fabsl:
2151 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002152 case LibFunc::sqrtf:
2153 case LibFunc::sqrt:
2154 case LibFunc::sqrtl:
2155 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002156 case LibFunc::ffs:
2157 case LibFunc::ffsl:
2158 case LibFunc::ffsll:
2159 return optimizeFFS(CI, Builder);
2160 case LibFunc::abs:
2161 case LibFunc::labs:
2162 case LibFunc::llabs:
2163 return optimizeAbs(CI, Builder);
2164 case LibFunc::isdigit:
2165 return optimizeIsDigit(CI, Builder);
2166 case LibFunc::isascii:
2167 return optimizeIsAscii(CI, Builder);
2168 case LibFunc::toascii:
2169 return optimizeToAscii(CI, Builder);
2170 case LibFunc::printf:
2171 return optimizePrintF(CI, Builder);
2172 case LibFunc::sprintf:
2173 return optimizeSPrintF(CI, Builder);
2174 case LibFunc::fprintf:
2175 return optimizeFPrintF(CI, Builder);
2176 case LibFunc::fwrite:
2177 return optimizeFWrite(CI, Builder);
2178 case LibFunc::fputs:
2179 return optimizeFPuts(CI, Builder);
2180 case LibFunc::puts:
2181 return optimizePuts(CI, Builder);
Davide Italiano51507d22015-11-04 23:36:56 +00002182 case LibFunc::tan:
2183 case LibFunc::tanf:
2184 case LibFunc::tanl:
2185 return optimizeTan(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002186 case LibFunc::perror:
2187 return optimizeErrorReporting(CI, Builder);
2188 case LibFunc::vfprintf:
2189 case LibFunc::fiprintf:
2190 return optimizeErrorReporting(CI, Builder, 0);
2191 case LibFunc::fputc:
2192 return optimizeErrorReporting(CI, Builder, 1);
2193 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002194 case LibFunc::floor:
2195 case LibFunc::rint:
2196 case LibFunc::round:
2197 case LibFunc::nearbyint:
2198 case LibFunc::trunc:
2199 if (hasFloatVersion(FuncName))
2200 return optimizeUnaryDoubleFP(CI, Builder, false);
2201 return nullptr;
2202 case LibFunc::acos:
2203 case LibFunc::acosh:
2204 case LibFunc::asin:
2205 case LibFunc::asinh:
2206 case LibFunc::atan:
2207 case LibFunc::atanh:
2208 case LibFunc::cbrt:
2209 case LibFunc::cosh:
2210 case LibFunc::exp:
2211 case LibFunc::exp10:
2212 case LibFunc::expm1:
2213 case LibFunc::log:
2214 case LibFunc::log10:
2215 case LibFunc::log1p:
2216 case LibFunc::log2:
2217 case LibFunc::logb:
2218 case LibFunc::sin:
2219 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002220 case LibFunc::tanh:
2221 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2222 return optimizeUnaryDoubleFP(CI, Builder, true);
2223 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002224 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002225 if (hasFloatVersion(FuncName))
2226 return optimizeBinaryDoubleFP(CI, Builder);
2227 return nullptr;
Sanjay Patel57fd1dc2015-08-16 20:18:19 +00002228 case LibFunc::fminf:
2229 case LibFunc::fmin:
2230 case LibFunc::fminl:
2231 case LibFunc::fmaxf:
2232 case LibFunc::fmax:
2233 case LibFunc::fmaxl:
2234 return optimizeFMinFMax(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002235 default:
2236 return nullptr;
2237 }
Meador Inge20255ef2013-03-12 00:08:29 +00002238 }
Craig Topperf40110f2014-04-25 05:29:35 +00002239 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002240}
2241
Chandler Carruth92803822015-01-21 02:11:59 +00002242LibCallSimplifier::LibCallSimplifier(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002243 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth92803822015-01-21 02:11:59 +00002244 function_ref<void(Instruction *, Value *)> Replacer)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002245 : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
Chandler Carruth92803822015-01-21 02:11:59 +00002246 Replacer(Replacer) {}
2247
2248void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
2249 // Indirect through the replacer used in this instance.
2250 Replacer(I, With);
Meador Ingedf796f82012-10-13 16:45:24 +00002251}
2252
Meador Ingedfb08a22013-06-20 19:48:07 +00002253// TODO:
2254// Additional cases that we need to add to this file:
2255//
2256// cbrt:
2257// * cbrt(expN(X)) -> expN(x/3)
2258// * cbrt(sqrt(x)) -> pow(x,1/6)
David Majnemer3354fe42015-08-26 18:30:16 +00002259// * cbrt(cbrt(x)) -> pow(x,1/9)
Meador Ingedfb08a22013-06-20 19:48:07 +00002260//
2261// exp, expf, expl:
2262// * exp(log(x)) -> x
2263//
2264// log, logf, logl:
2265// * log(exp(x)) -> x
2266// * log(x**y) -> y*log(x)
2267// * log(exp(y)) -> y*log(e)
2268// * log(exp2(y)) -> y*log(2)
2269// * log(exp10(y)) -> y*log(10)
2270// * log(sqrt(x)) -> 0.5*log(x)
2271// * log(pow(x,y)) -> y*log(x)
2272//
2273// lround, lroundf, lroundl:
2274// * lround(cnst) -> cnst'
2275//
2276// pow, powf, powl:
2277// * pow(exp(x),y) -> exp(x*y)
2278// * pow(sqrt(x),y) -> pow(x,y*0.5)
2279// * pow(pow(x,y),z)-> pow(x,y*z)
2280//
2281// round, roundf, roundl:
2282// * round(cnst) -> cnst'
2283//
2284// signbit:
2285// * signbit(cnst) -> cnst'
2286// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2287//
2288// sqrt, sqrtf, sqrtl:
2289// * sqrt(expN(x)) -> expN(x*0.5)
2290// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2291// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2292//
Meador Ingedfb08a22013-06-20 19:48:07 +00002293// tan, tanf, tanl:
2294// * tan(atan(x)) -> x
2295//
2296// trunc, truncf, truncl:
2297// * trunc(cnst) -> cnst'
2298//
2299//
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002300
2301//===----------------------------------------------------------------------===//
2302// Fortified Library Call Optimizations
2303//===----------------------------------------------------------------------===//
2304
2305bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
2306 unsigned ObjSizeOp,
2307 unsigned SizeOp,
2308 bool isString) {
2309 if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
2310 return true;
2311 if (ConstantInt *ObjSizeCI =
2312 dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
2313 if (ObjSizeCI->isAllOnesValue())
2314 return true;
2315 // If the object size wasn't -1 (unknown), bail out if we were asked to.
2316 if (OnlyLowerUnknownSize)
2317 return false;
2318 if (isString) {
2319 uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
2320 // If the length is 0 we don't know how long it is and so we can't
2321 // remove the check.
2322 if (Len == 0)
2323 return false;
2324 return ObjSizeCI->getZExtValue() >= Len;
2325 }
2326 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
2327 return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
2328 }
2329 return false;
2330}
2331
2332Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
2333 Function *Callee = CI->getCalledFunction();
2334
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002335 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002336 return nullptr;
2337
2338 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2339 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper72bc23e2015-11-18 22:17:24 +00002340 CI->getArgOperand(2), 1, 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002341 return CI->getArgOperand(0);
2342 }
2343 return nullptr;
2344}
2345
2346Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
2347 Function *Callee = CI->getCalledFunction();
2348
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002349 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002350 return nullptr;
2351
2352 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2353 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
Pete Cooper72bc23e2015-11-18 22:17:24 +00002354 CI->getArgOperand(2), 1, 1);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002355 return CI->getArgOperand(0);
2356 }
2357 return nullptr;
2358}
2359
2360Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
2361 Function *Callee = CI->getCalledFunction();
2362
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002363 if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002364 return nullptr;
2365
2366 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
2367 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
2368 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
2369 return CI->getArgOperand(0);
2370 }
2371 return nullptr;
2372}
2373
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002374Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
2375 IRBuilder<> &B,
2376 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002377 Function *Callee = CI->getCalledFunction();
2378 StringRef Name = Callee->getName();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002379 const DataLayout &DL = CI->getModule()->getDataLayout();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002380
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002381 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002382 return nullptr;
2383
2384 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
2385 *ObjSize = CI->getArgOperand(2);
2386
2387 // __stpcpy_chk(x,x,...) -> x+strlen(x)
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002388 if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002389 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
David Blaikieaa41cd52015-04-03 21:33:42 +00002390 return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002391 }
2392
2393 // If a) we don't have any length information, or b) we know this will
2394 // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
2395 // st[rp]cpy_chk call which may fail at runtime if the size is too long.
2396 // TODO: It might be nice to get a maximum length out of the possible
2397 // string lengths for varying.
David Blaikie65fab6d2015-04-03 21:32:06 +00002398 if (isFortifiedCallFoldable(CI, 2, 1, true))
2399 return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002400
David Blaikie65fab6d2015-04-03 21:32:06 +00002401 if (OnlyLowerUnknownSize)
2402 return nullptr;
2403
2404 // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
2405 uint64_t Len = GetStringLength(Src);
2406 if (Len == 0)
2407 return nullptr;
2408
2409 Type *SizeTTy = DL.getIntPtrType(CI->getContext());
2410 Value *LenV = ConstantInt::get(SizeTTy, Len);
2411 Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
2412 // If the function was an __stpcpy_chk, and we were able to fold it into
2413 // a __memcpy_chk, we still need to return the correct end pointer.
2414 if (Ret && Func == LibFunc::stpcpy_chk)
2415 return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
2416 return Ret;
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002417}
2418
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002419Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
2420 IRBuilder<> &B,
2421 LibFunc::Func Func) {
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002422 Function *Callee = CI->getCalledFunction();
2423 StringRef Name = Callee->getName();
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002424
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002425 if (!checkStringCopyLibFuncSignature(Callee, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002426 return nullptr;
2427 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002428 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
2429 CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002430 return Ret;
2431 }
2432 return nullptr;
2433}
2434
2435Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002436 // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
2437 // Some clang users checked for _chk libcall availability using:
2438 // __has_builtin(__builtin___memcpy_chk)
2439 // When compiling with -fno-builtin, this is always true.
2440 // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
2441 // end up with fortified libcalls, which isn't acceptable in a freestanding
2442 // environment which only provides their non-fortified counterparts.
2443 //
2444 // Until we change clang and/or teach external users to check for availability
2445 // differently, disregard the "nobuiltin" attribute and TLI::has.
2446 //
2447 // PR23093.
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002448
2449 LibFunc::Func Func;
2450 Function *Callee = CI->getCalledFunction();
2451 StringRef FuncName = Callee->getName();
2452 IRBuilder<> Builder(CI);
2453 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
2454
2455 // First, check that this is a known library functions.
Ahmed Bougacha408d0102015-04-01 00:45:09 +00002456 if (!TLI->getLibFunc(FuncName, Func))
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002457 return nullptr;
2458
2459 // We never change the calling convention.
2460 if (!ignoreCallingConv(Func) && !isCallingConvC)
2461 return nullptr;
2462
2463 switch (Func) {
2464 case LibFunc::memcpy_chk:
2465 return optimizeMemCpyChk(CI, Builder);
2466 case LibFunc::memmove_chk:
2467 return optimizeMemMoveChk(CI, Builder);
2468 case LibFunc::memset_chk:
2469 return optimizeMemSetChk(CI, Builder);
2470 case LibFunc::stpcpy_chk:
2471 case LibFunc::strcpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002472 return optimizeStrpCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002473 case LibFunc::stpncpy_chk:
2474 case LibFunc::strncpy_chk:
Ahmed Bougacha1ac93562015-01-27 21:52:16 +00002475 return optimizeStrpNCpyChk(CI, Builder, Func);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002476 default:
2477 break;
2478 }
2479 return nullptr;
2480}
2481
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002482FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
2483 const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
2484 : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}