blob: fbffd90a5476139f0c25991b4649688df905b9b7 [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"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
Meador Inge20255ef2013-03-12 00:08:29 +000025#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Intrinsics.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
Nadav Rotem464e8072013-02-27 05:53:43 +000029#include "llvm/Support/Allocator.h"
Hal Finkel66cd3f12013-11-17 02:06:35 +000030#include "llvm/Support/CommandLine.h"
Meador Ingedf796f82012-10-13 16:45:24 +000031#include "llvm/Target/TargetLibraryInfo.h"
32#include "llvm/Transforms/Utils/BuildLibCalls.h"
33
34using namespace llvm;
35
Hal Finkel66cd3f12013-11-17 02:06:35 +000036static cl::opt<bool>
37ColdErrorCalls("error-reporting-is-cold", cl::init(true),
38 cl::Hidden, cl::desc("Treat error-reporting calls as cold"));
39
Meador Ingedf796f82012-10-13 16:45:24 +000040/// This class is the abstract base class for the set of optimizations that
41/// corresponds to one library call.
42namespace {
43class LibCallOptimization {
44protected:
45 Function *Caller;
Rafael Espindola37dc9e12014-02-21 00:06:31 +000046 const DataLayout *DL;
Meador Ingedf796f82012-10-13 16:45:24 +000047 const TargetLibraryInfo *TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +000048 const LibCallSimplifier *LCS;
Meador Ingedf796f82012-10-13 16:45:24 +000049 LLVMContext* Context;
50public:
51 LibCallOptimization() { }
52 virtual ~LibCallOptimization() {}
53
54 /// callOptimizer - This pure virtual method is implemented by base classes to
55 /// do various optimizations. If this returns null then no transformation was
56 /// performed. If it returns CI, then it transformed the call and CI is to be
57 /// deleted. If it returns something else, replace CI with the new value and
58 /// delete CI.
59 virtual Value *callOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
60 =0;
61
Chad Rosier22d275f2013-02-08 18:00:14 +000062 /// ignoreCallingConv - Returns false if this transformation could possibly
63 /// change the calling convention.
64 virtual bool ignoreCallingConv() { return false; }
65
Rafael Espindola37dc9e12014-02-21 00:06:31 +000066 Value *optimizeCall(CallInst *CI, const DataLayout *DL,
Meador Inge76fc1a42012-11-11 03:51:43 +000067 const TargetLibraryInfo *TLI,
68 const LibCallSimplifier *LCS, IRBuilder<> &B) {
Meador Ingedf796f82012-10-13 16:45:24 +000069 Caller = CI->getParent()->getParent();
Rafael Espindola37dc9e12014-02-21 00:06:31 +000070 this->DL = DL;
Meador Ingedf796f82012-10-13 16:45:24 +000071 this->TLI = TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +000072 this->LCS = LCS;
Meador Ingedf796f82012-10-13 16:45:24 +000073 if (CI->getCalledFunction())
74 Context = &CI->getCalledFunction()->getContext();
75
76 // We never change the calling convention.
Chad Rosier22d275f2013-02-08 18:00:14 +000077 if (!ignoreCallingConv() && CI->getCallingConv() != llvm::CallingConv::C)
Meador Ingedf796f82012-10-13 16:45:24 +000078 return NULL;
79
80 return callOptimizer(CI->getCalledFunction(), CI, B);
81 }
82};
83
84//===----------------------------------------------------------------------===//
Meador Inged589ac62012-10-31 03:33:06 +000085// Helper Functions
86//===----------------------------------------------------------------------===//
87
88/// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
89/// value is equal or not-equal to zero.
90static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
92 UI != E; ++UI) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
94 if (IC->isEquality())
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 if (C->isNullValue())
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
103
Meador Inge56edbc92012-11-11 03:51:48 +0000104/// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
105/// comparisons with With.
106static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
107 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
108 UI != E; ++UI) {
109 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
110 if (IC->isEquality() && IC->getOperand(1) == With)
111 continue;
112 // Unknown instruction.
113 return false;
114 }
115 return true;
116}
117
Meador Inge08ca1152012-11-26 20:37:20 +0000118static bool callHasFloatingPointArgument(const CallInst *CI) {
119 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
120 it != e; ++it) {
121 if ((*it)->getType()->isFloatingPointTy())
122 return true;
123 }
124 return false;
125}
126
Benjamin Kramer2702caa2013-08-31 18:19:35 +0000127/// \brief Check whether the overloaded unary floating point function
128/// corresponing to \a Ty is available.
129static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
130 LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
131 LibFunc::Func LongDoubleFn) {
132 switch (Ty->getTypeID()) {
133 case Type::FloatTyID:
134 return TLI->has(FloatFn);
135 case Type::DoubleTyID:
136 return TLI->has(DoubleFn);
137 default:
138 return TLI->has(LongDoubleFn);
139 }
140}
141
Meador Inged589ac62012-10-31 03:33:06 +0000142//===----------------------------------------------------------------------===//
Meador Ingedf796f82012-10-13 16:45:24 +0000143// Fortified Library Call Optimizations
144//===----------------------------------------------------------------------===//
145
146struct FortifiedLibCallOptimization : public LibCallOptimization {
147protected:
148 virtual bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
149 bool isString) const = 0;
150};
151
152struct InstFortifiedLibCallOptimization : public FortifiedLibCallOptimization {
153 CallInst *CI;
154
Craig Topper3e4c6972014-03-05 09:10:37 +0000155 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp,
156 bool isString) const override {
Meador Ingedf796f82012-10-13 16:45:24 +0000157 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
158 return true;
159 if (ConstantInt *SizeCI =
160 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
161 if (SizeCI->isAllOnesValue())
162 return true;
163 if (isString) {
164 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
165 // If the length is 0 we don't know how long it is and so we can't
166 // remove the check.
167 if (Len == 0) return false;
168 return SizeCI->getZExtValue() >= Len;
169 }
170 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
171 CI->getArgOperand(SizeArgOp)))
172 return SizeCI->getZExtValue() >= Arg->getZExtValue();
173 }
174 return false;
175 }
176};
177
178struct MemCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000179 Value *callOptimizer(Function *Callee, CallInst *CI,
180 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000181 this->CI = CI;
182 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000183 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000184
185 // Check if this has the right signature.
186 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
187 !FT->getParamType(0)->isPointerTy() ||
188 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000189 FT->getParamType(2) != DL->getIntPtrType(Context) ||
190 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000191 return 0;
192
193 if (isFoldable(3, 2, false)) {
194 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
195 CI->getArgOperand(2), 1);
196 return CI->getArgOperand(0);
197 }
198 return 0;
199 }
200};
201
202struct MemMoveChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000203 Value *callOptimizer(Function *Callee, CallInst *CI,
204 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000205 this->CI = CI;
206 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000207 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000208
209 // Check if this has the right signature.
210 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
211 !FT->getParamType(0)->isPointerTy() ||
212 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000213 FT->getParamType(2) != DL->getIntPtrType(Context) ||
214 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000215 return 0;
216
217 if (isFoldable(3, 2, false)) {
218 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
219 CI->getArgOperand(2), 1);
220 return CI->getArgOperand(0);
221 }
222 return 0;
223 }
224};
225
226struct MemSetChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000227 Value *callOptimizer(Function *Callee, CallInst *CI,
228 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000229 this->CI = CI;
230 FunctionType *FT = Callee->getFunctionType();
Chandler Carruth7ec50852012-11-01 08:07:29 +0000231 LLVMContext &Context = CI->getParent()->getContext();
Meador Ingedf796f82012-10-13 16:45:24 +0000232
233 // Check if this has the right signature.
234 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
235 !FT->getParamType(0)->isPointerTy() ||
236 !FT->getParamType(1)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000237 FT->getParamType(2) != DL->getIntPtrType(Context) ||
238 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000239 return 0;
240
241 if (isFoldable(3, 2, false)) {
242 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(),
243 false);
244 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
245 return CI->getArgOperand(0);
246 }
247 return 0;
248 }
249};
250
251struct StrCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000252 Value *callOptimizer(Function *Callee, CallInst *CI,
253 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000254 this->CI = CI;
255 StringRef Name = Callee->getName();
256 FunctionType *FT = Callee->getFunctionType();
257 LLVMContext &Context = CI->getParent()->getContext();
258
259 // Check if this has the right signature.
260 if (FT->getNumParams() != 3 ||
261 FT->getReturnType() != FT->getParamType(0) ||
262 FT->getParamType(0) != FT->getParamType(1) ||
263 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000264 FT->getParamType(2) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000265 return 0;
266
Meador Inge000dbcc2012-10-18 18:12:40 +0000267 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
268 if (Dst == Src) // __strcpy_chk(x,x) -> x
269 return Src;
270
Meador Ingedf796f82012-10-13 16:45:24 +0000271 // If a) we don't have any length information, or b) we know this will
Meador Ingecdb2ca52012-10-31 00:20:51 +0000272 // fit then just lower to a plain strcpy. Otherwise we'll keep our
273 // strcpy_chk call which may fail at runtime if the size is too long.
Meador Ingedf796f82012-10-13 16:45:24 +0000274 // TODO: It might be nice to get a maximum length out of the possible
275 // string lengths for varying.
276 if (isFoldable(2, 1, true)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000277 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
Meador Inge000dbcc2012-10-18 18:12:40 +0000278 return Ret;
279 } else {
280 // Maybe we can stil fold __strcpy_chk to __memcpy_chk.
281 uint64_t Len = GetStringLength(Src);
282 if (Len == 0) return 0;
283
284 // This optimization require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000285 if (!DL) return 0;
Meador Inge000dbcc2012-10-18 18:12:40 +0000286
287 Value *Ret =
288 EmitMemCpyChk(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000289 ConstantInt::get(DL->getIntPtrType(Context), Len),
290 CI->getArgOperand(2), B, DL, TLI);
Meador Ingedf796f82012-10-13 16:45:24 +0000291 return Ret;
292 }
293 return 0;
294 }
295};
296
Meador Ingecdb2ca52012-10-31 00:20:51 +0000297struct StpCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000298 Value *callOptimizer(Function *Callee, CallInst *CI,
299 IRBuilder<> &B) override {
Meador Ingecdb2ca52012-10-31 00:20:51 +0000300 this->CI = CI;
301 StringRef Name = Callee->getName();
302 FunctionType *FT = Callee->getFunctionType();
303 LLVMContext &Context = CI->getParent()->getContext();
304
305 // Check if this has the right signature.
306 if (FT->getNumParams() != 3 ||
307 FT->getReturnType() != FT->getParamType(0) ||
308 FT->getParamType(0) != FT->getParamType(1) ||
309 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000310 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Meador Ingecdb2ca52012-10-31 00:20:51 +0000311 return 0;
312
313 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
314 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
Meador Ingecdb2ca52012-10-31 00:20:51 +0000316 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
317 }
318
319 // If a) we don't have any length information, or b) we know this will
320 // fit then just lower to a plain stpcpy. Otherwise we'll keep our
321 // stpcpy_chk call which may fail at runtime if the size is too long.
322 // TODO: It might be nice to get a maximum length out of the possible
323 // string lengths for varying.
324 if (isFoldable(2, 1, true)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000325 Value *Ret = EmitStrCpy(Dst, Src, B, DL, TLI, Name.substr(2, 6));
Meador Ingecdb2ca52012-10-31 00:20:51 +0000326 return Ret;
327 } else {
328 // Maybe we can stil fold __stpcpy_chk to __memcpy_chk.
329 uint64_t Len = GetStringLength(Src);
330 if (Len == 0) return 0;
331
332 // This optimization require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000333 if (!DL) return 0;
Meador Ingecdb2ca52012-10-31 00:20:51 +0000334
335 Type *PT = FT->getParamType(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000336 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
Meador Ingecdb2ca52012-10-31 00:20:51 +0000337 Value *DstEnd = B.CreateGEP(Dst,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000338 ConstantInt::get(DL->getIntPtrType(PT),
Meador Ingecdb2ca52012-10-31 00:20:51 +0000339 Len - 1));
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000340 if (!EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B, DL, TLI))
Meador Ingecdb2ca52012-10-31 00:20:51 +0000341 return 0;
342 return DstEnd;
343 }
344 return 0;
345 }
346};
347
Meador Ingedf796f82012-10-13 16:45:24 +0000348struct StrNCpyChkOpt : public InstFortifiedLibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000349 Value *callOptimizer(Function *Callee, CallInst *CI,
350 IRBuilder<> &B) override {
Meador Ingedf796f82012-10-13 16:45:24 +0000351 this->CI = CI;
352 StringRef Name = Callee->getName();
353 FunctionType *FT = Callee->getFunctionType();
354 LLVMContext &Context = CI->getParent()->getContext();
355
356 // Check if this has the right signature.
357 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
358 FT->getParamType(0) != FT->getParamType(1) ||
359 FT->getParamType(0) != Type::getInt8PtrTy(Context) ||
360 !FT->getParamType(2)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000361 FT->getParamType(3) != DL->getIntPtrType(Context))
Meador Ingedf796f82012-10-13 16:45:24 +0000362 return 0;
363
364 if (isFoldable(3, 2, false)) {
365 Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000366 CI->getArgOperand(2), B, DL, TLI,
Meador Ingedf796f82012-10-13 16:45:24 +0000367 Name.substr(2, 7));
368 return Ret;
369 }
370 return 0;
371 }
372};
373
Meador Inge7fb2f732012-10-13 16:45:32 +0000374//===----------------------------------------------------------------------===//
375// String and Memory Library Call Optimizations
376//===----------------------------------------------------------------------===//
377
378struct StrCatOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000379 Value *callOptimizer(Function *Callee, CallInst *CI,
380 IRBuilder<> &B) override {
Meador Inge7fb2f732012-10-13 16:45:32 +0000381 // Verify the "strcat" function prototype.
382 FunctionType *FT = Callee->getFunctionType();
383 if (FT->getNumParams() != 2 ||
384 FT->getReturnType() != B.getInt8PtrTy() ||
385 FT->getParamType(0) != FT->getReturnType() ||
386 FT->getParamType(1) != FT->getReturnType())
387 return 0;
388
389 // Extract some information from the instruction
390 Value *Dst = CI->getArgOperand(0);
391 Value *Src = CI->getArgOperand(1);
392
393 // See if we can get the length of the input string.
394 uint64_t Len = GetStringLength(Src);
395 if (Len == 0) return 0;
396 --Len; // Unbias length.
397
398 // Handle the simple, do-nothing case: strcat(x, "") -> x
399 if (Len == 0)
400 return Dst;
401
402 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000403 if (!DL) return 0;
Meador Inge7fb2f732012-10-13 16:45:32 +0000404
405 return emitStrLenMemCpy(Src, Dst, Len, B);
406 }
407
408 Value *emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
409 IRBuilder<> &B) {
410 // We need to find the end of the destination string. That's where the
411 // memory is to be moved to. We just generate a call to strlen.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000412 Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
Meador Inge7fb2f732012-10-13 16:45:32 +0000413 if (!DstLen)
414 return 0;
415
416 // Now that we have the destination's length, we must index into the
417 // destination's pointer to get the actual memcpy destination (end of
418 // the string .. we're concatenating).
419 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
420
421 // We have enough information to now generate the memcpy call to do the
422 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
423 B.CreateMemCpy(CpyDst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000424 ConstantInt::get(DL->getIntPtrType(*Context), Len + 1), 1);
Meador Inge7fb2f732012-10-13 16:45:32 +0000425 return Dst;
426 }
427};
428
429struct StrNCatOpt : public StrCatOpt {
Craig Topper3e4c6972014-03-05 09:10:37 +0000430 Value *callOptimizer(Function *Callee, CallInst *CI,
431 IRBuilder<> &B) override {
Meador Inge7fb2f732012-10-13 16:45:32 +0000432 // Verify the "strncat" function prototype.
433 FunctionType *FT = Callee->getFunctionType();
434 if (FT->getNumParams() != 3 ||
435 FT->getReturnType() != B.getInt8PtrTy() ||
436 FT->getParamType(0) != FT->getReturnType() ||
437 FT->getParamType(1) != FT->getReturnType() ||
438 !FT->getParamType(2)->isIntegerTy())
439 return 0;
440
441 // Extract some information from the instruction
442 Value *Dst = CI->getArgOperand(0);
443 Value *Src = CI->getArgOperand(1);
444 uint64_t Len;
445
446 // We don't do anything if length is not constant
447 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
448 Len = LengthArg->getZExtValue();
449 else
450 return 0;
451
452 // See if we can get the length of the input string.
453 uint64_t SrcLen = GetStringLength(Src);
454 if (SrcLen == 0) return 0;
455 --SrcLen; // Unbias length.
456
457 // Handle the simple, do-nothing cases:
458 // strncat(x, "", c) -> x
459 // strncat(x, c, 0) -> x
460 if (SrcLen == 0 || Len == 0) return Dst;
461
462 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000463 if (!DL) return 0;
Meador Inge7fb2f732012-10-13 16:45:32 +0000464
465 // We don't optimize this case
466 if (Len < SrcLen) return 0;
467
468 // strncat(x, s, c) -> strcat(x, s)
469 // s is constant so the strcat can be optimized further
470 return emitStrLenMemCpy(Src, Dst, SrcLen, B);
471 }
472};
473
Meador Inge17418502012-10-13 16:45:37 +0000474struct StrChrOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000475 Value *callOptimizer(Function *Callee, CallInst *CI,
476 IRBuilder<> &B) override {
Meador Inge17418502012-10-13 16:45:37 +0000477 // Verify the "strchr" function prototype.
478 FunctionType *FT = Callee->getFunctionType();
479 if (FT->getNumParams() != 2 ||
480 FT->getReturnType() != B.getInt8PtrTy() ||
481 FT->getParamType(0) != FT->getReturnType() ||
482 !FT->getParamType(1)->isIntegerTy(32))
483 return 0;
484
485 Value *SrcStr = CI->getArgOperand(0);
486
487 // If the second operand is non-constant, see if we can compute the length
488 // of the input string and turn this into memchr.
489 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
490 if (CharC == 0) {
491 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000492 if (!DL) return 0;
Meador Inge17418502012-10-13 16:45:37 +0000493
494 uint64_t Len = GetStringLength(SrcStr);
495 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
496 return 0;
497
498 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000499 ConstantInt::get(DL->getIntPtrType(*Context), Len),
500 B, DL, TLI);
Meador Inge17418502012-10-13 16:45:37 +0000501 }
502
503 // Otherwise, the character is a constant, see if the first argument is
504 // a string literal. If so, we can constant fold.
505 StringRef Str;
Kai Nackea56bb782014-02-04 05:55:16 +0000506 if (!getConstantStringInfo(SrcStr, Str)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000507 if (DL && CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
508 return B.CreateGEP(SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
Meador Inge17418502012-10-13 16:45:37 +0000509 return 0;
Kai Nackea56bb782014-02-04 05:55:16 +0000510 }
Meador Inge17418502012-10-13 16:45:37 +0000511
512 // Compute the offset, make sure to handle the case when we're searching for
513 // zero (a weird way to spell strlen).
Yunzhong Gao05efa232013-08-21 22:11:15 +0000514 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
Meador Inge17418502012-10-13 16:45:37 +0000515 Str.size() : Str.find(CharC->getSExtValue());
516 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
517 return Constant::getNullValue(CI->getType());
518
519 // strchr(s+n,c) -> gep(s+n+i,c)
520 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
521 }
522};
523
524struct StrRChrOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000525 Value *callOptimizer(Function *Callee, CallInst *CI,
526 IRBuilder<> &B) override {
Meador Inge17418502012-10-13 16:45:37 +0000527 // Verify the "strrchr" function prototype.
528 FunctionType *FT = Callee->getFunctionType();
529 if (FT->getNumParams() != 2 ||
530 FT->getReturnType() != B.getInt8PtrTy() ||
531 FT->getParamType(0) != FT->getReturnType() ||
532 !FT->getParamType(1)->isIntegerTy(32))
533 return 0;
534
535 Value *SrcStr = CI->getArgOperand(0);
536 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
537
538 // Cannot fold anything if we're not looking for a constant.
539 if (!CharC)
540 return 0;
541
542 StringRef Str;
543 if (!getConstantStringInfo(SrcStr, Str)) {
544 // strrchr(s, 0) -> strchr(s, 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000545 if (DL && CharC->isZero())
546 return EmitStrChr(SrcStr, '\0', B, DL, TLI);
Meador Inge17418502012-10-13 16:45:37 +0000547 return 0;
548 }
549
550 // Compute the offset.
Yunzhong Gao05efa232013-08-21 22:11:15 +0000551 size_t I = (0xFF & CharC->getSExtValue()) == 0 ?
Meador Inge17418502012-10-13 16:45:37 +0000552 Str.size() : Str.rfind(CharC->getSExtValue());
553 if (I == StringRef::npos) // Didn't find the char. Return null.
554 return Constant::getNullValue(CI->getType());
555
556 // strrchr(s+n,c) -> gep(s+n+i,c)
557 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
558 }
559};
560
Meador Inge40b6fac2012-10-15 03:47:37 +0000561struct StrCmpOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000562 Value *callOptimizer(Function *Callee, CallInst *CI,
563 IRBuilder<> &B) override {
Meador Inge40b6fac2012-10-15 03:47:37 +0000564 // Verify the "strcmp" function prototype.
565 FunctionType *FT = Callee->getFunctionType();
566 if (FT->getNumParams() != 2 ||
567 !FT->getReturnType()->isIntegerTy(32) ||
568 FT->getParamType(0) != FT->getParamType(1) ||
569 FT->getParamType(0) != B.getInt8PtrTy())
570 return 0;
571
572 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
573 if (Str1P == Str2P) // strcmp(x,x) -> 0
574 return ConstantInt::get(CI->getType(), 0);
575
576 StringRef Str1, Str2;
577 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
578 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
579
580 // strcmp(x, y) -> cnst (if both x and y are constant strings)
581 if (HasStr1 && HasStr2)
582 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
583
584 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
585 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
586 CI->getType()));
587
588 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
589 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
590
591 // strcmp(P, "x") -> memcmp(P, "x", 2)
592 uint64_t Len1 = GetStringLength(Str1P);
593 uint64_t Len2 = GetStringLength(Str2P);
594 if (Len1 && Len2) {
595 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000596 if (!DL) return 0;
Meador Inge40b6fac2012-10-15 03:47:37 +0000597
598 return EmitMemCmp(Str1P, Str2P,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000599 ConstantInt::get(DL->getIntPtrType(*Context),
600 std::min(Len1, Len2)), B, DL, TLI);
Meador Inge40b6fac2012-10-15 03:47:37 +0000601 }
602
603 return 0;
604 }
605};
606
607struct StrNCmpOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000608 Value *callOptimizer(Function *Callee, CallInst *CI,
609 IRBuilder<> &B) override {
Meador Inge40b6fac2012-10-15 03:47:37 +0000610 // Verify the "strncmp" function prototype.
611 FunctionType *FT = Callee->getFunctionType();
612 if (FT->getNumParams() != 3 ||
613 !FT->getReturnType()->isIntegerTy(32) ||
614 FT->getParamType(0) != FT->getParamType(1) ||
615 FT->getParamType(0) != B.getInt8PtrTy() ||
616 !FT->getParamType(2)->isIntegerTy())
617 return 0;
618
619 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
620 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
621 return ConstantInt::get(CI->getType(), 0);
622
623 // Get the length argument if it is constant.
624 uint64_t Length;
625 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
626 Length = LengthArg->getZExtValue();
627 else
628 return 0;
629
630 if (Length == 0) // strncmp(x,y,0) -> 0
631 return ConstantInt::get(CI->getType(), 0);
632
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000633 if (DL && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
634 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
Meador Inge40b6fac2012-10-15 03:47:37 +0000635
636 StringRef Str1, Str2;
637 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
638 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
639
640 // strncmp(x, y) -> cnst (if both x and y are constant strings)
641 if (HasStr1 && HasStr2) {
642 StringRef SubStr1 = Str1.substr(0, Length);
643 StringRef SubStr2 = Str2.substr(0, Length);
644 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
645 }
646
647 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
648 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
649 CI->getType()));
650
651 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
652 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
653
654 return 0;
655 }
656};
657
Meador Inge000dbcc2012-10-18 18:12:40 +0000658struct StrCpyOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000659 Value *callOptimizer(Function *Callee, CallInst *CI,
660 IRBuilder<> &B) override {
Meador Inge000dbcc2012-10-18 18:12:40 +0000661 // Verify the "strcpy" function prototype.
662 FunctionType *FT = Callee->getFunctionType();
663 if (FT->getNumParams() != 2 ||
664 FT->getReturnType() != FT->getParamType(0) ||
665 FT->getParamType(0) != FT->getParamType(1) ||
666 FT->getParamType(0) != B.getInt8PtrTy())
667 return 0;
668
669 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
670 if (Dst == Src) // strcpy(x,x) -> x
671 return Src;
672
673 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000674 if (!DL) return 0;
Meador Inge000dbcc2012-10-18 18:12:40 +0000675
676 // See if we can get the length of the input string.
677 uint64_t Len = GetStringLength(Src);
678 if (Len == 0) return 0;
679
680 // We have enough information to now generate the memcpy call to do the
681 // copy for us. Make a memcpy to copy the nul byte with align = 1.
682 B.CreateMemCpy(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000683 ConstantInt::get(DL->getIntPtrType(*Context), Len), 1);
Meador Inge000dbcc2012-10-18 18:12:40 +0000684 return Dst;
685 }
686};
687
Meador Inge9a6a1902012-10-31 00:20:56 +0000688struct StpCpyOpt: public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000689 Value *callOptimizer(Function *Callee, CallInst *CI,
690 IRBuilder<> &B) override {
Meador Inge9a6a1902012-10-31 00:20:56 +0000691 // Verify the "stpcpy" function prototype.
692 FunctionType *FT = Callee->getFunctionType();
693 if (FT->getNumParams() != 2 ||
694 FT->getReturnType() != FT->getParamType(0) ||
695 FT->getParamType(0) != FT->getParamType(1) ||
696 FT->getParamType(0) != B.getInt8PtrTy())
697 return 0;
698
699 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000700 if (!DL) return 0;
Meador Inge9a6a1902012-10-31 00:20:56 +0000701
702 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
703 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000704 Value *StrLen = EmitStrLen(Src, B, DL, TLI);
Meador Inge9a6a1902012-10-31 00:20:56 +0000705 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
706 }
707
708 // See if we can get the length of the input string.
709 uint64_t Len = GetStringLength(Src);
710 if (Len == 0) return 0;
711
712 Type *PT = FT->getParamType(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000713 Value *LenV = ConstantInt::get(DL->getIntPtrType(PT), Len);
Meador Inge9a6a1902012-10-31 00:20:56 +0000714 Value *DstEnd = B.CreateGEP(Dst,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000715 ConstantInt::get(DL->getIntPtrType(PT),
Meador Inge9a6a1902012-10-31 00:20:56 +0000716 Len - 1));
717
718 // We have enough information to now generate the memcpy call to do the
719 // copy for us. Make a memcpy to copy the nul byte with align = 1.
720 B.CreateMemCpy(Dst, Src, LenV, 1);
721 return DstEnd;
722 }
723};
724
Meador Inge067294b2012-10-31 03:33:00 +0000725struct StrNCpyOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000726 Value *callOptimizer(Function *Callee, CallInst *CI,
727 IRBuilder<> &B) override {
Meador Inge067294b2012-10-31 03:33:00 +0000728 FunctionType *FT = Callee->getFunctionType();
729 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
730 FT->getParamType(0) != FT->getParamType(1) ||
731 FT->getParamType(0) != B.getInt8PtrTy() ||
732 !FT->getParamType(2)->isIntegerTy())
733 return 0;
734
735 Value *Dst = CI->getArgOperand(0);
736 Value *Src = CI->getArgOperand(1);
737 Value *LenOp = CI->getArgOperand(2);
738
739 // See if we can get the length of the input string.
740 uint64_t SrcLen = GetStringLength(Src);
741 if (SrcLen == 0) return 0;
742 --SrcLen;
743
744 if (SrcLen == 0) {
745 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
746 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
747 return Dst;
748 }
749
750 uint64_t Len;
751 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
752 Len = LengthArg->getZExtValue();
753 else
754 return 0;
755
756 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
757
758 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000759 if (!DL) return 0;
Meador Inge067294b2012-10-31 03:33:00 +0000760
761 // Let strncpy handle the zero padding
762 if (Len > SrcLen+1) return 0;
763
764 Type *PT = FT->getParamType(0);
765 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
766 B.CreateMemCpy(Dst, Src,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000767 ConstantInt::get(DL->getIntPtrType(PT), Len), 1);
Meador Inge067294b2012-10-31 03:33:00 +0000768
769 return Dst;
770 }
771};
772
Meador Inged589ac62012-10-31 03:33:06 +0000773struct StrLenOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000774 bool ignoreCallingConv() override { return true; }
775 Value *callOptimizer(Function *Callee, CallInst *CI,
776 IRBuilder<> &B) override {
Meador Inged589ac62012-10-31 03:33:06 +0000777 FunctionType *FT = Callee->getFunctionType();
778 if (FT->getNumParams() != 1 ||
779 FT->getParamType(0) != B.getInt8PtrTy() ||
780 !FT->getReturnType()->isIntegerTy())
781 return 0;
782
783 Value *Src = CI->getArgOperand(0);
784
785 // Constant folding: strlen("xyz") -> 3
786 if (uint64_t Len = GetStringLength(Src))
787 return ConstantInt::get(CI->getType(), Len-1);
788
789 // strlen(x) != 0 --> *x != 0
790 // strlen(x) == 0 --> *x == 0
791 if (isOnlyUsedInZeroEqualityComparison(CI))
792 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
793 return 0;
794 }
795};
796
Meador Inge6f8e0112012-10-31 04:29:58 +0000797struct StrPBrkOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000798 Value *callOptimizer(Function *Callee, CallInst *CI,
799 IRBuilder<> &B) override {
Meador Inge6f8e0112012-10-31 04:29:58 +0000800 FunctionType *FT = Callee->getFunctionType();
801 if (FT->getNumParams() != 2 ||
802 FT->getParamType(0) != B.getInt8PtrTy() ||
803 FT->getParamType(1) != FT->getParamType(0) ||
804 FT->getReturnType() != FT->getParamType(0))
805 return 0;
806
807 StringRef S1, S2;
808 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
809 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
810
811 // strpbrk(s, "") -> NULL
812 // strpbrk("", s) -> NULL
813 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
814 return Constant::getNullValue(CI->getType());
815
816 // Constant folding.
817 if (HasS1 && HasS2) {
818 size_t I = S1.find_first_of(S2);
Matt Arsenaultf631f8c2013-09-10 00:41:53 +0000819 if (I == StringRef::npos) // No match.
Meador Inge6f8e0112012-10-31 04:29:58 +0000820 return Constant::getNullValue(CI->getType());
821
822 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
823 }
824
825 // strpbrk(s, "a") -> strchr(s, 'a')
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000826 if (DL && HasS2 && S2.size() == 1)
827 return EmitStrChr(CI->getArgOperand(0), S2[0], B, DL, TLI);
Meador Inge6f8e0112012-10-31 04:29:58 +0000828
829 return 0;
830 }
831};
832
Meador Inge05a625a2012-10-31 14:58:26 +0000833struct StrToOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000834 Value *callOptimizer(Function *Callee, CallInst *CI,
835 IRBuilder<> &B) override {
Meador Inge05a625a2012-10-31 14:58:26 +0000836 FunctionType *FT = Callee->getFunctionType();
837 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
838 !FT->getParamType(0)->isPointerTy() ||
839 !FT->getParamType(1)->isPointerTy())
840 return 0;
841
842 Value *EndPtr = CI->getArgOperand(1);
843 if (isa<ConstantPointerNull>(EndPtr)) {
844 // With a null EndPtr, this function won't capture the main argument.
845 // It would be readonly too, except that it still may write to errno.
Peter Collingbourne1b97a9c2013-03-02 01:20:18 +0000846 CI->addAttribute(1, Attribute::NoCapture);
Meador Inge05a625a2012-10-31 14:58:26 +0000847 }
848
849 return 0;
850 }
851};
852
Meador Inge489b5d62012-11-08 01:33:50 +0000853struct StrSpnOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000854 Value *callOptimizer(Function *Callee, CallInst *CI,
855 IRBuilder<> &B) override {
Meador Inge489b5d62012-11-08 01:33:50 +0000856 FunctionType *FT = Callee->getFunctionType();
857 if (FT->getNumParams() != 2 ||
858 FT->getParamType(0) != B.getInt8PtrTy() ||
859 FT->getParamType(1) != FT->getParamType(0) ||
860 !FT->getReturnType()->isIntegerTy())
861 return 0;
862
863 StringRef S1, S2;
864 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
865 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
866
867 // strspn(s, "") -> 0
868 // strspn("", s) -> 0
869 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
870 return Constant::getNullValue(CI->getType());
871
872 // Constant folding.
873 if (HasS1 && HasS2) {
874 size_t Pos = S1.find_first_not_of(S2);
875 if (Pos == StringRef::npos) Pos = S1.size();
876 return ConstantInt::get(CI->getType(), Pos);
877 }
878
879 return 0;
880 }
881};
882
Meador Ingebcd88ef72012-11-10 15:16:48 +0000883struct StrCSpnOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000884 Value *callOptimizer(Function *Callee, CallInst *CI,
885 IRBuilder<> &B) override {
Meador Ingebcd88ef72012-11-10 15:16:48 +0000886 FunctionType *FT = Callee->getFunctionType();
887 if (FT->getNumParams() != 2 ||
888 FT->getParamType(0) != B.getInt8PtrTy() ||
889 FT->getParamType(1) != FT->getParamType(0) ||
890 !FT->getReturnType()->isIntegerTy())
891 return 0;
892
893 StringRef S1, S2;
894 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
895 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
896
897 // strcspn("", s) -> 0
898 if (HasS1 && S1.empty())
899 return Constant::getNullValue(CI->getType());
900
901 // Constant folding.
902 if (HasS1 && HasS2) {
903 size_t Pos = S1.find_first_of(S2);
904 if (Pos == StringRef::npos) Pos = S1.size();
905 return ConstantInt::get(CI->getType(), Pos);
906 }
907
908 // strcspn(s, "") -> strlen(s)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000909 if (DL && HasS2 && S2.empty())
910 return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
Meador Ingebcd88ef72012-11-10 15:16:48 +0000911
912 return 0;
913 }
914};
915
Meador Inge56edbc92012-11-11 03:51:48 +0000916struct StrStrOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000917 Value *callOptimizer(Function *Callee, CallInst *CI,
918 IRBuilder<> &B) override {
Meador Inge56edbc92012-11-11 03:51:48 +0000919 FunctionType *FT = Callee->getFunctionType();
920 if (FT->getNumParams() != 2 ||
921 !FT->getParamType(0)->isPointerTy() ||
922 !FT->getParamType(1)->isPointerTy() ||
923 !FT->getReturnType()->isPointerTy())
924 return 0;
925
926 // fold strstr(x, x) -> x.
927 if (CI->getArgOperand(0) == CI->getArgOperand(1))
928 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
929
930 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000931 if (DL && isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
932 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000933 if (!StrLen)
934 return 0;
935 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000936 StrLen, B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000937 if (!StrNCmp)
938 return 0;
939 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
940 UI != UE; ) {
941 ICmpInst *Old = cast<ICmpInst>(*UI++);
942 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
943 ConstantInt::getNullValue(StrNCmp->getType()),
944 "cmp");
945 LCS->replaceAllUsesWith(Old, Cmp);
946 }
947 return CI;
948 }
949
950 // See if either input string is a constant string.
951 StringRef SearchStr, ToFindStr;
952 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
953 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
954
955 // fold strstr(x, "") -> x.
956 if (HasStr2 && ToFindStr.empty())
957 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
958
959 // If both strings are known, constant fold it.
960 if (HasStr1 && HasStr2) {
Matt Arsenaultf631f8c2013-09-10 00:41:53 +0000961 size_t Offset = SearchStr.find(ToFindStr);
Meador Inge56edbc92012-11-11 03:51:48 +0000962
963 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
964 return Constant::getNullValue(CI->getType());
965
966 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
967 Value *Result = CastToCStr(CI->getArgOperand(0), B);
968 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
969 return B.CreateBitCast(Result, CI->getType());
970 }
971
972 // fold strstr(x, "y") -> strchr(x, 'y').
973 if (HasStr2 && ToFindStr.size() == 1) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000974 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, DL, TLI);
Meador Inge56edbc92012-11-11 03:51:48 +0000975 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
976 }
977 return 0;
978 }
979};
980
Meador Inge4d2827c2012-11-11 05:11:20 +0000981struct MemCmpOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +0000982 Value *callOptimizer(Function *Callee, CallInst *CI,
983 IRBuilder<> &B) override {
Meador Inge4d2827c2012-11-11 05:11:20 +0000984 FunctionType *FT = Callee->getFunctionType();
985 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
986 !FT->getParamType(1)->isPointerTy() ||
987 !FT->getReturnType()->isIntegerTy(32))
988 return 0;
989
990 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
991
992 if (LHS == RHS) // memcmp(s,s,x) -> 0
993 return Constant::getNullValue(CI->getType());
994
995 // Make sure we have a constant length.
996 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
997 if (!LenC) return 0;
998 uint64_t Len = LenC->getZExtValue();
999
1000 if (Len == 0) // memcmp(s1,s2,0) -> 0
1001 return Constant::getNullValue(CI->getType());
1002
1003 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
1004 if (Len == 1) {
1005 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
1006 CI->getType(), "lhsv");
1007 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
1008 CI->getType(), "rhsv");
1009 return B.CreateSub(LHSV, RHSV, "chardiff");
1010 }
1011
1012 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1013 StringRef LHSStr, RHSStr;
1014 if (getConstantStringInfo(LHS, LHSStr) &&
1015 getConstantStringInfo(RHS, RHSStr)) {
1016 // Make sure we're not reading out-of-bounds memory.
1017 if (Len > LHSStr.size() || Len > RHSStr.size())
1018 return 0;
Meador Ingeb3e91f62012-11-12 14:00:45 +00001019 // Fold the memcmp and normalize the result. This way we get consistent
1020 // results across multiple platforms.
1021 uint64_t Ret = 0;
1022 int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
1023 if (Cmp < 0)
1024 Ret = -1;
1025 else if (Cmp > 0)
1026 Ret = 1;
Meador Inge4d2827c2012-11-11 05:11:20 +00001027 return ConstantInt::get(CI->getType(), Ret);
1028 }
1029
1030 return 0;
1031 }
1032};
1033
Meador Ingedd9234a2012-11-11 05:54:34 +00001034struct MemCpyOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001035 Value *callOptimizer(Function *Callee, CallInst *CI,
1036 IRBuilder<> &B) override {
Meador Ingedd9234a2012-11-11 05:54:34 +00001037 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001038 if (!DL) return 0;
Meador Ingedd9234a2012-11-11 05:54:34 +00001039
1040 FunctionType *FT = Callee->getFunctionType();
1041 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1042 !FT->getParamType(0)->isPointerTy() ||
1043 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001044 FT->getParamType(2) != DL->getIntPtrType(*Context))
Meador Ingedd9234a2012-11-11 05:54:34 +00001045 return 0;
1046
1047 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1048 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1049 CI->getArgOperand(2), 1);
1050 return CI->getArgOperand(0);
1051 }
1052};
1053
Meador Inge9cf328b2012-11-11 06:22:40 +00001054struct MemMoveOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001055 Value *callOptimizer(Function *Callee, CallInst *CI,
1056 IRBuilder<> &B) override {
Meador Inge9cf328b2012-11-11 06:22:40 +00001057 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001058 if (!DL) return 0;
Meador Inge9cf328b2012-11-11 06:22:40 +00001059
1060 FunctionType *FT = Callee->getFunctionType();
1061 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1062 !FT->getParamType(0)->isPointerTy() ||
1063 !FT->getParamType(1)->isPointerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001064 FT->getParamType(2) != DL->getIntPtrType(*Context))
Meador Inge9cf328b2012-11-11 06:22:40 +00001065 return 0;
1066
1067 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1068 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
1069 CI->getArgOperand(2), 1);
1070 return CI->getArgOperand(0);
1071 }
1072};
1073
Meador Inged4825782012-11-11 06:49:03 +00001074struct MemSetOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001075 Value *callOptimizer(Function *Callee, CallInst *CI,
1076 IRBuilder<> &B) override {
Meador Inged4825782012-11-11 06:49:03 +00001077 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001078 if (!DL) return 0;
Meador Inged4825782012-11-11 06:49:03 +00001079
1080 FunctionType *FT = Callee->getFunctionType();
1081 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1082 !FT->getParamType(0)->isPointerTy() ||
1083 !FT->getParamType(1)->isIntegerTy() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001084 FT->getParamType(2) != DL->getIntPtrType(FT->getParamType(0)))
Meador Inged4825782012-11-11 06:49:03 +00001085 return 0;
1086
1087 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1088 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
1089 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
1090 return CI->getArgOperand(0);
1091 }
1092};
1093
Meador Inge193e0352012-11-13 04:16:17 +00001094//===----------------------------------------------------------------------===//
1095// Math Library Optimizations
1096//===----------------------------------------------------------------------===//
1097
1098//===----------------------------------------------------------------------===//
1099// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1100
1101struct UnaryDoubleFPOpt : public LibCallOptimization {
1102 bool CheckRetType;
1103 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001104 Value *callOptimizer(Function *Callee, CallInst *CI,
1105 IRBuilder<> &B) override {
Meador Inge193e0352012-11-13 04:16:17 +00001106 FunctionType *FT = Callee->getFunctionType();
1107 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1108 !FT->getParamType(0)->isDoubleTy())
1109 return 0;
1110
1111 if (CheckRetType) {
1112 // Check if all the uses for function like 'sin' are converted to float.
1113 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1114 ++UseI) {
1115 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1116 if (Cast == 0 || !Cast->getType()->isFloatTy())
1117 return 0;
1118 }
1119 }
1120
1121 // If this is something like 'floor((double)floatval)', convert to floorf.
1122 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1123 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1124 return 0;
1125
1126 // floor((double)floatval) -> (double)floorf(floatval)
1127 Value *V = Cast->getOperand(0);
1128 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
1129 return B.CreateFPExt(V, B.getDoubleTy());
1130 }
1131};
1132
Yi Jiang6ab044e2013-12-16 22:42:40 +00001133// Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
1134struct BinaryDoubleFPOpt : public LibCallOptimization {
1135 bool CheckRetType;
1136 BinaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001137 Value *callOptimizer(Function *Callee, CallInst *CI,
1138 IRBuilder<> &B) override {
Yi Jiang6ab044e2013-12-16 22:42:40 +00001139 FunctionType *FT = Callee->getFunctionType();
1140 // Just make sure this has 2 arguments of the same FP type, which match the
1141 // result type.
1142 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1143 FT->getParamType(0) != FT->getParamType(1) ||
1144 !FT->getParamType(0)->isFloatingPointTy())
1145 return 0;
1146
1147 if (CheckRetType) {
1148 // Check if all the uses for function like 'fmin/fmax' are converted to
1149 // float.
1150 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
1151 ++UseI) {
1152 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
1153 if (Cast == 0 || !Cast->getType()->isFloatTy())
1154 return 0;
1155 }
1156 }
1157
1158 // If this is something like 'fmin((double)floatval1, (double)floatval2)',
1159 // we convert it to fminf.
1160 FPExtInst *Cast1 = dyn_cast<FPExtInst>(CI->getArgOperand(0));
1161 FPExtInst *Cast2 = dyn_cast<FPExtInst>(CI->getArgOperand(1));
1162 if (Cast1 == 0 || !Cast1->getOperand(0)->getType()->isFloatTy() ||
1163 Cast2 == 0 || !Cast2->getOperand(0)->getType()->isFloatTy())
1164 return 0;
1165
1166 // fmin((double)floatval1, (double)floatval2)
1167 // -> (double)fmin(floatval1, floatval2)
1168 Value *V = NULL;
1169 Value *V1 = Cast1->getOperand(0);
1170 Value *V2 = Cast2->getOperand(0);
1171 V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
1172 Callee->getAttributes());
1173 return B.CreateFPExt(V, B.getDoubleTy());
1174 }
1175};
1176
Meador Inge193e0352012-11-13 04:16:17 +00001177struct UnsafeFPLibCallOptimization : public LibCallOptimization {
1178 bool UnsafeFPShrink;
1179 UnsafeFPLibCallOptimization(bool UnsafeFPShrink) {
1180 this->UnsafeFPShrink = UnsafeFPShrink;
1181 }
1182};
1183
1184struct CosOpt : public UnsafeFPLibCallOptimization {
1185 CosOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001186 Value *callOptimizer(Function *Callee, CallInst *CI,
1187 IRBuilder<> &B) override {
Meador Inge193e0352012-11-13 04:16:17 +00001188 Value *Ret = NULL;
1189 if (UnsafeFPShrink && Callee->getName() == "cos" &&
1190 TLI->has(LibFunc::cosf)) {
1191 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1192 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1193 }
1194
1195 FunctionType *FT = Callee->getFunctionType();
1196 // Just make sure this has 1 argument of FP type, which matches the
1197 // result type.
1198 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1199 !FT->getParamType(0)->isFloatingPointTy())
1200 return Ret;
1201
1202 // cos(-x) -> cos(x)
1203 Value *Op1 = CI->getArgOperand(0);
1204 if (BinaryOperator::isFNeg(Op1)) {
1205 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
1206 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
1207 }
1208 return Ret;
1209 }
1210};
1211
1212struct PowOpt : public UnsafeFPLibCallOptimization {
1213 PowOpt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001214 Value *callOptimizer(Function *Callee, CallInst *CI,
1215 IRBuilder<> &B) override {
Meador Inge193e0352012-11-13 04:16:17 +00001216 Value *Ret = NULL;
1217 if (UnsafeFPShrink && Callee->getName() == "pow" &&
1218 TLI->has(LibFunc::powf)) {
1219 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1220 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1221 }
1222
1223 FunctionType *FT = Callee->getFunctionType();
1224 // Just make sure this has 2 arguments of the same FP type, which match the
1225 // result type.
1226 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1227 FT->getParamType(0) != FT->getParamType(1) ||
1228 !FT->getParamType(0)->isFloatingPointTy())
1229 return Ret;
1230
1231 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
1232 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001233 // pow(1.0, x) -> 1.0
1234 if (Op1C->isExactlyValue(1.0))
Meador Inge193e0352012-11-13 04:16:17 +00001235 return Op1C;
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001236 // pow(2.0, x) -> exp2(x)
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001237 if (Op1C->isExactlyValue(2.0) &&
1238 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
1239 LibFunc::exp2l))
Meador Inge193e0352012-11-13 04:16:17 +00001240 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Yi Jiangf92a5742013-12-12 01:55:04 +00001241 // pow(10.0, x) -> exp10(x)
1242 if (Op1C->isExactlyValue(10.0) &&
1243 hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
1244 LibFunc::exp10l))
1245 return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
1246 Callee->getAttributes());
Meador Inge193e0352012-11-13 04:16:17 +00001247 }
1248
1249 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1250 if (Op2C == 0) return Ret;
1251
1252 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1253 return ConstantFP::get(CI->getType(), 1.0);
1254
Michael Kuperstein4bb3f8f2013-08-19 06:55:47 +00001255 if (Op2C->isExactlyValue(0.5) &&
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001256 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
1257 LibFunc::sqrtl) &&
1258 hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
1259 LibFunc::fabsl)) {
Meador Inge193e0352012-11-13 04:16:17 +00001260 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1261 // This is faster than calling pow, and still handles negative zero
1262 // and negative infinity correctly.
1263 // TODO: In fast-math mode, this could be just sqrt(x).
1264 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1265 Value *Inf = ConstantFP::getInfinity(CI->getType());
1266 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1267 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1268 Callee->getAttributes());
1269 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1270 Callee->getAttributes());
1271 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
1272 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
1273 return Sel;
1274 }
1275
1276 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1277 return Op1;
1278 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1279 return B.CreateFMul(Op1, Op1, "pow2");
1280 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1281 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1282 Op1, "powrecip");
1283 return 0;
1284 }
1285};
1286
1287struct Exp2Opt : public UnsafeFPLibCallOptimization {
1288 Exp2Opt(bool UnsafeFPShrink) : UnsafeFPLibCallOptimization(UnsafeFPShrink) {}
Craig Topper3e4c6972014-03-05 09:10:37 +00001289 Value *callOptimizer(Function *Callee, CallInst *CI,
1290 IRBuilder<> &B) override {
Meador Inge193e0352012-11-13 04:16:17 +00001291 Value *Ret = NULL;
1292 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
Benjamin Kramer2702caa2013-08-31 18:19:35 +00001293 TLI->has(LibFunc::exp2f)) {
Meador Inge193e0352012-11-13 04:16:17 +00001294 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
1295 Ret = UnsafeUnaryDoubleFP.callOptimizer(Callee, CI, B);
1296 }
1297
1298 FunctionType *FT = Callee->getFunctionType();
1299 // Just make sure this has 1 argument of FP type, which matches the
1300 // result type.
1301 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1302 !FT->getParamType(0)->isFloatingPointTy())
1303 return Ret;
1304
1305 Value *Op = CI->getArgOperand(0);
1306 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1307 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001308 LibFunc::Func LdExp = LibFunc::ldexpl;
1309 if (Op->getType()->isFloatTy())
1310 LdExp = LibFunc::ldexpf;
1311 else if (Op->getType()->isDoubleTy())
1312 LdExp = LibFunc::ldexp;
Meador Inge193e0352012-11-13 04:16:17 +00001313
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001314 if (TLI->has(LdExp)) {
1315 Value *LdExpArg = 0;
1316 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1317 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1318 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
1319 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1320 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1321 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
1322 }
Meador Inge193e0352012-11-13 04:16:17 +00001323
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001324 if (LdExpArg) {
1325 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1326 if (!Op->getType()->isFloatTy())
1327 One = ConstantExpr::getFPExtend(One, Op->getType());
Meador Inge193e0352012-11-13 04:16:17 +00001328
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001329 Module *M = Caller->getParent();
1330 Value *Callee =
1331 M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
1332 Op->getType(), B.getInt32Ty(), NULL);
1333 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1334 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1335 CI->setCallingConv(F->getCallingConv());
Meador Inge193e0352012-11-13 04:16:17 +00001336
Benjamin Kramer34f460e2014-02-04 20:27:23 +00001337 return CI;
1338 }
Meador Inge193e0352012-11-13 04:16:17 +00001339 }
1340 return Ret;
1341 }
1342};
1343
Bob Wilsond8d92d92013-11-03 06:48:38 +00001344struct SinCosPiOpt : public LibCallOptimization {
1345 SinCosPiOpt() {}
1346
Craig Topper3e4c6972014-03-05 09:10:37 +00001347 Value *callOptimizer(Function *Callee, CallInst *CI,
1348 IRBuilder<> &B) override {
Bob Wilsond8d92d92013-11-03 06:48:38 +00001349 // Make sure the prototype is as expected, otherwise the rest of the
1350 // function is probably invalid and likely to abort.
1351 if (!isTrigLibCall(CI))
1352 return 0;
1353
1354 Value *Arg = CI->getArgOperand(0);
1355 SmallVector<CallInst *, 1> SinCalls;
1356 SmallVector<CallInst *, 1> CosCalls;
1357 SmallVector<CallInst *, 1> SinCosCalls;
1358
1359 bool IsFloat = Arg->getType()->isFloatTy();
1360
1361 // Look for all compatible sinpi, cospi and sincospi calls with the same
1362 // argument. If there are enough (in some sense) we can make the
1363 // substitution.
1364 for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
1365 UI != UE; ++UI)
1366 classifyArgUse(*UI, CI->getParent(), IsFloat, SinCalls, CosCalls,
1367 SinCosCalls);
1368
1369 // It's only worthwhile if both sinpi and cospi are actually used.
1370 if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
1371 return 0;
1372
1373 Value *Sin, *Cos, *SinCos;
1374 insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos,
1375 SinCos);
1376
1377 replaceTrigInsts(SinCalls, Sin);
1378 replaceTrigInsts(CosCalls, Cos);
1379 replaceTrigInsts(SinCosCalls, SinCos);
1380
1381 return 0;
1382 }
1383
1384 bool isTrigLibCall(CallInst *CI) {
1385 Function *Callee = CI->getCalledFunction();
1386 FunctionType *FT = Callee->getFunctionType();
1387
1388 // We can only hope to do anything useful if we can ignore things like errno
1389 // and floating-point exceptions.
1390 bool AttributesSafe = CI->hasFnAttr(Attribute::NoUnwind) &&
1391 CI->hasFnAttr(Attribute::ReadNone);
1392
1393 // Other than that we need float(float) or double(double)
1394 return AttributesSafe && FT->getNumParams() == 1 &&
1395 FT->getReturnType() == FT->getParamType(0) &&
1396 (FT->getParamType(0)->isFloatTy() ||
1397 FT->getParamType(0)->isDoubleTy());
1398 }
1399
1400 void classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
1401 SmallVectorImpl<CallInst *> &SinCalls,
1402 SmallVectorImpl<CallInst *> &CosCalls,
1403 SmallVectorImpl<CallInst *> &SinCosCalls) {
1404 CallInst *CI = dyn_cast<CallInst>(Val);
1405
1406 if (!CI)
1407 return;
1408
1409 Function *Callee = CI->getCalledFunction();
1410 StringRef FuncName = Callee->getName();
1411 LibFunc::Func Func;
1412 if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) ||
1413 !isTrigLibCall(CI))
1414 return;
1415
1416 if (IsFloat) {
1417 if (Func == LibFunc::sinpif)
1418 SinCalls.push_back(CI);
1419 else if (Func == LibFunc::cospif)
1420 CosCalls.push_back(CI);
Tim Northover103e6482014-02-04 16:28:20 +00001421 else if (Func == LibFunc::sincospif_stret)
Bob Wilsond8d92d92013-11-03 06:48:38 +00001422 SinCosCalls.push_back(CI);
1423 } else {
1424 if (Func == LibFunc::sinpi)
1425 SinCalls.push_back(CI);
1426 else if (Func == LibFunc::cospi)
1427 CosCalls.push_back(CI);
1428 else if (Func == LibFunc::sincospi_stret)
1429 SinCosCalls.push_back(CI);
1430 }
1431 }
1432
1433 void replaceTrigInsts(SmallVectorImpl<CallInst*> &Calls, Value *Res) {
1434 for (SmallVectorImpl<CallInst*>::iterator I = Calls.begin(),
1435 E = Calls.end();
1436 I != E; ++I) {
1437 LCS->replaceAllUsesWith(*I, Res);
1438 }
1439 }
1440
1441 void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
1442 bool UseFloat, Value *&Sin, Value *&Cos,
1443 Value *&SinCos) {
1444 Type *ArgTy = Arg->getType();
1445 Type *ResTy;
1446 StringRef Name;
1447
1448 Triple T(OrigCallee->getParent()->getTargetTriple());
1449 if (UseFloat) {
Tim Northover103e6482014-02-04 16:28:20 +00001450 Name = "__sincospif_stret";
Bob Wilsond8d92d92013-11-03 06:48:38 +00001451
1452 assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
1453 // x86_64 can't use {float, float} since that would be returned in both
1454 // xmm0 and xmm1, which isn't what a real struct would do.
1455 ResTy = T.getArch() == Triple::x86_64
1456 ? static_cast<Type *>(VectorType::get(ArgTy, 2))
1457 : static_cast<Type *>(StructType::get(ArgTy, ArgTy, NULL));
1458 } else {
1459 Name = "__sincospi_stret";
1460 ResTy = StructType::get(ArgTy, ArgTy, NULL);
1461 }
1462
1463 Module *M = OrigCallee->getParent();
1464 Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
1465 ResTy, ArgTy, NULL);
1466
1467 if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1468 // If the argument is an instruction, it must dominate all uses so put our
1469 // sincos call there.
1470 BasicBlock::iterator Loc = ArgInst;
1471 B.SetInsertPoint(ArgInst->getParent(), ++Loc);
1472 } else {
1473 // Otherwise (e.g. for a constant) the beginning of the function is as
1474 // good a place as any.
1475 BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
1476 B.SetInsertPoint(&EntryBB, EntryBB.begin());
1477 }
1478
1479 SinCos = B.CreateCall(Callee, Arg, "sincospi");
1480
1481 if (SinCos->getType()->isStructTy()) {
1482 Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
1483 Cos = B.CreateExtractValue(SinCos, 1, "cospi");
1484 } else {
1485 Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
1486 "sinpi");
1487 Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
1488 "cospi");
1489 }
1490 }
1491
1492};
1493
Meador Inge7415f842012-11-25 20:45:27 +00001494//===----------------------------------------------------------------------===//
1495// Integer Library Call Optimizations
1496//===----------------------------------------------------------------------===//
1497
1498struct FFSOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001499 Value *callOptimizer(Function *Callee, CallInst *CI,
1500 IRBuilder<> &B) override {
Meador Inge7415f842012-11-25 20:45:27 +00001501 FunctionType *FT = Callee->getFunctionType();
1502 // Just make sure this has 2 arguments of the same FP type, which match the
1503 // result type.
1504 if (FT->getNumParams() != 1 ||
1505 !FT->getReturnType()->isIntegerTy(32) ||
1506 !FT->getParamType(0)->isIntegerTy())
1507 return 0;
1508
1509 Value *Op = CI->getArgOperand(0);
1510
1511 // Constant fold.
1512 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1513 if (CI->isZero()) // ffs(0) -> 0.
1514 return B.getInt32(0);
1515 // ffs(c) -> cttz(c)+1
1516 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
1517 }
1518
1519 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1520 Type *ArgType = Op->getType();
1521 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1522 Intrinsic::cttz, ArgType);
1523 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
1524 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1525 V = B.CreateIntCast(V, B.getInt32Ty(), false);
1526
1527 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
1528 return B.CreateSelect(Cond, V, B.getInt32(0));
1529 }
1530};
1531
Meador Ingea0b6d872012-11-26 00:24:07 +00001532struct AbsOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001533 bool ignoreCallingConv() override { return true; }
1534 Value *callOptimizer(Function *Callee, CallInst *CI,
1535 IRBuilder<> &B) override {
Meador Ingea0b6d872012-11-26 00:24:07 +00001536 FunctionType *FT = Callee->getFunctionType();
1537 // We require integer(integer) where the types agree.
1538 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1539 FT->getParamType(0) != FT->getReturnType())
1540 return 0;
1541
1542 // abs(x) -> x >s -1 ? x : -x
1543 Value *Op = CI->getArgOperand(0);
1544 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
1545 "ispos");
1546 Value *Neg = B.CreateNeg(Op, "neg");
1547 return B.CreateSelect(Pos, Op, Neg);
1548 }
1549};
1550
Meador Inge9a59ab62012-11-26 02:31:59 +00001551struct IsDigitOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001552 Value *callOptimizer(Function *Callee, CallInst *CI,
1553 IRBuilder<> &B) override {
Meador Inge9a59ab62012-11-26 02:31:59 +00001554 FunctionType *FT = Callee->getFunctionType();
1555 // We require integer(i32)
1556 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1557 !FT->getParamType(0)->isIntegerTy(32))
1558 return 0;
1559
1560 // isdigit(c) -> (c-'0') <u 10
1561 Value *Op = CI->getArgOperand(0);
1562 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1563 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
1564 return B.CreateZExt(Op, CI->getType());
1565 }
1566};
1567
Meador Ingea62a39e2012-11-26 03:10:07 +00001568struct IsAsciiOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001569 Value *callOptimizer(Function *Callee, CallInst *CI,
1570 IRBuilder<> &B) override {
Meador Ingea62a39e2012-11-26 03:10:07 +00001571 FunctionType *FT = Callee->getFunctionType();
1572 // We require integer(i32)
1573 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1574 !FT->getParamType(0)->isIntegerTy(32))
1575 return 0;
1576
1577 // isascii(c) -> c <u 128
1578 Value *Op = CI->getArgOperand(0);
1579 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
1580 return B.CreateZExt(Op, CI->getType());
1581 }
1582};
1583
Meador Inge604937d2012-11-26 03:38:52 +00001584struct ToAsciiOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001585 Value *callOptimizer(Function *Callee, CallInst *CI,
1586 IRBuilder<> &B) override {
Meador Inge604937d2012-11-26 03:38:52 +00001587 FunctionType *FT = Callee->getFunctionType();
1588 // We require i32(i32)
1589 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1590 !FT->getParamType(0)->isIntegerTy(32))
1591 return 0;
1592
Meador Ingeefe23932012-11-26 20:37:23 +00001593 // toascii(c) -> c & 0x7f
Meador Inge604937d2012-11-26 03:38:52 +00001594 return B.CreateAnd(CI->getArgOperand(0),
1595 ConstantInt::get(CI->getType(),0x7F));
1596 }
1597};
1598
Meador Inge08ca1152012-11-26 20:37:20 +00001599//===----------------------------------------------------------------------===//
1600// Formatting and IO Library Call Optimizations
1601//===----------------------------------------------------------------------===//
1602
Hal Finkel66cd3f12013-11-17 02:06:35 +00001603struct ErrorReportingOpt : public LibCallOptimization {
1604 ErrorReportingOpt(int S = -1) : StreamArg(S) {}
1605
Craig Topper3e4c6972014-03-05 09:10:37 +00001606 Value *callOptimizer(Function *Callee, CallInst *CI,
1607 IRBuilder<> &) override {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001608 // Error reporting calls should be cold, mark them as such.
1609 // This applies even to non-builtin calls: it is only a hint and applies to
1610 // functions that the frontend might not understand as builtins.
1611
1612 // This heuristic was suggested in:
1613 // Improving Static Branch Prediction in a Compiler
1614 // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
1615 // Proceedings of PACT'98, Oct. 1998, IEEE
1616
1617 if (!CI->hasFnAttr(Attribute::Cold) && isReportingError(Callee, CI)) {
1618 CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
1619 }
1620
1621 return 0;
1622 }
1623
1624protected:
1625 bool isReportingError(Function *Callee, CallInst *CI) {
1626 if (!ColdErrorCalls)
1627 return false;
1628
1629 if (!Callee || !Callee->isDeclaration())
1630 return false;
1631
1632 if (StreamArg < 0)
1633 return true;
1634
1635 // These functions might be considered cold, but only if their stream
1636 // argument is stderr.
1637
1638 if (StreamArg >= (int) CI->getNumArgOperands())
1639 return false;
1640 LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
1641 if (!LI)
1642 return false;
1643 GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
1644 if (!GV || !GV->isDeclaration())
1645 return false;
1646 return GV->getName() == "stderr";
1647 }
1648
1649 int StreamArg;
1650};
1651
Meador Inge08ca1152012-11-26 20:37:20 +00001652struct PrintFOpt : public LibCallOptimization {
1653 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1654 IRBuilder<> &B) {
1655 // Check for a fixed format string.
1656 StringRef FormatStr;
1657 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
1658 return 0;
1659
1660 // Empty format string -> noop.
1661 if (FormatStr.empty()) // Tolerate printf's declared void.
1662 return CI->use_empty() ? (Value*)CI :
1663 ConstantInt::get(CI->getType(), 0);
1664
1665 // Do not do any of the following transformations if the printf return value
1666 // is used, in general the printf return value is not compatible with either
1667 // putchar() or puts().
1668 if (!CI->use_empty())
1669 return 0;
1670
1671 // printf("x") -> putchar('x'), even for '%'.
1672 if (FormatStr.size() == 1) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001673 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001674 if (CI->use_empty() || !Res) return Res;
1675 return B.CreateIntCast(Res, CI->getType(), true);
1676 }
1677
1678 // printf("foo\n") --> puts("foo")
1679 if (FormatStr[FormatStr.size()-1] == '\n' &&
Matt Arsenaultf631f8c2013-09-10 00:41:53 +00001680 FormatStr.find('%') == StringRef::npos) { // No format characters.
Meador Inge08ca1152012-11-26 20:37:20 +00001681 // Create a string literal with no \n on it. We expect the constant merge
1682 // pass to be run after this pass, to merge duplicate strings.
1683 FormatStr = FormatStr.drop_back();
1684 Value *GV = B.CreateGlobalString(FormatStr, "str");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001685 Value *NewCI = EmitPutS(GV, B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001686 return (CI->use_empty() || !NewCI) ?
1687 NewCI :
1688 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1689 }
1690
1691 // Optimize specific format strings.
1692 // printf("%c", chr) --> putchar(chr)
1693 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
1694 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001695 Value *Res = EmitPutChar(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001696
1697 if (CI->use_empty() || !Res) return Res;
1698 return B.CreateIntCast(Res, CI->getType(), true);
1699 }
1700
1701 // printf("%s\n", str) --> puts(str)
1702 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
1703 CI->getArgOperand(1)->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001704 return EmitPutS(CI->getArgOperand(1), B, DL, TLI);
Meador Inge08ca1152012-11-26 20:37:20 +00001705 }
1706 return 0;
1707 }
1708
Craig Topper3e4c6972014-03-05 09:10:37 +00001709 Value *callOptimizer(Function *Callee, CallInst *CI,
1710 IRBuilder<> &B) override {
Meador Inge08ca1152012-11-26 20:37:20 +00001711 // Require one fixed pointer argument and an integer/void result.
1712 FunctionType *FT = Callee->getFunctionType();
1713 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1714 !(FT->getReturnType()->isIntegerTy() ||
1715 FT->getReturnType()->isVoidTy()))
1716 return 0;
1717
1718 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1719 return V;
1720 }
1721
1722 // printf(format, ...) -> iprintf(format, ...) if no floating point
1723 // arguments.
1724 if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
1725 Module *M = B.GetInsertBlock()->getParent()->getParent();
1726 Constant *IPrintFFn =
1727 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1728 CallInst *New = cast<CallInst>(CI->clone());
1729 New->setCalledFunction(IPrintFFn);
1730 B.Insert(New);
1731 return New;
1732 }
1733 return 0;
1734 }
1735};
1736
Meador Inge25c9b3b2012-11-27 05:57:54 +00001737struct SPrintFOpt : public LibCallOptimization {
1738 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1739 IRBuilder<> &B) {
1740 // Check for a fixed format string.
1741 StringRef FormatStr;
1742 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1743 return 0;
1744
1745 // If we just have a format string (nothing else crazy) transform it.
1746 if (CI->getNumArgOperands() == 2) {
1747 // Make sure there's no % in the constant array. We could try to handle
1748 // %% -> % in the future if we cared.
1749 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1750 if (FormatStr[i] == '%')
1751 return 0; // we found a format specifier, bail out.
1752
1753 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001754 if (!DL) return 0;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001755
1756 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1757 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001758 ConstantInt::get(DL->getIntPtrType(*Context), // Copy the
Meador Inge25c9b3b2012-11-27 05:57:54 +00001759 FormatStr.size() + 1), 1); // nul byte.
1760 return ConstantInt::get(CI->getType(), FormatStr.size());
1761 }
1762
1763 // The remaining optimizations require the format string to be "%s" or "%c"
1764 // and have an extra operand.
1765 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1766 CI->getNumArgOperands() < 3)
1767 return 0;
1768
1769 // Decode the second character of the format string.
1770 if (FormatStr[1] == 'c') {
1771 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1772 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1773 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
1774 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
1775 B.CreateStore(V, Ptr);
1776 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1777 B.CreateStore(B.getInt8(0), Ptr);
1778
1779 return ConstantInt::get(CI->getType(), 1);
1780 }
1781
1782 if (FormatStr[1] == 's') {
1783 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001784 if (!DL) return 0;
Meador Inge25c9b3b2012-11-27 05:57:54 +00001785
1786 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1787 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
1788
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001789 Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
Meador Inge25c9b3b2012-11-27 05:57:54 +00001790 if (!Len)
1791 return 0;
1792 Value *IncLen = B.CreateAdd(Len,
1793 ConstantInt::get(Len->getType(), 1),
1794 "leninc");
1795 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
1796
1797 // The sprintf result is the unincremented number of bytes in the string.
1798 return B.CreateIntCast(Len, CI->getType(), false);
1799 }
1800 return 0;
1801 }
1802
Craig Topper3e4c6972014-03-05 09:10:37 +00001803 Value *callOptimizer(Function *Callee, CallInst *CI,
1804 IRBuilder<> &B) override {
Meador Inge25c9b3b2012-11-27 05:57:54 +00001805 // Require two fixed pointer arguments and an integer result.
1806 FunctionType *FT = Callee->getFunctionType();
1807 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1808 !FT->getParamType(1)->isPointerTy() ||
1809 !FT->getReturnType()->isIntegerTy())
1810 return 0;
1811
1812 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1813 return V;
1814 }
1815
1816 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
1817 // point arguments.
1818 if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
1819 Module *M = B.GetInsertBlock()->getParent()->getParent();
1820 Constant *SIPrintFFn =
1821 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1822 CallInst *New = cast<CallInst>(CI->clone());
1823 New->setCalledFunction(SIPrintFFn);
1824 B.Insert(New);
1825 return New;
1826 }
1827 return 0;
1828 }
1829};
1830
Meador Inge1009cec2012-11-29 15:45:33 +00001831struct FPrintFOpt : public LibCallOptimization {
1832 Value *optimizeFixedFormatString(Function *Callee, CallInst *CI,
1833 IRBuilder<> &B) {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001834 ErrorReportingOpt ER(/* StreamArg = */ 0);
1835 (void) ER.callOptimizer(Callee, CI, B);
1836
Meador Inge1009cec2012-11-29 15:45:33 +00001837 // All the optimizations depend on the format string.
1838 StringRef FormatStr;
1839 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
1840 return 0;
1841
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001842 // Do not do any of the following transformations if the fprintf return
1843 // value is used, in general the fprintf return value is not compatible
1844 // with fwrite(), fputc() or fputs().
1845 if (!CI->use_empty())
1846 return 0;
1847
Meador Inge1009cec2012-11-29 15:45:33 +00001848 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1849 if (CI->getNumArgOperands() == 2) {
1850 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1851 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1852 return 0; // We found a format specifier.
1853
1854 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001855 if (!DL) return 0;
Meador Inge1009cec2012-11-29 15:45:33 +00001856
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001857 return EmitFWrite(CI->getArgOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001858 ConstantInt::get(DL->getIntPtrType(*Context),
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001859 FormatStr.size()),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001860 CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001861 }
1862
1863 // The remaining optimizations require the format string to be "%s" or "%c"
1864 // and have an extra operand.
1865 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1866 CI->getNumArgOperands() < 3)
1867 return 0;
1868
1869 // Decode the second character of the format string.
1870 if (FormatStr[1] == 'c') {
1871 // fprintf(F, "%c", chr) --> fputc(chr, F)
1872 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001873 return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001874 }
1875
1876 if (FormatStr[1] == 's') {
1877 // fprintf(F, "%s", str) --> fputs(str, F)
Peter Collingbourne37ae72b2013-04-17 02:01:10 +00001878 if (!CI->getArgOperand(2)->getType()->isPointerTy())
Meador Inge1009cec2012-11-29 15:45:33 +00001879 return 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001880 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, DL, TLI);
Meador Inge1009cec2012-11-29 15:45:33 +00001881 }
1882 return 0;
1883 }
1884
Craig Topper3e4c6972014-03-05 09:10:37 +00001885 Value *callOptimizer(Function *Callee, CallInst *CI,
1886 IRBuilder<> &B) override {
Meador Inge1009cec2012-11-29 15:45:33 +00001887 // Require two fixed paramters as pointers and integer result.
1888 FunctionType *FT = Callee->getFunctionType();
1889 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1890 !FT->getParamType(1)->isPointerTy() ||
1891 !FT->getReturnType()->isIntegerTy())
1892 return 0;
1893
1894 if (Value *V = optimizeFixedFormatString(Callee, CI, B)) {
1895 return V;
1896 }
1897
1898 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1899 // floating point arguments.
1900 if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
1901 Module *M = B.GetInsertBlock()->getParent()->getParent();
1902 Constant *FIPrintFFn =
1903 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1904 CallInst *New = cast<CallInst>(CI->clone());
1905 New->setCalledFunction(FIPrintFFn);
1906 B.Insert(New);
1907 return New;
1908 }
1909 return 0;
1910 }
1911};
1912
Meador Ingebc84d1a2012-11-29 15:45:39 +00001913struct FWriteOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001914 Value *callOptimizer(Function *Callee, CallInst *CI,
1915 IRBuilder<> &B) override {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001916 ErrorReportingOpt ER(/* StreamArg = */ 3);
1917 (void) ER.callOptimizer(Callee, CI, B);
1918
Meador Ingebc84d1a2012-11-29 15:45:39 +00001919 // Require a pointer, an integer, an integer, a pointer, returning integer.
1920 FunctionType *FT = Callee->getFunctionType();
1921 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1922 !FT->getParamType(1)->isIntegerTy() ||
1923 !FT->getParamType(2)->isIntegerTy() ||
1924 !FT->getParamType(3)->isPointerTy() ||
1925 !FT->getReturnType()->isIntegerTy())
1926 return 0;
1927
1928 // Get the element size and count.
1929 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1930 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
1931 if (!SizeC || !CountC) return 0;
1932 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1933
1934 // If this is writing zero records, remove the call (it's a noop).
1935 if (Bytes == 0)
1936 return ConstantInt::get(CI->getType(), 0);
1937
1938 // If this is writing one byte, turn it into fputc.
1939 // This optimisation is only valid, if the return value is unused.
1940 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1941 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001942 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, DL, TLI);
Meador Ingebc84d1a2012-11-29 15:45:39 +00001943 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
1944 }
1945
1946 return 0;
1947 }
1948};
1949
Meador Ingef8e72502012-11-29 15:45:43 +00001950struct FPutsOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001951 Value *callOptimizer(Function *Callee, CallInst *CI,
1952 IRBuilder<> &B) override {
Hal Finkel66cd3f12013-11-17 02:06:35 +00001953 ErrorReportingOpt ER(/* StreamArg = */ 1);
1954 (void) ER.callOptimizer(Callee, CI, B);
1955
Meador Ingef8e72502012-11-29 15:45:43 +00001956 // These optimizations require DataLayout.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001957 if (!DL) return 0;
Meador Ingef8e72502012-11-29 15:45:43 +00001958
1959 // Require two pointers. Also, we can't optimize if return value is used.
1960 FunctionType *FT = Callee->getFunctionType();
1961 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1962 !FT->getParamType(1)->isPointerTy() ||
1963 !CI->use_empty())
1964 return 0;
1965
1966 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1967 uint64_t Len = GetStringLength(CI->getArgOperand(0));
1968 if (!Len) return 0;
1969 // Known to have no uses (see above).
1970 return EmitFWrite(CI->getArgOperand(0),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001971 ConstantInt::get(DL->getIntPtrType(*Context), Len-1),
1972 CI->getArgOperand(1), B, DL, TLI);
Meador Ingef8e72502012-11-29 15:45:43 +00001973 }
1974};
1975
Meador Inge75798bb2012-11-29 19:15:17 +00001976struct PutsOpt : public LibCallOptimization {
Craig Topper3e4c6972014-03-05 09:10:37 +00001977 Value *callOptimizer(Function *Callee, CallInst *CI,
1978 IRBuilder<> &B) override {
Meador Inge75798bb2012-11-29 19:15:17 +00001979 // Require one fixed pointer argument and an integer/void result.
1980 FunctionType *FT = Callee->getFunctionType();
1981 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1982 !(FT->getReturnType()->isIntegerTy() ||
1983 FT->getReturnType()->isVoidTy()))
1984 return 0;
1985
1986 // Check for a constant string.
1987 StringRef Str;
1988 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
1989 return 0;
1990
1991 if (Str.empty() && CI->use_empty()) {
1992 // puts("") -> putchar('\n')
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001993 Value *Res = EmitPutChar(B.getInt32('\n'), B, DL, TLI);
Meador Inge75798bb2012-11-29 19:15:17 +00001994 if (CI->use_empty() || !Res) return Res;
1995 return B.CreateIntCast(Res, CI->getType(), true);
1996 }
1997
1998 return 0;
1999 }
2000};
2001
Meador Ingedf796f82012-10-13 16:45:24 +00002002} // End anonymous namespace.
2003
2004namespace llvm {
2005
2006class LibCallSimplifierImpl {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002007 const DataLayout *DL;
Meador Ingedf796f82012-10-13 16:45:24 +00002008 const TargetLibraryInfo *TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +00002009 const LibCallSimplifier *LCS;
Meador Inge193e0352012-11-13 04:16:17 +00002010 bool UnsafeFPShrink;
Meador Inge4d2827c2012-11-11 05:11:20 +00002011
Meador Inge193e0352012-11-13 04:16:17 +00002012 // Math library call optimizations.
Meador Inge20255ef2013-03-12 00:08:29 +00002013 CosOpt Cos;
2014 PowOpt Pow;
2015 Exp2Opt Exp2;
Meador Ingedf796f82012-10-13 16:45:24 +00002016public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002017 LibCallSimplifierImpl(const DataLayout *DL, const TargetLibraryInfo *TLI,
Meador Inge193e0352012-11-13 04:16:17 +00002018 const LibCallSimplifier *LCS,
2019 bool UnsafeFPShrink = false)
Meador Inge20255ef2013-03-12 00:08:29 +00002020 : Cos(UnsafeFPShrink), Pow(UnsafeFPShrink), Exp2(UnsafeFPShrink) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002021 this->DL = DL;
Meador Ingedf796f82012-10-13 16:45:24 +00002022 this->TLI = TLI;
Meador Inge76fc1a42012-11-11 03:51:43 +00002023 this->LCS = LCS;
Meador Inge193e0352012-11-13 04:16:17 +00002024 this->UnsafeFPShrink = UnsafeFPShrink;
Meador Ingedf796f82012-10-13 16:45:24 +00002025 }
2026
2027 Value *optimizeCall(CallInst *CI);
Meador Inge20255ef2013-03-12 00:08:29 +00002028 LibCallOptimization *lookupOptimization(CallInst *CI);
2029 bool hasFloatVersion(StringRef FuncName);
Meador Ingedf796f82012-10-13 16:45:24 +00002030};
2031
Meador Inge20255ef2013-03-12 00:08:29 +00002032bool LibCallSimplifierImpl::hasFloatVersion(StringRef FuncName) {
2033 LibFunc::Func Func;
2034 SmallString<20> FloatFuncName = FuncName;
2035 FloatFuncName += 'f';
2036 if (TLI->getLibFunc(FloatFuncName, Func))
2037 return TLI->has(Func);
2038 return false;
2039}
Meador Inge7fb2f732012-10-13 16:45:32 +00002040
Meador Inge20255ef2013-03-12 00:08:29 +00002041// Fortified library call optimizations.
2042static MemCpyChkOpt MemCpyChk;
2043static MemMoveChkOpt MemMoveChk;
2044static MemSetChkOpt MemSetChk;
2045static StrCpyChkOpt StrCpyChk;
2046static StpCpyChkOpt StpCpyChk;
2047static StrNCpyChkOpt StrNCpyChk;
Meador Inge4d2827c2012-11-11 05:11:20 +00002048
Meador Inge20255ef2013-03-12 00:08:29 +00002049// String library call optimizations.
2050static StrCatOpt StrCat;
2051static StrNCatOpt StrNCat;
2052static StrChrOpt StrChr;
2053static StrRChrOpt StrRChr;
2054static StrCmpOpt StrCmp;
2055static StrNCmpOpt StrNCmp;
2056static StrCpyOpt StrCpy;
2057static StpCpyOpt StpCpy;
2058static StrNCpyOpt StrNCpy;
2059static StrLenOpt StrLen;
2060static StrPBrkOpt StrPBrk;
2061static StrToOpt StrTo;
2062static StrSpnOpt StrSpn;
2063static StrCSpnOpt StrCSpn;
2064static StrStrOpt StrStr;
Meador Inge193e0352012-11-13 04:16:17 +00002065
Meador Inge20255ef2013-03-12 00:08:29 +00002066// Memory library call optimizations.
2067static MemCmpOpt MemCmp;
2068static MemCpyOpt MemCpy;
2069static MemMoveOpt MemMove;
2070static MemSetOpt MemSet;
Meador Inge193e0352012-11-13 04:16:17 +00002071
Meador Inge20255ef2013-03-12 00:08:29 +00002072// Math library call optimizations.
2073static UnaryDoubleFPOpt UnaryDoubleFP(false);
Yi Jiang6ab044e2013-12-16 22:42:40 +00002074static BinaryDoubleFPOpt BinaryDoubleFP(false);
Meador Inge20255ef2013-03-12 00:08:29 +00002075static UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
Bob Wilsond8d92d92013-11-03 06:48:38 +00002076static SinCosPiOpt SinCosPi;
Meador Inge7415f842012-11-25 20:45:27 +00002077
2078 // Integer library call optimizations.
Meador Inge20255ef2013-03-12 00:08:29 +00002079static FFSOpt FFS;
2080static AbsOpt Abs;
2081static IsDigitOpt IsDigit;
2082static IsAsciiOpt IsAscii;
2083static ToAsciiOpt ToAscii;
Meador Inge08ca1152012-11-26 20:37:20 +00002084
Meador Inge20255ef2013-03-12 00:08:29 +00002085// Formatting and IO library call optimizations.
Hal Finkel66cd3f12013-11-17 02:06:35 +00002086static ErrorReportingOpt ErrorReporting;
2087static ErrorReportingOpt ErrorReporting0(0);
2088static ErrorReportingOpt ErrorReporting1(1);
Meador Inge20255ef2013-03-12 00:08:29 +00002089static PrintFOpt PrintF;
2090static SPrintFOpt SPrintF;
2091static FPrintFOpt FPrintF;
2092static FWriteOpt FWrite;
2093static FPutsOpt FPuts;
2094static PutsOpt Puts;
2095
2096LibCallOptimization *LibCallSimplifierImpl::lookupOptimization(CallInst *CI) {
2097 LibFunc::Func Func;
2098 Function *Callee = CI->getCalledFunction();
2099 StringRef FuncName = Callee->getName();
2100
2101 // Next check for intrinsics.
2102 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2103 switch (II->getIntrinsicID()) {
2104 case Intrinsic::pow:
2105 return &Pow;
2106 case Intrinsic::exp2:
2107 return &Exp2;
2108 default:
2109 return 0;
2110 }
2111 }
2112
2113 // Then check for known library functions.
2114 if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
2115 switch (Func) {
2116 case LibFunc::strcat:
2117 return &StrCat;
2118 case LibFunc::strncat:
2119 return &StrNCat;
2120 case LibFunc::strchr:
2121 return &StrChr;
2122 case LibFunc::strrchr:
2123 return &StrRChr;
2124 case LibFunc::strcmp:
2125 return &StrCmp;
2126 case LibFunc::strncmp:
2127 return &StrNCmp;
2128 case LibFunc::strcpy:
2129 return &StrCpy;
2130 case LibFunc::stpcpy:
2131 return &StpCpy;
2132 case LibFunc::strncpy:
2133 return &StrNCpy;
2134 case LibFunc::strlen:
2135 return &StrLen;
2136 case LibFunc::strpbrk:
2137 return &StrPBrk;
2138 case LibFunc::strtol:
2139 case LibFunc::strtod:
2140 case LibFunc::strtof:
2141 case LibFunc::strtoul:
2142 case LibFunc::strtoll:
2143 case LibFunc::strtold:
2144 case LibFunc::strtoull:
2145 return &StrTo;
2146 case LibFunc::strspn:
2147 return &StrSpn;
2148 case LibFunc::strcspn:
2149 return &StrCSpn;
2150 case LibFunc::strstr:
2151 return &StrStr;
2152 case LibFunc::memcmp:
2153 return &MemCmp;
2154 case LibFunc::memcpy:
2155 return &MemCpy;
2156 case LibFunc::memmove:
2157 return &MemMove;
2158 case LibFunc::memset:
2159 return &MemSet;
2160 case LibFunc::cosf:
2161 case LibFunc::cos:
2162 case LibFunc::cosl:
2163 return &Cos;
Bob Wilsond8d92d92013-11-03 06:48:38 +00002164 case LibFunc::sinpif:
2165 case LibFunc::sinpi:
2166 case LibFunc::cospif:
2167 case LibFunc::cospi:
2168 return &SinCosPi;
Meador Inge20255ef2013-03-12 00:08:29 +00002169 case LibFunc::powf:
2170 case LibFunc::pow:
2171 case LibFunc::powl:
2172 return &Pow;
2173 case LibFunc::exp2l:
2174 case LibFunc::exp2:
2175 case LibFunc::exp2f:
2176 return &Exp2;
2177 case LibFunc::ffs:
2178 case LibFunc::ffsl:
2179 case LibFunc::ffsll:
2180 return &FFS;
2181 case LibFunc::abs:
2182 case LibFunc::labs:
2183 case LibFunc::llabs:
2184 return &Abs;
2185 case LibFunc::isdigit:
2186 return &IsDigit;
2187 case LibFunc::isascii:
2188 return &IsAscii;
2189 case LibFunc::toascii:
2190 return &ToAscii;
2191 case LibFunc::printf:
2192 return &PrintF;
2193 case LibFunc::sprintf:
2194 return &SPrintF;
2195 case LibFunc::fprintf:
2196 return &FPrintF;
2197 case LibFunc::fwrite:
2198 return &FWrite;
2199 case LibFunc::fputs:
2200 return &FPuts;
2201 case LibFunc::puts:
2202 return &Puts;
Hal Finkel66cd3f12013-11-17 02:06:35 +00002203 case LibFunc::perror:
2204 return &ErrorReporting;
2205 case LibFunc::vfprintf:
2206 case LibFunc::fiprintf:
2207 return &ErrorReporting0;
2208 case LibFunc::fputc:
2209 return &ErrorReporting1;
Meador Inge20255ef2013-03-12 00:08:29 +00002210 case LibFunc::ceil:
2211 case LibFunc::fabs:
2212 case LibFunc::floor:
2213 case LibFunc::rint:
2214 case LibFunc::round:
2215 case LibFunc::nearbyint:
2216 case LibFunc::trunc:
2217 if (hasFloatVersion(FuncName))
2218 return &UnaryDoubleFP;
2219 return 0;
2220 case LibFunc::acos:
2221 case LibFunc::acosh:
2222 case LibFunc::asin:
2223 case LibFunc::asinh:
2224 case LibFunc::atan:
2225 case LibFunc::atanh:
2226 case LibFunc::cbrt:
2227 case LibFunc::cosh:
2228 case LibFunc::exp:
2229 case LibFunc::exp10:
2230 case LibFunc::expm1:
2231 case LibFunc::log:
2232 case LibFunc::log10:
2233 case LibFunc::log1p:
2234 case LibFunc::log2:
2235 case LibFunc::logb:
2236 case LibFunc::sin:
2237 case LibFunc::sinh:
2238 case LibFunc::sqrt:
2239 case LibFunc::tan:
2240 case LibFunc::tanh:
2241 if (UnsafeFPShrink && hasFloatVersion(FuncName))
2242 return &UnsafeUnaryDoubleFP;
2243 return 0;
Yi Jiang6ab044e2013-12-16 22:42:40 +00002244 case LibFunc::fmin:
2245 case LibFunc::fmax:
2246 if (hasFloatVersion(FuncName))
2247 return &BinaryDoubleFP;
2248 return 0;
Meador Inge20255ef2013-03-12 00:08:29 +00002249 case LibFunc::memcpy_chk:
2250 return &MemCpyChk;
2251 default:
2252 return 0;
2253 }
2254 }
2255
2256 // Finally check for fortified library calls.
2257 if (FuncName.endswith("_chk")) {
2258 if (FuncName == "__memmove_chk")
2259 return &MemMoveChk;
2260 else if (FuncName == "__memset_chk")
2261 return &MemSetChk;
2262 else if (FuncName == "__strcpy_chk")
2263 return &StrCpyChk;
2264 else if (FuncName == "__stpcpy_chk")
2265 return &StpCpyChk;
2266 else if (FuncName == "__strncpy_chk")
2267 return &StrNCpyChk;
2268 else if (FuncName == "__stpncpy_chk")
2269 return &StrNCpyChk;
2270 }
2271
2272 return 0;
2273
Meador Ingedf796f82012-10-13 16:45:24 +00002274}
2275
2276Value *LibCallSimplifierImpl::optimizeCall(CallInst *CI) {
Meador Inge20255ef2013-03-12 00:08:29 +00002277 LibCallOptimization *LCO = lookupOptimization(CI);
Meador Ingedf796f82012-10-13 16:45:24 +00002278 if (LCO) {
2279 IRBuilder<> Builder(CI);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002280 return LCO->optimizeCall(CI, DL, TLI, LCS, Builder);
Meador Ingedf796f82012-10-13 16:45:24 +00002281 }
2282 return 0;
2283}
2284
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002285LibCallSimplifier::LibCallSimplifier(const DataLayout *DL,
Meador Inge193e0352012-11-13 04:16:17 +00002286 const TargetLibraryInfo *TLI,
2287 bool UnsafeFPShrink) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002288 Impl = new LibCallSimplifierImpl(DL, TLI, this, UnsafeFPShrink);
Meador Ingedf796f82012-10-13 16:45:24 +00002289}
2290
2291LibCallSimplifier::~LibCallSimplifier() {
2292 delete Impl;
2293}
2294
2295Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
Michael Gottesman41748d72013-06-27 00:25:01 +00002296 if (CI->isNoBuiltin()) return 0;
Meador Ingedf796f82012-10-13 16:45:24 +00002297 return Impl->optimizeCall(CI);
2298}
2299
Meador Inge76fc1a42012-11-11 03:51:43 +00002300void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) const {
2301 I->replaceAllUsesWith(With);
2302 I->eraseFromParent();
2303}
2304
Meador Ingedf796f82012-10-13 16:45:24 +00002305}
Meador Ingedfb08a22013-06-20 19:48:07 +00002306
2307// TODO:
2308// Additional cases that we need to add to this file:
2309//
2310// cbrt:
2311// * cbrt(expN(X)) -> expN(x/3)
2312// * cbrt(sqrt(x)) -> pow(x,1/6)
2313// * cbrt(sqrt(x)) -> pow(x,1/9)
2314//
2315// exp, expf, expl:
2316// * exp(log(x)) -> x
2317//
2318// log, logf, logl:
2319// * log(exp(x)) -> x
2320// * log(x**y) -> y*log(x)
2321// * log(exp(y)) -> y*log(e)
2322// * log(exp2(y)) -> y*log(2)
2323// * log(exp10(y)) -> y*log(10)
2324// * log(sqrt(x)) -> 0.5*log(x)
2325// * log(pow(x,y)) -> y*log(x)
2326//
2327// lround, lroundf, lroundl:
2328// * lround(cnst) -> cnst'
2329//
2330// pow, powf, powl:
2331// * pow(exp(x),y) -> exp(x*y)
2332// * pow(sqrt(x),y) -> pow(x,y*0.5)
2333// * pow(pow(x,y),z)-> pow(x,y*z)
2334//
2335// round, roundf, roundl:
2336// * round(cnst) -> cnst'
2337//
2338// signbit:
2339// * signbit(cnst) -> cnst'
2340// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2341//
2342// sqrt, sqrtf, sqrtl:
2343// * sqrt(expN(x)) -> expN(x*0.5)
2344// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2345// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2346//
Meador Ingedfb08a22013-06-20 19:48:07 +00002347// tan, tanf, tanl:
2348// * tan(atan(x)) -> x
2349//
2350// trunc, truncf, truncl:
2351// * trunc(cnst) -> cnst'
2352//
2353//