blob: 00d1ec6ef978865f9df0662c19b1d2f798780bd3 [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"
Meador Ingedf796f82012-10-13 16:45:24 +000033#include "llvm/Target/TargetLibraryInfo.h"
34#include "llvm/Transforms/Utils/BuildLibCalls.h"
35
36using namespace llvm;
Sanjay Patelc699a612014-10-16 18:48:17 +000037using namespace PatternMatch;
Meador Ingedf796f82012-10-13 16:45:24 +000038
Hal Finkel66cd3f12013-11-17 02:06:35 +000039static cl::opt<bool>
Chris Bienemanad070d02014-09-17 20:55:46 +000040 ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
41 cl::desc("Treat error-reporting calls as cold"));
Meador Ingedf796f82012-10-13 16:45:24 +000042
Sanjay Patela92fa442014-10-22 15:29:23 +000043static cl::opt<bool>
44 EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
45 cl::init(false),
46 cl::desc("Enable unsafe double to float "
47 "shrinking for math lib calls"));
48
49
Meador Ingedf796f82012-10-13 16:45:24 +000050//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000051// Helper Functions
52//===----------------------------------------------------------------------===//
53
Chris Bienemanad070d02014-09-17 20:55:46 +000054static bool ignoreCallingConv(LibFunc::Func Func) {
55 switch (Func) {
56 case LibFunc::abs:
57 case LibFunc::labs:
58 case LibFunc::llabs:
59 case LibFunc::strlen:
60 return true;
61 default:
62 return false;
63 }
Chris Bienemancf93cbb2014-09-17 21:06:59 +000064 llvm_unreachable("All cases should be covered in the switch.");
Chris Bienemanad070d02014-09-17 20:55:46 +000065}
66
Meador Inged589ac62012-10-31 03:33:06 +000067/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
68/// value is equal or not-equal to zero.
69static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000070 for (User *U : V->users()) {
71 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inged589ac62012-10-31 03:33:06 +000072 if (IC->isEquality())
73 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
74 if (C->isNullValue())
75 continue;
76 // Unknown instruction.
77 return false;
78 }
79 return true;
80}
81
Meador Inge56edbc92012-11-11 03:51:48 +000082/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
83/// comparisons with With.
84static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
Chandler Carruthcdf47882014-03-09 03:16:01 +000085 for (User *U : V->users()) {
86 if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
Meador Inge56edbc92012-11-11 03:51:48 +000087 if (IC->isEquality() && IC->getOperand(1) == With)
88 continue;
89 // Unknown instruction.
90 return false;
91 }
92 return true;
93}
94
Meador Inge08ca1152012-11-26 20:37:20 +000095static bool callHasFloatingPointArgument(const CallInst *CI) {
96 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
97 it != e; ++it) {
98 if ((*it)->getType()->isFloatingPointTy())
99 return true;
100 }
101 return false;
102}
103
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000104/// \brief Check whether the overloaded unary floating point function
105/// corresponing to \a Ty is available.
106static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
107 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
108 LibFunc::Func LongDoubleFn) {
109 switch (Ty->getTypeID()) {
110 case Type::FloatTyID:
111 return TLI->has(FloatFn);
112 case Type::DoubleTyID:
113 return TLI->has(DoubleFn);
114 default:
115 return TLI->has(LongDoubleFn);
116 }
117}
118
Meador Inged589ac62012-10-31 03:33:06 +0000119//===----------------------------------------------------------------------===//
Meador Ingedf796f82012-10-13 16:45:24 +0000120// Fortified Library Call Optimizations
121//===----------------------------------------------------------------------===//
122
Chris Bienemanad070d02014-09-17 20:55:46 +0000123static bool isFortifiedCallFoldable(CallInst *CI, unsigned SizeCIOp, unsigned SizeArgOp,
124 bool isString) {
125 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
126 return true;
127 if (ConstantInt *SizeCI =
128 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
129 if (SizeCI->isAllOnesValue())
Meador Ingedf796f82012-10-13 16:45:24 +0000130 return true;
Chris Bienemanad070d02014-09-17 20:55:46 +0000131 if (isString) {
132 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
133 // If the length is 0 we don't know how long it is and so we can't
134 // remove the check.
135 if (Len == 0)
136 return false;
137 return SizeCI->getZExtValue() >= Len;
Meador Ingedf796f82012-10-13 16:45:24 +0000138 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000139 if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getArgOperand(SizeArgOp)))
140 return SizeCI->getZExtValue() >= Arg->getZExtValue();
Meador Ingedf796f82012-10-13 16:45:24 +0000141 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000142 return false;
143}
Meador Ingedf796f82012-10-13 16:45:24 +0000144
Chris Bienemanad070d02014-09-17 20:55:46 +0000145Value *LibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
146 Function *Callee = CI->getCalledFunction();
147 FunctionType *FT = Callee->getFunctionType();
148 LLVMContext &Context = CI->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000149
Chris Bienemanad070d02014-09-17 20:55:46 +0000150 // Check if this has the right signature.
151 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
152 !FT->getParamType(0)->isPointerTy() ||
153 !FT->getParamType(1)->isPointerTy() ||
154 FT->getParamType(2) != DL->getIntPtrType(Context) ||
155 FT->getParamType(3) != DL->getIntPtrType(Context))
156 return nullptr;
157
158 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
159 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
160 CI->getArgOperand(2), 1);
161 return CI->getArgOperand(0);
162 }
163 return nullptr;
164}
165
166Value *LibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
167 Function *Callee = CI->getCalledFunction();
168 FunctionType *FT = Callee->getFunctionType();
169 LLVMContext &Context = CI->getContext();
170
171 // Check if this has the right signature.
172 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
173 !FT->getParamType(0)->isPointerTy() ||
174 !FT->getParamType(1)->isPointerTy() ||
175 FT->getParamType(2) != DL->getIntPtrType(Context) ||
176 FT->getParamType(3) != DL->getIntPtrType(Context))
177 return nullptr;
178
179 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
180 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
181 CI->getArgOperand(2), 1);
182 return CI->getArgOperand(0);
183 }
184 return nullptr;
185}
186
187Value *LibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
188 Function *Callee = CI->getCalledFunction();
189 FunctionType *FT = Callee->getFunctionType();
190 LLVMContext &Context = CI->getContext();
191
192 // Check if this has the right signature.
193 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
194 !FT->getParamType(0)->isPointerTy() ||
195 !FT->getParamType(1)->isIntegerTy() ||
196 FT->getParamType(2) != DL->getIntPtrType(Context) ||
197 FT->getParamType(3) != DL->getIntPtrType(Context))
198 return nullptr;
199
200 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
201 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
202 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
203 return CI->getArgOperand(0);
204 }
205 return nullptr;
206}
207
208Value *LibCallSimplifier::optimizeStrCpyChk(CallInst *CI, IRBuilder<> &B) {
209 Function *Callee = CI->getCalledFunction();
210 StringRef Name = Callee->getName();
211 FunctionType *FT = Callee->getFunctionType();
212 LLVMContext &Context = CI->getContext();
213
214 // Check if this has the right signature.
215 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
216 FT->getParamType(0) != FT->getParamType(1) ||
217 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
218 FT->getParamType(2) != DL->getIntPtrType(Context))
219 return nullptr;
220
221 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
222 if (Dst == Src) // __strcpy_chk(x,x) -> x
223 return Src;
224
225 // If a) we don't have any length information, or b) we know this will
226 // fit then just lower to a plain strcpy. Otherwise we'll keep our
227 // strcpy_chk call which may fail at runtime if the size is too long.
228 // TODO: It might be nice to get a maximum length out of the possible
229 // string lengths for varying.
230 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
231 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
232 return Ret;
233 } else {
234 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
235 uint64_t Len = GetStringLength(Src);
236 if (Len == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000237 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000238
Chris Bienemanad070d02014-09-17 20:55:46 +0000239 // This optimization require DataLayout.
240 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000241 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000242
Chris Bienemanad070d02014-09-17 20:55:46 +0000243 Value *Ret = EmitMemCpyChk(
244 Dst, Src, ConstantInt::get(DL->getIntPtrType(Context), Len),
245 CI->getArgOperand(2), B, DL, TLI);
246 return Ret;
Meador Ingedf796f82012-10-13 16:45:24 +0000247 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000248 return nullptr;
249}
Meador Ingedf796f82012-10-13 16:45:24 +0000250
Chris Bienemanad070d02014-09-17 20:55:46 +0000251Value *LibCallSimplifier::optimizeStpCpyChk(CallInst *CI, IRBuilder<> &B) {
252 Function *Callee = CI->getCalledFunction();
253 StringRef Name = Callee->getName();
254 FunctionType *FT = Callee->getFunctionType();
255 LLVMContext &Context = CI->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000256
Chris Bienemanad070d02014-09-17 20:55:46 +0000257 // Check if this has the right signature.
258 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
259 FT->getParamType(0) != FT->getParamType(1) ||
260 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
261 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
262 return nullptr;
263
264 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
265 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
266 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
267 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
268 }
269
270 // If a) we don't have any length information, or b) we know this will
271 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
272 // stpcpy_chk call which may fail at runtime if the size is too long.
273 // TODO: It might be nice to get a maximum length out of the possible
274 // string lengths for varying.
275 if (isFortifiedCallFoldable(CI, 2, 1, true)) {
276 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
277 return Ret;
278 } else {
279 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
280 uint64_t Len = GetStringLength(Src);
281 if (Len == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000282 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000283
Chris Bienemanad070d02014-09-17 20:55:46 +0000284 // This optimization require DataLayout.
285 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000286 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +0000287
Chris Bienemanad070d02014-09-17 20:55:46 +0000288 Type *PT = FT->getParamType(0);
289 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
290 Value *DstEnd =
291 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
292 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000293 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000294 return DstEnd;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000295 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000296 return nullptr;
297}
Meador Ingecdb2ca52012-10-31 00:20:51 +0000298
Chris Bienemanad070d02014-09-17 20:55:46 +0000299Value *LibCallSimplifier::optimizeStrNCpyChk(CallInst *CI, IRBuilder<> &B) {
300 Function *Callee = CI->getCalledFunction();
301 StringRef Name = Callee->getName();
302 FunctionType *FT = Callee->getFunctionType();
303 LLVMContext &Context = CI->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000304
Chris Bienemanad070d02014-09-17 20:55:46 +0000305 // Check if this has the right signature.
306 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
307 FT->getParamType(0) != FT->getParamType(1) ||
308 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
309 !FT->getParamType(2)->isIntegerTy() ||
310 FT->getParamType(3) != DL->getIntPtrType(Context))
Craig Topperf40110f2014-04-25 05:29:35 +0000311 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000312
313 if (isFortifiedCallFoldable(CI, 3, 2, false)) {
314 Value *Ret =
315 EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
316 CI->getArgOperand(2), B, DL, TLI, Name.substr(2, 7));
317 return Ret;
Meador Ingedf796f82012-10-13 16:45:24 +0000318 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000319 return nullptr;
320}
Meador Ingedf796f82012-10-13 16:45:24 +0000321
Meador Inge7fb2f732012-10-13 16:45:32 +0000322//===----------------------------------------------------------------------===//
323// String and Memory Library Call Optimizations
324//===----------------------------------------------------------------------===//
325
Chris Bienemanad070d02014-09-17 20:55:46 +0000326Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
327 Function *Callee = CI->getCalledFunction();
328 // Verify the "strcat" function prototype.
329 FunctionType *FT = Callee->getFunctionType();
330 if (FT->getNumParams() != 2||
331 FT->getReturnType() != B.getInt8PtrTy() ||
332 FT->getParamType(0) != FT->getReturnType() ||
333 FT->getParamType(1) != FT->getReturnType())
334 return nullptr;
335
336 // Extract some information from the instruction
337 Value *Dst = CI->getArgOperand(0);
338 Value *Src = CI->getArgOperand(1);
339
340 // See if we can get the length of the input string.
341 uint64_t Len = GetStringLength(Src);
342 if (Len == 0)
343 return nullptr;
344 --Len; // Unbias length.
345
346 // Handle the simple, do-nothing case: strcat(x, "") -> x
347 if (Len == 0)
348 return Dst;
349
350 // These optimizations require DataLayout.
351 if (!DL)
352 return nullptr;
353
354 return emitStrLenMemCpy(Src, Dst, Len, B);
355}
356
357Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
358 IRBuilder<> &B) {
359 // We need to find the end of the destination string. That's where the
360 // memory is to be moved to. We just generate a call to strlen.
361 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
362 if (!DstLen)
363 return nullptr;
364
365 // Now that we have the destination's length, we must index into the
366 // destination's pointer to get the actual memcpy destination (end of
367 // the string .. we're concatenating).
368 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
369
370 // We have enough information to now generate the memcpy call to do the
371 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
372 B.CreateMemCpy(
373 CpyDst, Src,
374 ConstantInt::get(DL->getIntPtrType(Src->getContext()), Len + 1), 1);
375 return Dst;
376}
377
378Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
379 Function *Callee = CI->getCalledFunction();
380 // Verify the "strncat" function prototype.
381 FunctionType *FT = Callee->getFunctionType();
382 if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
383 FT->getParamType(0) != FT->getReturnType() ||
384 FT->getParamType(1) != FT->getReturnType() ||
385 !FT->getParamType(2)->isIntegerTy())
386 return nullptr;
387
388 // Extract some information from the instruction
389 Value *Dst = CI->getArgOperand(0);
390 Value *Src = CI->getArgOperand(1);
391 uint64_t Len;
392
393 // We don't do anything if length is not constant
394 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
395 Len = LengthArg->getZExtValue();
396 else
397 return nullptr;
398
399 // See if we can get the length of the input string.
400 uint64_t SrcLen = GetStringLength(Src);
401 if (SrcLen == 0)
402 return nullptr;
403 --SrcLen; // Unbias length.
404
405 // Handle the simple, do-nothing cases:
406 // strncat(x, "", c) -> x
407 // strncat(x, c, 0) -> x
408 if (SrcLen == 0 || Len == 0)
409 return Dst;
410
411 // These optimizations require DataLayout.
412 if (!DL)
413 return nullptr;
414
415 // We don't optimize this case
416 if (Len < SrcLen)
417 return nullptr;
418
419 // strncat(x, s, c) -> strcat(x, s)
420 // s is constant so the strcat can be optimized further
421 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
422}
423
424Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
425 Function *Callee = CI->getCalledFunction();
426 // Verify the "strchr" function prototype.
427 FunctionType *FT = Callee->getFunctionType();
428 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
429 FT->getParamType(0) != FT->getReturnType() ||
430 !FT->getParamType(1)->isIntegerTy(32))
431 return nullptr;
432
433 Value *SrcStr = CI->getArgOperand(0);
434
435 // If the second operand is non-constant, see if we can compute the length
436 // of the input string and turn this into memchr.
437 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
438 if (!CharC) {
439 // These optimizations require DataLayout.
440 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000441 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000442
Chris Bienemanad070d02014-09-17 20:55:46 +0000443 uint64_t Len = GetStringLength(SrcStr);
444 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
445 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000446
Chris Bienemanad070d02014-09-17 20:55:46 +0000447 return EmitMemChr(
448 SrcStr, CI->getArgOperand(1), // include nul.
449 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000450 }
451
Chris Bienemanad070d02014-09-17 20:55:46 +0000452 // Otherwise, the character is a constant, see if the first argument is
453 // a string literal. If so, we can constant fold.
454 StringRef Str;
455 if (!getConstantStringInfo(SrcStr, Str)) {
456 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
457 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
458 return nullptr;
459 }
460
461 // Compute the offset, make sure to handle the case when we're searching for
462 // zero (a weird way to spell strlen).
463 size_t I = (0xFF & CharC->getSExtValue()) == 0
464 ? Str.size()
465 : Str.find(CharC->getSExtValue());
466 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
467 return Constant::getNullValue(CI->getType());
468
469 // strchr(s+n,c) -> gep(s+n+i,c)
470 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
471}
472
473Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
474 Function *Callee = CI->getCalledFunction();
475 // Verify the "strrchr" function prototype.
476 FunctionType *FT = Callee->getFunctionType();
477 if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
478 FT->getParamType(0) != FT->getReturnType() ||
479 !FT->getParamType(1)->isIntegerTy(32))
480 return nullptr;
481
482 Value *SrcStr = CI->getArgOperand(0);
483 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
484
485 // Cannot fold anything if we're not looking for a constant.
486 if (!CharC)
487 return nullptr;
488
489 StringRef Str;
490 if (!getConstantStringInfo(SrcStr, Str)) {
491 // strrchr(s, 0) -> strchr(s, 0)
492 if (DL && CharC->isZero())
493 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
494 return nullptr;
495 }
496
497 // Compute the offset.
498 size_t I = (0xFF & CharC->getSExtValue()) == 0
499 ? Str.size()
500 : Str.rfind(CharC->getSExtValue());
501 if (I == StringRef::npos) // Didn't find the char. Return null.
502 return Constant::getNullValue(CI->getType());
503
504 // strrchr(s+n,c) -> gep(s+n+i,c)
505 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
506}
507
508Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
509 Function *Callee = CI->getCalledFunction();
510 // Verify the "strcmp" function prototype.
511 FunctionType *FT = Callee->getFunctionType();
512 if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
513 FT->getParamType(0) != FT->getParamType(1) ||
514 FT->getParamType(0) != B.getInt8PtrTy())
515 return nullptr;
516
517 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
518 if (Str1P == Str2P) // strcmp(x,x) -> 0
519 return ConstantInt::get(CI->getType(), 0);
520
521 StringRef Str1, Str2;
522 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
523 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
524
525 // strcmp(x, y) -> cnst (if both x and y are constant strings)
526 if (HasStr1 && HasStr2)
527 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
528
529 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
530 return B.CreateNeg(
531 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
532
533 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
534 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
535
536 // strcmp(P, "x") -> memcmp(P, "x", 2)
537 uint64_t Len1 = GetStringLength(Str1P);
538 uint64_t Len2 = GetStringLength(Str2P);
539 if (Len1 && Len2) {
540 // These optimizations require DataLayout.
541 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000542 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000543
Chris Bienemanad070d02014-09-17 20:55:46 +0000544 return EmitMemCmp(Str1P, Str2P,
545 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
546 std::min(Len1, Len2)),
547 B, DL, TLI);
548 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000549
Chris Bienemanad070d02014-09-17 20:55:46 +0000550 return nullptr;
551}
552
553Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
554 Function *Callee = CI->getCalledFunction();
555 // Verify the "strncmp" function prototype.
556 FunctionType *FT = Callee->getFunctionType();
557 if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
558 FT->getParamType(0) != FT->getParamType(1) ||
559 FT->getParamType(0) != B.getInt8PtrTy() ||
560 !FT->getParamType(2)->isIntegerTy())
561 return nullptr;
562
563 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
564 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
565 return ConstantInt::get(CI->getType(), 0);
566
567 // Get the length argument if it is constant.
568 uint64_t Length;
569 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
570 Length = LengthArg->getZExtValue();
571 else
572 return nullptr;
573
574 if (Length == 0) // strncmp(x,y,0) -> 0
575 return ConstantInt::get(CI->getType(), 0);
576
577 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
578 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
579
580 StringRef Str1, Str2;
581 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
582 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
583
584 // strncmp(x, y) -> cnst (if both x and y are constant strings)
585 if (HasStr1 && HasStr2) {
586 StringRef SubStr1 = Str1.substr(0, Length);
587 StringRef SubStr2 = Str2.substr(0, Length);
588 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
589 }
590
591 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
592 return B.CreateNeg(
593 B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
594
595 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
596 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
597
598 return nullptr;
599}
600
601Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
602 Function *Callee = CI->getCalledFunction();
603 // Verify the "strcpy" function prototype.
604 FunctionType *FT = Callee->getFunctionType();
605 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
606 FT->getParamType(0) != FT->getParamType(1) ||
607 FT->getParamType(0) != B.getInt8PtrTy())
608 return nullptr;
609
610 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
611 if (Dst == Src) // strcpy(x,x) -> x
612 return Src;
613
614 // These optimizations require DataLayout.
615 if (!DL)
616 return nullptr;
617
618 // See if we can get the length of the input string.
619 uint64_t Len = GetStringLength(Src);
620 if (Len == 0)
621 return nullptr;
622
623 // We have enough information to now generate the memcpy call to do the
624 // copy for us. Make a memcpy to copy the nul byte with align = 1.
625 B.CreateMemCpy(Dst, Src,
626 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len), 1);
627 return Dst;
628}
629
630Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
631 Function *Callee = CI->getCalledFunction();
632 // Verify the "stpcpy" function prototype.
633 FunctionType *FT = Callee->getFunctionType();
634 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
635 FT->getParamType(0) != FT->getParamType(1) ||
636 FT->getParamType(0) != B.getInt8PtrTy())
637 return nullptr;
638
639 // These optimizations require DataLayout.
640 if (!DL)
641 return nullptr;
642
643 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
644 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
645 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
646 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : nullptr;
647 }
648
649 // See if we can get the length of the input string.
650 uint64_t Len = GetStringLength(Src);
651 if (Len == 0)
652 return nullptr;
653
654 Type *PT = FT->getParamType(0);
655 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
656 Value *DstEnd =
657 B.CreateGEP(Dst, ConstantInt::get(DL->getIntPtrType(PT), Len - 1));
658
659 // We have enough information to now generate the memcpy call to do the
660 // copy for us. Make a memcpy to copy the nul byte with align = 1.
661 B.CreateMemCpy(Dst, Src, LenV, 1);
662 return DstEnd;
663}
664
665Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
666 Function *Callee = CI->getCalledFunction();
667 FunctionType *FT = Callee->getFunctionType();
668 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
669 FT->getParamType(0) != FT->getParamType(1) ||
670 FT->getParamType(0) != B.getInt8PtrTy() ||
671 !FT->getParamType(2)->isIntegerTy())
672 return nullptr;
673
674 Value *Dst = CI->getArgOperand(0);
675 Value *Src = CI->getArgOperand(1);
676 Value *LenOp = CI->getArgOperand(2);
677
678 // See if we can get the length of the input string.
679 uint64_t SrcLen = GetStringLength(Src);
680 if (SrcLen == 0)
681 return nullptr;
682 --SrcLen;
683
684 if (SrcLen == 0) {
685 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
686 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000687 return Dst;
688 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000689
Chris Bienemanad070d02014-09-17 20:55:46 +0000690 uint64_t Len;
691 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
692 Len = LengthArg->getZExtValue();
693 else
694 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000695
Chris Bienemanad070d02014-09-17 20:55:46 +0000696 if (Len == 0)
697 return Dst; // strncpy(x, y, 0) -> x
Meador Inge7fb2f732012-10-13 16:45:32 +0000698
Chris Bienemanad070d02014-09-17 20:55:46 +0000699 // These optimizations require DataLayout.
700 if (!DL)
701 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000702
Chris Bienemanad070d02014-09-17 20:55:46 +0000703 // Let strncpy handle the zero padding
704 if (Len > SrcLen + 1)
705 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000706
Chris Bienemanad070d02014-09-17 20:55:46 +0000707 Type *PT = FT->getParamType(0);
708 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
709 B.CreateMemCpy(Dst, Src, ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000710
Chris Bienemanad070d02014-09-17 20:55:46 +0000711 return Dst;
712}
Meador Inge7fb2f732012-10-13 16:45:32 +0000713
Chris Bienemanad070d02014-09-17 20:55:46 +0000714Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
715 Function *Callee = CI->getCalledFunction();
716 FunctionType *FT = Callee->getFunctionType();
717 if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
718 !FT->getReturnType()->isIntegerTy())
719 return nullptr;
Meador Inge7fb2f732012-10-13 16:45:32 +0000720
Chris Bienemanad070d02014-09-17 20:55:46 +0000721 Value *Src = CI->getArgOperand(0);
722
723 // Constant folding: strlen("xyz") -> 3
724 if (uint64_t Len = GetStringLength(Src))
725 return ConstantInt::get(CI->getType(), Len - 1);
726
727 // strlen(x?"foo":"bars") --> x ? 3 : 4
728 if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
729 uint64_t LenTrue = GetStringLength(SI->getTrueValue());
730 uint64_t LenFalse = GetStringLength(SI->getFalseValue());
731 if (LenTrue && LenFalse) {
732 Function *Caller = CI->getParent()->getParent();
733 emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
734 SI->getDebugLoc(),
735 "folded strlen(select) to select of constants");
736 return B.CreateSelect(SI->getCondition(),
737 ConstantInt::get(CI->getType(), LenTrue - 1),
738 ConstantInt::get(CI->getType(), LenFalse - 1));
739 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000740 }
Meador Inge7fb2f732012-10-13 16:45:32 +0000741
Chris Bienemanad070d02014-09-17 20:55:46 +0000742 // strlen(x) != 0 --> *x != 0
743 // strlen(x) == 0 --> *x == 0
744 if (isOnlyUsedInZeroEqualityComparison(CI))
745 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000746
Chris Bienemanad070d02014-09-17 20:55:46 +0000747 return nullptr;
748}
Meador Inge17418502012-10-13 16:45:37 +0000749
Chris Bienemanad070d02014-09-17 20:55:46 +0000750Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
751 Function *Callee = CI->getCalledFunction();
752 FunctionType *FT = Callee->getFunctionType();
753 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
754 FT->getParamType(1) != FT->getParamType(0) ||
755 FT->getReturnType() != FT->getParamType(0))
756 return nullptr;
Meador Inge17418502012-10-13 16:45:37 +0000757
Chris Bienemanad070d02014-09-17 20:55:46 +0000758 StringRef S1, S2;
759 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
760 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Meador Inge17418502012-10-13 16:45:37 +0000761
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000762 // strpbrk(s, "") -> nullptr
763 // strpbrk("", s) -> nullptr
Chris Bienemanad070d02014-09-17 20:55:46 +0000764 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
765 return Constant::getNullValue(CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000766
Chris Bienemanad070d02014-09-17 20:55:46 +0000767 // Constant folding.
768 if (HasS1 && HasS2) {
769 size_t I = S1.find_first_of(S2);
770 if (I == StringRef::npos) // No match.
Meador Inge17418502012-10-13 16:45:37 +0000771 return Constant::getNullValue(CI->getType());
772
Chris Bienemanad070d02014-09-17 20:55:46 +0000773 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Meador Inge17418502012-10-13 16:45:37 +0000774 }
Meador Inge17418502012-10-13 16:45:37 +0000775
Chris Bienemanad070d02014-09-17 20:55:46 +0000776 // strpbrk(s, "a") -> strchr(s, 'a')
777 if (DL && HasS2 && S2.size() == 1)
778 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
779
780 return nullptr;
781}
782
783Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
784 Function *Callee = CI->getCalledFunction();
785 FunctionType *FT = Callee->getFunctionType();
786 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
787 !FT->getParamType(0)->isPointerTy() ||
788 !FT->getParamType(1)->isPointerTy())
789 return nullptr;
790
791 Value *EndPtr = CI->getArgOperand(1);
792 if (isa<ConstantPointerNull>(EndPtr)) {
793 // With a null EndPtr, this function won't capture the main argument.
794 // It would be readonly too, except that it still may write to errno.
795 CI->addAttribute(1, Attribute::NoCapture);
796 }
797
798 return nullptr;
799}
800
801Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
802 Function *Callee = CI->getCalledFunction();
803 FunctionType *FT = Callee->getFunctionType();
804 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
805 FT->getParamType(1) != FT->getParamType(0) ||
806 !FT->getReturnType()->isIntegerTy())
807 return nullptr;
808
809 StringRef S1, S2;
810 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
811 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
812
813 // strspn(s, "") -> 0
814 // strspn("", s) -> 0
815 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
816 return Constant::getNullValue(CI->getType());
817
818 // Constant folding.
819 if (HasS1 && HasS2) {
820 size_t Pos = S1.find_first_not_of(S2);
821 if (Pos == StringRef::npos)
822 Pos = S1.size();
823 return ConstantInt::get(CI->getType(), Pos);
824 }
825
826 return nullptr;
827}
828
829Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
830 Function *Callee = CI->getCalledFunction();
831 FunctionType *FT = Callee->getFunctionType();
832 if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
833 FT->getParamType(1) != FT->getParamType(0) ||
834 !FT->getReturnType()->isIntegerTy())
835 return nullptr;
836
837 StringRef S1, S2;
838 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
839 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
840
841 // strcspn("", s) -> 0
842 if (HasS1 && S1.empty())
843 return Constant::getNullValue(CI->getType());
844
845 // Constant folding.
846 if (HasS1 && HasS2) {
847 size_t Pos = S1.find_first_of(S2);
848 if (Pos == StringRef::npos)
849 Pos = S1.size();
850 return ConstantInt::get(CI->getType(), Pos);
851 }
852
853 // strcspn(s, "") -> strlen(s)
854 if (DL && HasS2 && S2.empty())
855 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
856
857 return nullptr;
858}
859
860Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
861 Function *Callee = CI->getCalledFunction();
862 FunctionType *FT = Callee->getFunctionType();
863 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
864 !FT->getParamType(1)->isPointerTy() ||
865 !FT->getReturnType()->isPointerTy())
866 return nullptr;
867
868 // fold strstr(x, x) -> x.
869 if (CI->getArgOperand(0) == CI->getArgOperand(1))
870 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
871
872 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
873 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
874 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
875 if (!StrLen)
Craig Topperf40110f2014-04-25 05:29:35 +0000876 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000877 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
878 StrLen, B, DL, TLI);
879 if (!StrNCmp)
Craig Topperf40110f2014-04-25 05:29:35 +0000880 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000881 for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
882 ICmpInst *Old = cast<ICmpInst>(*UI++);
883 Value *Cmp =
884 B.CreateICmp(Old->getPredicate(), StrNCmp,
885 ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
886 replaceAllUsesWith(Old, Cmp);
Meador Inge17418502012-10-13 16:45:37 +0000887 }
Chris Bienemanad070d02014-09-17 20:55:46 +0000888 return CI;
889 }
Meador Inge17418502012-10-13 16:45:37 +0000890
Chris Bienemanad070d02014-09-17 20:55:46 +0000891 // See if either input string is a constant string.
892 StringRef SearchStr, ToFindStr;
893 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
894 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
895
896 // fold strstr(x, "") -> x.
897 if (HasStr2 && ToFindStr.empty())
898 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
899
900 // If both strings are known, constant fold it.
901 if (HasStr1 && HasStr2) {
902 size_t Offset = SearchStr.find(ToFindStr);
903
904 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Meador Inge17418502012-10-13 16:45:37 +0000905 return Constant::getNullValue(CI->getType());
906
Chris Bienemanad070d02014-09-17 20:55:46 +0000907 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
908 Value *Result = CastToCStr(CI->getArgOperand(0), B);
909 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
910 return B.CreateBitCast(Result, CI->getType());
Meador Inge17418502012-10-13 16:45:37 +0000911 }
Meador Inge17418502012-10-13 16:45:37 +0000912
Chris Bienemanad070d02014-09-17 20:55:46 +0000913 // fold strstr(x, "y") -> strchr(x, 'y').
914 if (HasStr2 && ToFindStr.size() == 1) {
915 Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
916 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
917 }
918 return nullptr;
919}
Meador Inge40b6fac2012-10-15 03:47:37 +0000920
Chris Bienemanad070d02014-09-17 20:55:46 +0000921Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
922 Function *Callee = CI->getCalledFunction();
923 FunctionType *FT = Callee->getFunctionType();
924 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
925 !FT->getParamType(1)->isPointerTy() ||
926 !FT->getReturnType()->isIntegerTy(32))
Craig Topperf40110f2014-04-25 05:29:35 +0000927 return nullptr;
Meador Inge40b6fac2012-10-15 03:47:37 +0000928
Chris Bienemanad070d02014-09-17 20:55:46 +0000929 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Meador Inge40b6fac2012-10-15 03:47:37 +0000930
Chris Bienemanad070d02014-09-17 20:55:46 +0000931 if (LHS == RHS) // memcmp(s,s,x) -> 0
932 return Constant::getNullValue(CI->getType());
Meador Inge40b6fac2012-10-15 03:47:37 +0000933
Chris Bienemanad070d02014-09-17 20:55:46 +0000934 // Make sure we have a constant length.
935 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
936 if (!LenC)
Craig Topperf40110f2014-04-25 05:29:35 +0000937 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000938 uint64_t Len = LenC->getZExtValue();
939
940 if (Len == 0) // memcmp(s1,s2,0) -> 0
941 return Constant::getNullValue(CI->getType());
942
943 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
944 if (Len == 1) {
945 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
946 CI->getType(), "lhsv");
947 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
948 CI->getType(), "rhsv");
949 return B.CreateSub(LHSV, RHSV, "chardiff");
Meador Inge40b6fac2012-10-15 03:47:37 +0000950 }
Meador Inge40b6fac2012-10-15 03:47:37 +0000951
Chris Bienemanad070d02014-09-17 20:55:46 +0000952 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
953 StringRef LHSStr, RHSStr;
954 if (getConstantStringInfo(LHS, LHSStr) &&
955 getConstantStringInfo(RHS, RHSStr)) {
956 // Make sure we're not reading out-of-bounds memory.
957 if (Len > LHSStr.size() || Len > RHSStr.size())
Craig Topperf40110f2014-04-25 05:29:35 +0000958 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +0000959 // Fold the memcmp and normalize the result. This way we get consistent
960 // results across multiple platforms.
961 uint64_t Ret = 0;
962 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
963 if (Cmp < 0)
964 Ret = -1;
965 else if (Cmp > 0)
966 Ret = 1;
967 return ConstantInt::get(CI->getType(), Ret);
Meador Inge000dbcc2012-10-18 18:12:40 +0000968 }
Meador Inge000dbcc2012-10-18 18:12:40 +0000969
Chris Bienemanad070d02014-09-17 20:55:46 +0000970 return nullptr;
971}
Meador Inge9a6a1902012-10-31 00:20:56 +0000972
Chris Bienemanad070d02014-09-17 20:55:46 +0000973Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
974 Function *Callee = CI->getCalledFunction();
975 // These optimizations require DataLayout.
976 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000977 return nullptr;
Meador Inged589ac62012-10-31 03:33:06 +0000978
Chris Bienemanad070d02014-09-17 20:55:46 +0000979 FunctionType *FT = Callee->getFunctionType();
980 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
981 !FT->getParamType(0)->isPointerTy() ||
982 !FT->getParamType(1)->isPointerTy() ||
983 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
Craig Topperf40110f2014-04-25 05:29:35 +0000984 return nullptr;
Meador Inge6f8e0112012-10-31 04:29:58 +0000985
Chris Bienemanad070d02014-09-17 20:55:46 +0000986 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
987 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
988 CI->getArgOperand(2), 1);
989 return CI->getArgOperand(0);
990}
Meador Inge05a625a2012-10-31 14:58:26 +0000991
Chris Bienemanad070d02014-09-17 20:55:46 +0000992Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
993 Function *Callee = CI->getCalledFunction();
994 // These optimizations require DataLayout.
995 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +0000996 return nullptr;
Meador Inge05a625a2012-10-31 14:58:26 +0000997
Chris Bienemanad070d02014-09-17 20:55:46 +0000998 FunctionType *FT = Callee->getFunctionType();
999 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1000 !FT->getParamType(0)->isPointerTy() ||
1001 !FT->getParamType(1)->isPointerTy() ||
1002 FT->getParamType(2) != DL->getIntPtrType(CI->getContext()))
Craig Topperf40110f2014-04-25 05:29:35 +00001003 return nullptr;
Meador Inge489b5d62012-11-08 01:33:50 +00001004
Chris Bienemanad070d02014-09-17 20:55:46 +00001005 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1006 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1007 CI->getArgOperand(2), 1);
1008 return CI->getArgOperand(0);
1009}
Meador Ingebcd88ef72012-11-10 15:16:48 +00001010
Chris Bienemanad070d02014-09-17 20:55:46 +00001011Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
1012 Function *Callee = CI->getCalledFunction();
1013 // These optimizations require DataLayout.
1014 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +00001015 return nullptr;
Meador Ingebcd88ef72012-11-10 15:16:48 +00001016
Chris Bienemanad070d02014-09-17 20:55:46 +00001017 FunctionType *FT = Callee->getFunctionType();
1018 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1019 !FT->getParamType(0)->isPointerTy() ||
1020 !FT->getParamType(1)->isIntegerTy() ||
1021 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Craig Topperf40110f2014-04-25 05:29:35 +00001022 return nullptr;
Meador Inge56edbc92012-11-11 03:51:48 +00001023
Chris Bienemanad070d02014-09-17 20:55:46 +00001024 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1025 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1026 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1027 return CI->getArgOperand(0);
1028}
Meador Inged4825782012-11-11 06:49:03 +00001029
Meador Inge193e0352012-11-13 04:16:17 +00001030//===----------------------------------------------------------------------===//
1031// Math Library Optimizations
1032//===----------------------------------------------------------------------===//
1033
Matthias Braund34e4d22014-12-03 21:46:33 +00001034/// Return a variant of Val with float type.
1035/// Currently this works in two cases: If Val is an FPExtension of a float
1036/// value to something bigger, simply return the operand.
1037/// If Val is a ConstantFP but can be converted to a float ConstantFP without
1038/// loss of precision do so.
1039static Value *valueHasFloatPrecision(Value *Val) {
1040 if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
1041 Value *Op = Cast->getOperand(0);
1042 if (Op->getType()->isFloatTy())
1043 return Op;
1044 }
1045 if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
1046 APFloat F = Const->getValueAPF();
Matthias Braun395a82f2014-12-03 22:10:39 +00001047 bool losesInfo;
Matthias Braund34e4d22014-12-03 21:46:33 +00001048 (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
Matthias Braun395a82f2014-12-03 22:10:39 +00001049 &losesInfo);
1050 if (!losesInfo)
Matthias Braund34e4d22014-12-03 21:46:33 +00001051 return ConstantFP::get(Const->getContext(), F);
1052 }
1053 return nullptr;
1054}
1055
Meador Inge193e0352012-11-13 04:16:17 +00001056//===----------------------------------------------------------------------===//
1057// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1058
Chris Bienemanad070d02014-09-17 20:55:46 +00001059Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
1060 bool CheckRetType) {
1061 Function *Callee = CI->getCalledFunction();
1062 FunctionType *FT = Callee->getFunctionType();
1063 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1064 !FT->getParamType(0)->isDoubleTy())
1065 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001066
Chris Bienemanad070d02014-09-17 20:55:46 +00001067 if (CheckRetType) {
1068 // Check if all the uses for function like 'sin' are converted to float.
1069 for (User *U : CI->users()) {
1070 FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
1071 if (!Cast || !Cast->getType()->isFloatTy())
1072 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001073 }
Meador Inge193e0352012-11-13 04:16:17 +00001074 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001075
1076 // If this is something like 'floor((double)floatval)', convert to floorf.
Matthias Braund34e4d22014-12-03 21:46:33 +00001077 Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
1078 if (V == nullptr)
Chris Bienemanad070d02014-09-17 20:55:46 +00001079 return nullptr;
1080
1081 // floor((double)floatval) -> (double)floorf(floatval)
Sanjay Patel848309d2014-10-23 21:52:45 +00001082 if (Callee->isIntrinsic()) {
1083 Module *M = CI->getParent()->getParent()->getParent();
1084 Intrinsic::ID IID = (Intrinsic::ID) Callee->getIntrinsicID();
1085 Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
1086 V = B.CreateCall(F, V);
1087 } else {
1088 // The call is a library call rather than an intrinsic.
1089 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1090 }
1091
Chris Bienemanad070d02014-09-17 20:55:46 +00001092 return B.CreateFPExt(V, B.getDoubleTy());
1093}
Meador Inge193e0352012-11-13 04:16:17 +00001094
Yi Jiang6ab044e2013-12-16 22:42:40 +00001095// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
Chris Bienemanad070d02014-09-17 20:55:46 +00001096Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
1097 Function *Callee = CI->getCalledFunction();
1098 FunctionType *FT = Callee->getFunctionType();
1099 // Just make sure this has 2 arguments of the same FP type, which match the
1100 // result type.
1101 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1102 FT->getParamType(0) != FT->getParamType(1) ||
1103 !FT->getParamType(0)->isFloatingPointTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001104 return nullptr;
Meador Inge193e0352012-11-13 04:16:17 +00001105
Chris Bienemanad070d02014-09-17 20:55:46 +00001106 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
Matthias Braund34e4d22014-12-03 21:46:33 +00001107 // or fmin(1.0, (double)floatval), then we convert it to fminf.
1108 Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
1109 if (V1 == nullptr)
1110 return nullptr;
1111 Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
1112 if (V2 == nullptr)
Craig Topperf40110f2014-04-25 05:29:35 +00001113 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001114
1115 // fmin((double)floatval1, (double)floatval2)
Matthias Braund34e4d22014-12-03 21:46:33 +00001116 // -> (double)fminf(floatval1, floatval2)
Sanjay Patel848309d2014-10-23 21:52:45 +00001117 // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
Matthias Braund34e4d22014-12-03 21:46:33 +00001118 Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1119 Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001120 return B.CreateFPExt(V, B.getDoubleTy());
1121}
1122
1123Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
1124 Function *Callee = CI->getCalledFunction();
1125 Value *Ret = nullptr;
1126 if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
1127 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001128 }
1129
Chris Bienemanad070d02014-09-17 20:55:46 +00001130 FunctionType *FT = Callee->getFunctionType();
1131 // Just make sure this has 1 argument of FP type, which matches the
1132 // result type.
1133 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1134 !FT->getParamType(0)->isFloatingPointTy())
1135 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001136
Chris Bienemanad070d02014-09-17 20:55:46 +00001137 // cos(-x) -> cos(x)
1138 Value *Op1 = CI->getArgOperand(0);
1139 if (BinaryOperator::isFNeg(Op1)) {
1140 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1141 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1142 }
1143 return Ret;
1144}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001145
Chris Bienemanad070d02014-09-17 20:55:46 +00001146Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
1147 Function *Callee = CI->getCalledFunction();
1148
1149 Value *Ret = nullptr;
1150 if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
1151 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001152 }
1153
Chris Bienemanad070d02014-09-17 20:55:46 +00001154 FunctionType *FT = Callee->getFunctionType();
1155 // Just make sure this has 2 arguments of the same FP type, which match the
1156 // result type.
1157 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1158 FT->getParamType(0) != FT->getParamType(1) ||
1159 !FT->getParamType(0)->isFloatingPointTy())
1160 return Ret;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001161
Chris Bienemanad070d02014-09-17 20:55:46 +00001162 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1163 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1164 // pow(1.0, x) -> 1.0
1165 if (Op1C->isExactlyValue(1.0))
1166 return Op1C;
1167 // pow(2.0, x) -> exp2(x)
1168 if (Op1C->isExactlyValue(2.0) &&
1169 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1170 LibFunc::exp2l))
1171 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1172 // pow(10.0, x) -> exp10(x)
1173 if (Op1C->isExactlyValue(10.0) &&
1174 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1175 LibFunc::exp10l))
1176 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1177 Callee->getAttributes());
Bob Wilsond8d92d92013-11-03 06:48:38 +00001178 }
1179
Chris Bienemanad070d02014-09-17 20:55:46 +00001180 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1181 if (!Op2C)
1182 return Ret;
1183
1184 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1185 return ConstantFP::get(CI->getType(), 1.0);
1186
1187 if (Op2C->isExactlyValue(0.5) &&
1188 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1189 LibFunc::sqrtl) &&
1190 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1191 LibFunc::fabsl)) {
1192 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1193 // This is faster than calling pow, and still handles negative zero
1194 // and negative infinity correctly.
1195 // TODO: In fast-math mode, this could be just sqrt(x).
1196 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1197 Value *Inf = ConstantFP::getInfinity(CI->getType());
1198 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1199 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
1200 Value *FAbs =
1201 EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
1202 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1203 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1204 return Sel;
Bob Wilsond8d92d92013-11-03 06:48:38 +00001205 }
1206
Chris Bienemanad070d02014-09-17 20:55:46 +00001207 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1208 return Op1;
1209 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1210 return B.CreateFMul(Op1, Op1, "pow2");
1211 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1212 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1213 return nullptr;
1214}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001215
Chris Bienemanad070d02014-09-17 20:55:46 +00001216Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
1217 Function *Callee = CI->getCalledFunction();
1218 Function *Caller = CI->getParent()->getParent();
Bob Wilsond8d92d92013-11-03 06:48:38 +00001219
Chris Bienemanad070d02014-09-17 20:55:46 +00001220 Value *Ret = nullptr;
1221 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
1222 TLI->has(LibFunc::exp2f)) {
1223 Ret = optimizeUnaryDoubleFP(CI, B, true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00001224 }
1225
Chris Bienemanad070d02014-09-17 20:55:46 +00001226 FunctionType *FT = Callee->getFunctionType();
1227 // Just make sure this has 1 argument of FP type, which matches the
1228 // result type.
1229 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1230 !FT->getParamType(0)->isFloatingPointTy())
1231 return Ret;
1232
1233 Value *Op = CI->getArgOperand(0);
1234 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1235 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1236 LibFunc::Func LdExp = LibFunc::ldexpl;
1237 if (Op->getType()->isFloatTy())
1238 LdExp = LibFunc::ldexpf;
1239 else if (Op->getType()->isDoubleTy())
1240 LdExp = LibFunc::ldexp;
1241
1242 if (TLI->has(LdExp)) {
1243 Value *LdExpArg = nullptr;
1244 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1245 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1246 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1247 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1248 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1249 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1250 }
1251
1252 if (LdExpArg) {
1253 Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
1254 if (!Op->getType()->isFloatTy())
1255 One = ConstantExpr::getFPExtend(One, Op->getType());
1256
1257 Module *M = Caller->getParent();
1258 Value *Callee =
1259 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001260 Op->getType(), B.getInt32Ty(), nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001261 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1262 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1263 CI->setCallingConv(F->getCallingConv());
1264
1265 return CI;
1266 }
1267 }
1268 return Ret;
1269}
1270
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00001271Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
1272 Function *Callee = CI->getCalledFunction();
1273
1274 Value *Ret = nullptr;
1275 if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
1276 Ret = optimizeUnaryDoubleFP(CI, B, false);
1277 }
1278
1279 FunctionType *FT = Callee->getFunctionType();
1280 // Make sure this has 1 argument of FP type which matches the result type.
1281 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1282 !FT->getParamType(0)->isFloatingPointTy())
1283 return Ret;
1284
1285 Value *Op = CI->getArgOperand(0);
1286 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1287 // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
1288 if (I->getOpcode() == Instruction::FMul)
1289 if (I->getOperand(0) == I->getOperand(1))
1290 return Op;
1291 }
1292 return Ret;
1293}
1294
Sanjay Patelc699a612014-10-16 18:48:17 +00001295Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
1296 Function *Callee = CI->getCalledFunction();
1297
1298 Value *Ret = nullptr;
Sanjay Patel848309d2014-10-23 21:52:45 +00001299 if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
1300 Callee->getIntrinsicID() == Intrinsic::sqrt))
Sanjay Patelc699a612014-10-16 18:48:17 +00001301 Ret = optimizeUnaryDoubleFP(CI, B, true);
Sanjay Patelc699a612014-10-16 18:48:17 +00001302
1303 // FIXME: For finer-grain optimization, we need intrinsics to have the same
1304 // fast-math flag decorations that are applied to FP instructions. For now,
1305 // we have to rely on the function-level unsafe-fp-math attribute to do this
1306 // optimization because there's no other way to express that the sqrt can be
1307 // reassociated.
1308 Function *F = CI->getParent()->getParent();
1309 if (F->hasFnAttribute("unsafe-fp-math")) {
1310 // Check for unsafe-fp-math = true.
1311 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
1312 if (Attr.getValueAsString() != "true")
1313 return Ret;
1314 }
1315 Value *Op = CI->getArgOperand(0);
1316 if (Instruction *I = dyn_cast<Instruction>(Op)) {
1317 if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
1318 // We're looking for a repeated factor in a multiplication tree,
1319 // so we can do this fold: sqrt(x * x) -> fabs(x);
1320 // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
1321 Value *Op0 = I->getOperand(0);
1322 Value *Op1 = I->getOperand(1);
1323 Value *RepeatOp = nullptr;
1324 Value *OtherOp = nullptr;
1325 if (Op0 == Op1) {
1326 // Simple match: the operands of the multiply are identical.
1327 RepeatOp = Op0;
1328 } else {
1329 // Look for a more complicated pattern: one of the operands is itself
1330 // a multiply, so search for a common factor in that multiply.
1331 // Note: We don't bother looking any deeper than this first level or for
1332 // variations of this pattern because instcombine's visitFMUL and/or the
1333 // reassociation pass should give us this form.
1334 Value *OtherMul0, *OtherMul1;
1335 if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
1336 // Pattern: sqrt((x * y) * z)
1337 if (OtherMul0 == OtherMul1) {
1338 // Matched: sqrt((x * x) * z)
1339 RepeatOp = OtherMul0;
1340 OtherOp = Op1;
1341 }
1342 }
1343 }
1344 if (RepeatOp) {
1345 // Fast math flags for any created instructions should match the sqrt
1346 // and multiply.
1347 // FIXME: We're not checking the sqrt because it doesn't have
1348 // fast-math-flags (see earlier comment).
1349 IRBuilder<true, ConstantFolder,
1350 IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
1351 B.SetFastMathFlags(I->getFastMathFlags());
1352 // If we found a repeated factor, hoist it out of the square root and
1353 // replace it with the fabs of that factor.
1354 Module *M = Callee->getParent();
1355 Type *ArgType = Op->getType();
1356 Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
1357 Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
1358 if (OtherOp) {
1359 // If we found a non-repeated factor, we still need to get its square
1360 // root. We then multiply that by the value that was simplified out
1361 // of the square root calculation.
1362 Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
1363 Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
1364 return B.CreateFMul(FabsCall, SqrtCall);
1365 }
1366 return FabsCall;
1367 }
1368 }
1369 }
1370 return Ret;
1371}
1372
Chris Bienemanad070d02014-09-17 20:55:46 +00001373static bool isTrigLibCall(CallInst *CI);
1374static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1375 bool UseFloat, Value *&Sin, Value *&Cos,
1376 Value *&SinCos);
1377
1378Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
1379
1380 // Make sure the prototype is as expected, otherwise the rest of the
1381 // function is probably invalid and likely to abort.
1382 if (!isTrigLibCall(CI))
1383 return nullptr;
1384
1385 Value *Arg = CI->getArgOperand(0);
1386 SmallVector<CallInst *, 1> SinCalls;
1387 SmallVector<CallInst *, 1> CosCalls;
1388 SmallVector<CallInst *, 1> SinCosCalls;
1389
1390 bool IsFloat = Arg->getType()->isFloatTy();
1391
1392 // Look for all compatible sinpi, cospi and sincospi calls with the same
1393 // argument. If there are enough (in some sense) we can make the
1394 // substitution.
1395 for (User *U : Arg->users())
1396 classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
1397 SinCosCalls);
1398
1399 // It's only worthwhile if both sinpi and cospi are actually used.
1400 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1401 return nullptr;
1402
1403 Value *Sin, *Cos, *SinCos;
1404 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
1405
1406 replaceTrigInsts(SinCalls, Sin);
1407 replaceTrigInsts(CosCalls, Cos);
1408 replaceTrigInsts(SinCosCalls, SinCos);
1409
1410 return nullptr;
1411}
1412
1413static bool isTrigLibCall(CallInst *CI) {
1414 Function *Callee = CI->getCalledFunction();
1415 FunctionType *FT = Callee->getFunctionType();
1416
1417 // We can only hope to do anything useful if we can ignore things like errno
1418 // and floating-point exceptions.
1419 bool AttributesSafe =
1420 CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
1421
1422 // Other than that we need float(float) or double(double)
1423 return AttributesSafe && FT->getNumParams() == 1 &&
1424 FT->getReturnType() == FT->getParamType(0) &&
1425 (FT->getParamType(0)->isFloatTy() ||
1426 FT->getParamType(0)->isDoubleTy());
1427}
1428
1429void
1430LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1431 SmallVectorImpl<CallInst *> &SinCalls,
1432 SmallVectorImpl<CallInst *> &CosCalls,
1433 SmallVectorImpl<CallInst *> &SinCosCalls) {
1434 CallInst *CI = dyn_cast<CallInst>(Val);
1435
1436 if (!CI)
1437 return;
1438
1439 Function *Callee = CI->getCalledFunction();
1440 StringRef FuncName = Callee->getName();
1441 LibFunc::Func Func;
1442 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
1443 return;
1444
1445 if (IsFloat) {
1446 if (Func == LibFunc::sinpif)
1447 SinCalls.push_back(CI);
1448 else if (Func == LibFunc::cospif)
1449 CosCalls.push_back(CI);
1450 else if (Func == LibFunc::sincospif_stret)
1451 SinCosCalls.push_back(CI);
1452 } else {
1453 if (Func == LibFunc::sinpi)
1454 SinCalls.push_back(CI);
1455 else if (Func == LibFunc::cospi)
1456 CosCalls.push_back(CI);
1457 else if (Func == LibFunc::sincospi_stret)
1458 SinCosCalls.push_back(CI);
1459 }
1460}
1461
1462void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
1463 Value *Res) {
1464 for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
1465 I != E; ++I) {
1466 replaceAllUsesWith(*I, Res);
1467 }
1468}
1469
1470void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1471 bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
1472 Type *ArgTy = Arg->getType();
1473 Type *ResTy;
1474 StringRef Name;
1475
1476 Triple T(OrigCallee->getParent()->getTargetTriple());
1477 if (UseFloat) {
1478 Name = "__sincospif_stret";
1479
1480 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1481 // x86_64 can't use {float, float} since that would be returned in both
1482 // xmm0 and xmm1, which isn't what a real struct would do.
1483 ResTy = T.getArch() == Triple::x86_64
1484 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001485 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
Chris Bienemanad070d02014-09-17 20:55:46 +00001486 } else {
1487 Name = "__sincospi_stret";
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001488 ResTy = StructType::get(ArgTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001489 }
1490
1491 Module *M = OrigCallee->getParent();
1492 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001493 ResTy, ArgTy, nullptr);
Chris Bienemanad070d02014-09-17 20:55:46 +00001494
1495 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1496 // If the argument is an instruction, it must dominate all uses so put our
1497 // sincos call there.
1498 BasicBlock::iterator Loc = ArgInst;
1499 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1500 } else {
1501 // Otherwise (e.g. for a constant) the beginning of the function is as
1502 // good a place as any.
1503 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1504 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1505 }
1506
1507 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1508
1509 if (SinCos->getType()->isStructTy()) {
1510 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1511 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1512 } else {
1513 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1514 "sinpi");
1515 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1516 "cospi");
1517 }
1518}
Bob Wilsond8d92d92013-11-03 06:48:38 +00001519
Meador Inge7415f842012-11-25 20:45:27 +00001520//===----------------------------------------------------------------------===//
1521// Integer Library Call Optimizations
1522//===----------------------------------------------------------------------===//
1523
Chris Bienemanad070d02014-09-17 20:55:46 +00001524Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
1525 Function *Callee = CI->getCalledFunction();
1526 FunctionType *FT = Callee->getFunctionType();
1527 // Just make sure this has 2 arguments of the same FP type, which match the
1528 // result type.
1529 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
1530 !FT->getParamType(0)->isIntegerTy())
1531 return nullptr;
Meador Inge7415f842012-11-25 20:45:27 +00001532
Chris Bienemanad070d02014-09-17 20:55:46 +00001533 Value *Op = CI->getArgOperand(0);
Meador Inge7415f842012-11-25 20:45:27 +00001534
Chris Bienemanad070d02014-09-17 20:55:46 +00001535 // Constant fold.
1536 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1537 if (CI->isZero()) // ffs(0) -> 0.
1538 return B.getInt32(0);
1539 // ffs(c) -> cttz(c)+1
1540 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Meador Inge7415f842012-11-25 20:45:27 +00001541 }
Meador Inge7415f842012-11-25 20:45:27 +00001542
Chris Bienemanad070d02014-09-17 20:55:46 +00001543 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1544 Type *ArgType = Op->getType();
1545 Value *F =
1546 Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
1547 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1548 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1549 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Meador Ingea0b6d872012-11-26 00:24:07 +00001550
Chris Bienemanad070d02014-09-17 20:55:46 +00001551 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1552 return B.CreateSelect(Cond, V, B.getInt32(0));
1553}
Meador Ingea0b6d872012-11-26 00:24:07 +00001554
Chris Bienemanad070d02014-09-17 20:55:46 +00001555Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
1556 Function *Callee = CI->getCalledFunction();
1557 FunctionType *FT = Callee->getFunctionType();
1558 // We require integer(integer) where the types agree.
1559 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1560 FT->getParamType(0) != FT->getReturnType())
1561 return nullptr;
Meador Inge9a59ab62012-11-26 02:31:59 +00001562
Chris Bienemanad070d02014-09-17 20:55:46 +00001563 // abs(x) -> x >s -1 ? x : -x
1564 Value *Op = CI->getArgOperand(0);
1565 Value *Pos =
1566 B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
1567 Value *Neg = B.CreateNeg(Op, "neg");
1568 return B.CreateSelect(Pos, Op, Neg);
1569}
Meador Inge9a59ab62012-11-26 02:31:59 +00001570
Chris Bienemanad070d02014-09-17 20:55:46 +00001571Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
1572 Function *Callee = CI->getCalledFunction();
1573 FunctionType *FT = Callee->getFunctionType();
1574 // We require integer(i32)
1575 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1576 !FT->getParamType(0)->isIntegerTy(32))
1577 return nullptr;
Meador Ingea62a39e2012-11-26 03:10:07 +00001578
Chris Bienemanad070d02014-09-17 20:55:46 +00001579 // isdigit(c) -> (c-'0') <u 10
1580 Value *Op = CI->getArgOperand(0);
1581 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1582 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1583 return B.CreateZExt(Op, CI->getType());
1584}
Meador Ingea62a39e2012-11-26 03:10:07 +00001585
Chris Bienemanad070d02014-09-17 20:55:46 +00001586Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
1587 Function *Callee = CI->getCalledFunction();
1588 FunctionType *FT = Callee->getFunctionType();
1589 // We require integer(i32)
1590 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1591 !FT->getParamType(0)->isIntegerTy(32))
1592 return nullptr;
Meador Inge604937d2012-11-26 03:38:52 +00001593
Chris Bienemanad070d02014-09-17 20:55:46 +00001594 // isascii(c) -> c <u 128
1595 Value *Op = CI->getArgOperand(0);
1596 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1597 return B.CreateZExt(Op, CI->getType());
1598}
1599
1600Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
1601 Function *Callee = CI->getCalledFunction();
1602 FunctionType *FT = Callee->getFunctionType();
1603 // We require i32(i32)
1604 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1605 !FT->getParamType(0)->isIntegerTy(32))
1606 return nullptr;
1607
1608 // toascii(c) -> c & 0x7f
1609 return B.CreateAnd(CI->getArgOperand(0),
1610 ConstantInt::get(CI->getType(), 0x7F));
1611}
Meador Inge604937d2012-11-26 03:38:52 +00001612
Meador Inge08ca1152012-11-26 20:37:20 +00001613//===----------------------------------------------------------------------===//
1614// Formatting and IO Library Call Optimizations
1615//===----------------------------------------------------------------------===//
1616
Chris Bienemanad070d02014-09-17 20:55:46 +00001617static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001618
Chris Bienemanad070d02014-09-17 20:55:46 +00001619Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
1620 int StreamArg) {
1621 // Error reporting calls should be cold, mark them as such.
1622 // This applies even to non-builtin calls: it is only a hint and applies to
1623 // functions that the frontend might not understand as builtins.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001624
Chris Bienemanad070d02014-09-17 20:55:46 +00001625 // This heuristic was suggested in:
1626 // Improving Static Branch Prediction in a Compiler
1627 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1628 // Proceedings of PACT'98, Oct. 1998, IEEE
1629 Function *Callee = CI->getCalledFunction();
Hal Finkel66cd3f12013-11-17 02:06:35 +00001630
Chris Bienemanad070d02014-09-17 20:55:46 +00001631 if (!CI->hasFnAttr(Attribute::Cold) &&
1632 isReportingError(Callee, CI, StreamArg)) {
1633 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1634 }
Hal Finkel66cd3f12013-11-17 02:06:35 +00001635
Chris Bienemanad070d02014-09-17 20:55:46 +00001636 return nullptr;
1637}
1638
1639static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
1640 if (!ColdErrorCalls)
1641 return false;
1642
1643 if (!Callee || !Callee->isDeclaration())
1644 return false;
1645
1646 if (StreamArg < 0)
1647 return true;
1648
1649 // These functions might be considered cold, but only if their stream
1650 // argument is stderr.
1651
1652 if (StreamArg >= (int)CI->getNumArgOperands())
1653 return false;
1654 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1655 if (!LI)
1656 return false;
1657 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1658 if (!GV || !GV->isDeclaration())
1659 return false;
1660 return GV->getName() == "stderr";
1661}
1662
1663Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
1664 // Check for a fixed format string.
1665 StringRef FormatStr;
1666 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001667 return nullptr;
Hal Finkel66cd3f12013-11-17 02:06:35 +00001668
Chris Bienemanad070d02014-09-17 20:55:46 +00001669 // Empty format string -> noop.
1670 if (FormatStr.empty()) // Tolerate printf's declared void.
1671 return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
Hal Finkel66cd3f12013-11-17 02:06:35 +00001672
Chris Bienemanad070d02014-09-17 20:55:46 +00001673 // Do not do any of the following transformations if the printf return value
1674 // is used, in general the printf return value is not compatible with either
1675 // putchar() or puts().
1676 if (!CI->use_empty())
Craig Topperf40110f2014-04-25 05:29:35 +00001677 return nullptr;
Chris Bienemanad070d02014-09-17 20:55:46 +00001678
1679 // printf("x") -> putchar('x'), even for '%'.
1680 if (FormatStr.size() == 1) {
1681 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
1682 if (CI->use_empty() || !Res)
1683 return Res;
1684 return B.CreateIntCast(Res, CI->getType(), true);
Meador Inge08ca1152012-11-26 20:37:20 +00001685 }
1686
Chris Bienemanad070d02014-09-17 20:55:46 +00001687 // printf("foo\n") --> puts("foo")
1688 if (FormatStr[FormatStr.size() - 1] == '\n' &&
1689 FormatStr.find('%') == StringRef::npos) { // No format characters.
1690 // Create a string literal with no \n on it. We expect the constant merge
1691 // pass to be run after this pass, to merge duplicate strings.
1692 FormatStr = FormatStr.drop_back();
1693 Value *GV = B.CreateGlobalString(FormatStr, "str");
1694 Value *NewCI = EmitPutS(GV, B, DL, TLI);
1695 return (CI->use_empty() || !NewCI)
1696 ? NewCI
1697 : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
1698 }
Meador Inge08ca1152012-11-26 20:37:20 +00001699
Chris Bienemanad070d02014-09-17 20:55:46 +00001700 // Optimize specific format strings.
1701 // printf("%c", chr) --> putchar(chr)
1702 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1703 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1704 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001705
Chris Bienemanad070d02014-09-17 20:55:46 +00001706 if (CI->use_empty() || !Res)
1707 return Res;
1708 return B.CreateIntCast(Res, CI->getType(), true);
1709 }
1710
1711 // printf("%s\n", str) --> puts(str)
1712 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1713 CI->getArgOperand(1)->getType()->isPointerTy()) {
1714 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
1715 }
1716 return nullptr;
1717}
1718
1719Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
1720
1721 Function *Callee = CI->getCalledFunction();
1722 // Require one fixed pointer argument and an integer/void result.
1723 FunctionType *FT = Callee->getFunctionType();
1724 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1725 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1726 return nullptr;
1727
1728 if (Value *V = optimizePrintFString(CI, B)) {
1729 return V;
1730 }
1731
1732 // printf(format, ...) -> iprintf(format, ...) if no floating point
1733 // arguments.
1734 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1735 Module *M = B.GetInsertBlock()->getParent()->getParent();
1736 Constant *IPrintFFn =
Meador Inge08ca1152012-11-26 20:37:20 +00001737 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
Chris Bienemanad070d02014-09-17 20:55:46 +00001738 CallInst *New = cast<CallInst>(CI->clone());
1739 New->setCalledFunction(IPrintFFn);
1740 B.Insert(New);
1741 return New;
Meador Inge08ca1152012-11-26 20:37:20 +00001742 }
Chris Bienemanad070d02014-09-17 20:55:46 +00001743 return nullptr;
1744}
Meador Inge08ca1152012-11-26 20:37:20 +00001745
Chris Bienemanad070d02014-09-17 20:55:46 +00001746Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
1747 // Check for a fixed format string.
1748 StringRef FormatStr;
1749 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Craig Topperf40110f2014-04-25 05:29:35 +00001750 return nullptr;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001751
Chris Bienemanad070d02014-09-17 20:55:46 +00001752 // If we just have a format string (nothing else crazy) transform it.
1753 if (CI->getNumArgOperands() == 2) {
1754 // Make sure there's no % in the constant array. We could try to handle
1755 // %% -> % in the future if we cared.
1756 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1757 if (FormatStr[i] == '%')
1758 return nullptr; // we found a format specifier, bail out.
Hal Finkel66cd3f12013-11-17 02:06:35 +00001759
Meador Ingef8e72502012-11-29 15:45:43 +00001760 // These optimizations require DataLayout.
Chris Bienemanad070d02014-09-17 20:55:46 +00001761 if (!DL)
Craig Topperf40110f2014-04-25 05:29:35 +00001762 return nullptr;
Meador Ingef8e72502012-11-29 15:45:43 +00001763
Chris Bienemanad070d02014-09-17 20:55:46 +00001764 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1765 B.CreateMemCpy(
1766 CI->getArgOperand(0), CI->getArgOperand(1),
1767 ConstantInt::get(DL->getIntPtrType(CI->getContext()),
1768 FormatStr.size() + 1),
1769 1); // Copy the null byte.
1770 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);
1787 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1788 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') {
1794 // These optimizations require DataLayout.
1795 if (!DL)
1796 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00001797
Chris Bienemanad070d02014-09-17 20:55:46 +00001798 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1799 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1800 return nullptr;
1801
1802 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
1803 if (!Len)
1804 return nullptr;
1805 Value *IncLen =
1806 B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
1807 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1808
1809 // The sprintf result is the unincremented number of bytes in the string.
1810 return B.CreateIntCast(Len, CI->getType(), false);
1811 }
1812 return nullptr;
1813}
1814
1815Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
1816 Function *Callee = CI->getCalledFunction();
1817 // Require two fixed pointer arguments and an integer result.
1818 FunctionType *FT = Callee->getFunctionType();
1819 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1820 !FT->getParamType(1)->isPointerTy() ||
1821 !FT->getReturnType()->isIntegerTy())
1822 return nullptr;
1823
1824 if (Value *V = optimizeSPrintFString(CI, B)) {
1825 return V;
1826 }
1827
1828 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1829 // point arguments.
1830 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1831 Module *M = B.GetInsertBlock()->getParent()->getParent();
1832 Constant *SIPrintFFn =
1833 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1834 CallInst *New = cast<CallInst>(CI->clone());
1835 New->setCalledFunction(SIPrintFFn);
1836 B.Insert(New);
1837 return New;
1838 }
1839 return nullptr;
1840}
1841
1842Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
1843 optimizeErrorReporting(CI, B, 0);
1844
1845 // All the optimizations depend on the format string.
1846 StringRef FormatStr;
1847 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1848 return nullptr;
1849
1850 // Do not do any of the following transformations if the fprintf return
1851 // value is used, in general the fprintf return value is not compatible
1852 // with fwrite(), fputc() or fputs().
1853 if (!CI->use_empty())
1854 return nullptr;
1855
1856 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1857 if (CI->getNumArgOperands() == 2) {
1858 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1859 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1860 return nullptr; // We found a format specifier.
1861
1862 // These optimizations require DataLayout.
1863 if (!DL)
1864 return nullptr;
1865
1866 return EmitFWrite(
1867 CI->getArgOperand(1),
1868 ConstantInt::get(DL->getIntPtrType(CI->getContext()), FormatStr.size()),
1869 CI->getArgOperand(0), B, DL, TLI);
1870 }
1871
1872 // The remaining optimizations require the format string to be "%s" or "%c"
1873 // and have an extra operand.
1874 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1875 CI->getNumArgOperands() < 3)
1876 return nullptr;
1877
1878 // Decode the second character of the format string.
1879 if (FormatStr[1] == 'c') {
1880 // fprintf(F, "%c", chr) --> fputc(chr, F)
1881 if (!CI->getArgOperand(2)->getType()->isIntegerTy())
1882 return nullptr;
1883 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1884 }
1885
1886 if (FormatStr[1] == 's') {
1887 // fprintf(F, "%s", str) --> fputs(str, F)
1888 if (!CI->getArgOperand(2)->getType()->isPointerTy())
1889 return nullptr;
1890 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
1891 }
1892 return nullptr;
1893}
1894
1895Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
1896 Function *Callee = CI->getCalledFunction();
1897 // Require two fixed paramters as pointers and integer result.
1898 FunctionType *FT = Callee->getFunctionType();
1899 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1900 !FT->getParamType(1)->isPointerTy() ||
1901 !FT->getReturnType()->isIntegerTy())
1902 return nullptr;
1903
1904 if (Value *V = optimizeFPrintFString(CI, B)) {
1905 return V;
1906 }
1907
1908 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1909 // floating point arguments.
1910 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1911 Module *M = B.GetInsertBlock()->getParent()->getParent();
1912 Constant *FIPrintFFn =
1913 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1914 CallInst *New = cast<CallInst>(CI->clone());
1915 New->setCalledFunction(FIPrintFFn);
1916 B.Insert(New);
1917 return New;
1918 }
1919 return nullptr;
1920}
1921
1922Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
1923 optimizeErrorReporting(CI, B, 3);
1924
1925 Function *Callee = CI->getCalledFunction();
1926 // Require a pointer, an integer, an integer, a pointer, returning integer.
1927 FunctionType *FT = Callee->getFunctionType();
1928 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1929 !FT->getParamType(1)->isIntegerTy() ||
1930 !FT->getParamType(2)->isIntegerTy() ||
1931 !FT->getParamType(3)->isPointerTy() ||
1932 !FT->getReturnType()->isIntegerTy())
1933 return nullptr;
1934
1935 // Get the element size and count.
1936 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1937 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1938 if (!SizeC || !CountC)
1939 return nullptr;
1940 uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
1941
1942 // If this is writing zero records, remove the call (it's a noop).
1943 if (Bytes == 0)
1944 return ConstantInt::get(CI->getType(), 0);
1945
1946 // If this is writing one byte, turn it into fputc.
1947 // This optimisation is only valid, if the return value is unused.
1948 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1949 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1950 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
1951 return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
1952 }
1953
1954 return nullptr;
1955}
1956
1957Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
1958 optimizeErrorReporting(CI, B, 1);
1959
1960 Function *Callee = CI->getCalledFunction();
1961
1962 // These optimizations require DataLayout.
1963 if (!DL)
1964 return nullptr;
1965
1966 // Require two pointers. Also, we can't optimize if return value is used.
1967 FunctionType *FT = Callee->getFunctionType();
1968 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1969 !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
1970 return nullptr;
1971
1972 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1973 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1974 if (!Len)
1975 return nullptr;
1976
1977 // Known to have no uses (see above).
1978 return EmitFWrite(
1979 CI->getArgOperand(0),
1980 ConstantInt::get(DL->getIntPtrType(CI->getContext()), Len - 1),
1981 CI->getArgOperand(1), B, DL, TLI);
1982}
1983
1984Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
1985 Function *Callee = CI->getCalledFunction();
1986 // Require one fixed pointer argument and an integer/void result.
1987 FunctionType *FT = Callee->getFunctionType();
1988 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1989 !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
1990 return nullptr;
1991
1992 // Check for a constant string.
1993 StringRef Str;
1994 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1995 return nullptr;
1996
1997 if (Str.empty() && CI->use_empty()) {
1998 // puts("") -> putchar('\n')
1999 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
2000 if (CI->use_empty() || !Res)
2001 return Res;
2002 return B.CreateIntCast(Res, CI->getType(), true);
2003 }
2004
2005 return nullptr;
2006}
2007
2008bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
Meador Inge20255ef2013-03-12 00:08:29 +00002009 LibFunc::Func Func;
2010 SmallString<20> FloatFuncName = FuncName;
2011 FloatFuncName += 'f';
2012 if (TLI->getLibFunc(FloatFuncName, Func))
2013 return TLI->has(Func);
2014 return false;
2015}
Meador Inge7fb2f732012-10-13 16:45:32 +00002016
Chris Bienemanad070d02014-09-17 20:55:46 +00002017Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
2018 if (CI->isNoBuiltin())
2019 return nullptr;
Meador Inge4d2827c2012-11-11 05:11:20 +00002020
Meador Inge20255ef2013-03-12 00:08:29 +00002021 LibFunc::Func Func;
2022 Function *Callee = CI->getCalledFunction();
2023 StringRef FuncName = Callee->getName();
Chris Bienemanad070d02014-09-17 20:55:46 +00002024 IRBuilder<> Builder(CI);
2025 bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
Meador Inge20255ef2013-03-12 00:08:29 +00002026
Sanjay Patela92fa442014-10-22 15:29:23 +00002027 // Command-line parameter overrides function attribute.
2028 if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
2029 UnsafeFPShrink = EnableUnsafeFPShrink;
2030 else if (Callee->hasFnAttribute("unsafe-fp-math")) {
2031 // FIXME: This is the same problem as described in optimizeSqrt().
2032 // If calls gain access to IR-level FMF, then use that instead of a
2033 // function attribute.
2034
2035 // Check for unsafe-fp-math = true.
2036 Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
2037 if (Attr.getValueAsString() == "true")
2038 UnsafeFPShrink = true;
2039 }
2040
Sanjay Patel848309d2014-10-23 21:52:45 +00002041 // First, check for intrinsics.
Meador Inge20255ef2013-03-12 00:08:29 +00002042 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002043 if (!isCallingConvC)
2044 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002045 switch (II->getIntrinsicID()) {
2046 case Intrinsic::pow:
Chris Bienemanad070d02014-09-17 20:55:46 +00002047 return optimizePow(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002048 case Intrinsic::exp2:
Chris Bienemanad070d02014-09-17 20:55:46 +00002049 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002050 case Intrinsic::fabs:
2051 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002052 case Intrinsic::sqrt:
2053 return optimizeSqrt(CI, Builder);
Meador Inge20255ef2013-03-12 00:08:29 +00002054 default:
Chris Bienemanad070d02014-09-17 20:55:46 +00002055 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002056 }
2057 }
2058
2059 // Then check for known library functions.
2060 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002061 // We never change the calling convention.
2062 if (!ignoreCallingConv(Func) && !isCallingConvC)
2063 return nullptr;
Meador Inge20255ef2013-03-12 00:08:29 +00002064 switch (Func) {
Chris Bienemanad070d02014-09-17 20:55:46 +00002065 case LibFunc::strcat:
2066 return optimizeStrCat(CI, Builder);
2067 case LibFunc::strncat:
2068 return optimizeStrNCat(CI, Builder);
2069 case LibFunc::strchr:
2070 return optimizeStrChr(CI, Builder);
2071 case LibFunc::strrchr:
2072 return optimizeStrRChr(CI, Builder);
2073 case LibFunc::strcmp:
2074 return optimizeStrCmp(CI, Builder);
2075 case LibFunc::strncmp:
2076 return optimizeStrNCmp(CI, Builder);
2077 case LibFunc::strcpy:
2078 return optimizeStrCpy(CI, Builder);
2079 case LibFunc::stpcpy:
2080 return optimizeStpCpy(CI, Builder);
2081 case LibFunc::strncpy:
2082 return optimizeStrNCpy(CI, Builder);
2083 case LibFunc::strlen:
2084 return optimizeStrLen(CI, Builder);
2085 case LibFunc::strpbrk:
2086 return optimizeStrPBrk(CI, Builder);
2087 case LibFunc::strtol:
2088 case LibFunc::strtod:
2089 case LibFunc::strtof:
2090 case LibFunc::strtoul:
2091 case LibFunc::strtoll:
2092 case LibFunc::strtold:
2093 case LibFunc::strtoull:
2094 return optimizeStrTo(CI, Builder);
2095 case LibFunc::strspn:
2096 return optimizeStrSpn(CI, Builder);
2097 case LibFunc::strcspn:
2098 return optimizeStrCSpn(CI, Builder);
2099 case LibFunc::strstr:
2100 return optimizeStrStr(CI, Builder);
2101 case LibFunc::memcmp:
2102 return optimizeMemCmp(CI, Builder);
2103 case LibFunc::memcpy:
2104 return optimizeMemCpy(CI, Builder);
2105 case LibFunc::memmove:
2106 return optimizeMemMove(CI, Builder);
2107 case LibFunc::memset:
2108 return optimizeMemSet(CI, Builder);
2109 case LibFunc::cosf:
2110 case LibFunc::cos:
2111 case LibFunc::cosl:
2112 return optimizeCos(CI, Builder);
2113 case LibFunc::sinpif:
2114 case LibFunc::sinpi:
2115 case LibFunc::cospif:
2116 case LibFunc::cospi:
2117 return optimizeSinCosPi(CI, Builder);
2118 case LibFunc::powf:
2119 case LibFunc::pow:
2120 case LibFunc::powl:
2121 return optimizePow(CI, Builder);
2122 case LibFunc::exp2l:
2123 case LibFunc::exp2:
2124 case LibFunc::exp2f:
2125 return optimizeExp2(CI, Builder);
Sanjay Patel0ca42bb2014-10-14 20:43:11 +00002126 case LibFunc::fabsf:
2127 case LibFunc::fabs:
2128 case LibFunc::fabsl:
2129 return optimizeFabs(CI, Builder);
Sanjay Patelc699a612014-10-16 18:48:17 +00002130 case LibFunc::sqrtf:
2131 case LibFunc::sqrt:
2132 case LibFunc::sqrtl:
2133 return optimizeSqrt(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002134 case LibFunc::ffs:
2135 case LibFunc::ffsl:
2136 case LibFunc::ffsll:
2137 return optimizeFFS(CI, Builder);
2138 case LibFunc::abs:
2139 case LibFunc::labs:
2140 case LibFunc::llabs:
2141 return optimizeAbs(CI, Builder);
2142 case LibFunc::isdigit:
2143 return optimizeIsDigit(CI, Builder);
2144 case LibFunc::isascii:
2145 return optimizeIsAscii(CI, Builder);
2146 case LibFunc::toascii:
2147 return optimizeToAscii(CI, Builder);
2148 case LibFunc::printf:
2149 return optimizePrintF(CI, Builder);
2150 case LibFunc::sprintf:
2151 return optimizeSPrintF(CI, Builder);
2152 case LibFunc::fprintf:
2153 return optimizeFPrintF(CI, Builder);
2154 case LibFunc::fwrite:
2155 return optimizeFWrite(CI, Builder);
2156 case LibFunc::fputs:
2157 return optimizeFPuts(CI, Builder);
2158 case LibFunc::puts:
2159 return optimizePuts(CI, Builder);
2160 case LibFunc::perror:
2161 return optimizeErrorReporting(CI, Builder);
2162 case LibFunc::vfprintf:
2163 case LibFunc::fiprintf:
2164 return optimizeErrorReporting(CI, Builder, 0);
2165 case LibFunc::fputc:
2166 return optimizeErrorReporting(CI, Builder, 1);
2167 case LibFunc::ceil:
Chris Bienemanad070d02014-09-17 20:55:46 +00002168 case LibFunc::floor:
2169 case LibFunc::rint:
2170 case LibFunc::round:
2171 case LibFunc::nearbyint:
2172 case LibFunc::trunc:
2173 if (hasFloatVersion(FuncName))
2174 return optimizeUnaryDoubleFP(CI, Builder, false);
2175 return nullptr;
2176 case LibFunc::acos:
2177 case LibFunc::acosh:
2178 case LibFunc::asin:
2179 case LibFunc::asinh:
2180 case LibFunc::atan:
2181 case LibFunc::atanh:
2182 case LibFunc::cbrt:
2183 case LibFunc::cosh:
2184 case LibFunc::exp:
2185 case LibFunc::exp10:
2186 case LibFunc::expm1:
2187 case LibFunc::log:
2188 case LibFunc::log10:
2189 case LibFunc::log1p:
2190 case LibFunc::log2:
2191 case LibFunc::logb:
2192 case LibFunc::sin:
2193 case LibFunc::sinh:
Chris Bienemanad070d02014-09-17 20:55:46 +00002194 case LibFunc::tan:
2195 case LibFunc::tanh:
2196 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2197 return optimizeUnaryDoubleFP(CI, Builder, true);
2198 return nullptr;
Matthias Braun892c9232014-12-03 21:46:29 +00002199 case LibFunc::copysign:
Chris Bienemanad070d02014-09-17 20:55:46 +00002200 case LibFunc::fmin:
2201 case LibFunc::fmax:
2202 if (hasFloatVersion(FuncName))
2203 return optimizeBinaryDoubleFP(CI, Builder);
2204 return nullptr;
2205 case LibFunc::memcpy_chk:
2206 return optimizeMemCpyChk(CI, Builder);
Ahmed Bougacha55a333d2014-11-12 21:23:34 +00002207 case LibFunc::memmove_chk:
2208 return optimizeMemMoveChk(CI, Builder);
2209 case LibFunc::memset_chk:
2210 return optimizeMemSetChk(CI, Builder);
2211 case LibFunc::strcpy_chk:
2212 return optimizeStrCpyChk(CI, Builder);
2213 case LibFunc::stpcpy_chk:
2214 return optimizeStpCpyChk(CI, Builder);
2215 case LibFunc::stpncpy_chk:
2216 case LibFunc::strncpy_chk:
2217 return optimizeStrNCpyChk(CI, Builder);
Chris Bienemanad070d02014-09-17 20:55:46 +00002218 default:
2219 return nullptr;
2220 }
Meador Inge20255ef2013-03-12 00:08:29 +00002221 }
2222
Craig Topperf40110f2014-04-25 05:29:35 +00002223 return nullptr;
Meador Ingedf796f82012-10-13 16:45:24 +00002224}
2225
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002226LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
Sanjay Patela92fa442014-10-22 15:29:23 +00002227 const TargetLibraryInfo *TLI) :
Chris Bienemanad070d02014-09-17 20:55:46 +00002228 DL(DL),
2229 TLI(TLI),
Sanjay Patela92fa442014-10-22 15:29:23 +00002230 UnsafeFPShrink(false) {
Meador Ingedf796f82012-10-13 16:45:24 +00002231}
2232
Meador Inge76fc1a42012-11-11 03:51:43 +00002233void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2234 I->replaceAllUsesWith(With);
2235 I->eraseFromParent();
2236}
2237
Meador Ingedfb08a22013-06-20 19:48:07 +00002238// TODO:
2239// Additional cases that we need to add to this file:
2240//
2241// cbrt:
2242// * cbrt(expN(X)) -> expN(x/3)
2243// * cbrt(sqrt(x)) -> pow(x,1/6)
2244// * cbrt(sqrt(x)) -> pow(x,1/9)
2245//
2246// exp, expf, expl:
2247// * exp(log(x)) -> x
2248//
2249// log, logf, logl:
2250// * log(exp(x)) -> x
2251// * log(x**y) -> y*log(x)
2252// * log(exp(y)) -> y*log(e)
2253// * log(exp2(y)) -> y*log(2)
2254// * log(exp10(y)) -> y*log(10)
2255// * log(sqrt(x)) -> 0.5*log(x)
2256// * log(pow(x,y)) -> y*log(x)
2257//
2258// lround, lroundf, lroundl:
2259// * lround(cnst) -> cnst'
2260//
2261// pow, powf, powl:
2262// * pow(exp(x),y) -> exp(x*y)
2263// * pow(sqrt(x),y) -> pow(x,y*0.5)
2264// * pow(pow(x,y),z)-> pow(x,y*z)
2265//
2266// round, roundf, roundl:
2267// * round(cnst) -> cnst'
2268//
2269// signbit:
2270// * signbit(cnst) -> cnst'
2271// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2272//
2273// sqrt, sqrtf, sqrtl:
2274// * sqrt(expN(x)) -> expN(x*0.5)
2275// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2276// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2277//
Meador Ingedfb08a22013-06-20 19:48:07 +00002278// tan, tanf, tanl:
2279// * tan(atan(x)) -> x
2280//
2281// trunc, truncf, truncl:
2282// * trunc(cnst) -> cnst'
2283//
2284//