1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a simple pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BuildLibCalls.h"
21 #include "llvm/IRBuilder.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/DataLayout.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
39 STATISTIC(NumSimplified, "Number of library calls simplified");
40 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
42 //===----------------------------------------------------------------------===//
43 // Optimizer Base Class
44 //===----------------------------------------------------------------------===//
46 /// This class is the abstract base class for the set of optimizations that
47 /// corresponds to one library call.
49 class LibCallOptimization {
53 const TargetLibraryInfo *TLI;
56 LibCallOptimization() { }
57 virtual ~LibCallOptimization() {}
59 /// CallOptimizer - This pure virtual method is implemented by base classes to
60 /// do various optimizations. If this returns null then no transformation was
61 /// performed. If it returns CI, then it transformed the call and CI is to be
62 /// deleted. If it returns something else, replace CI with the new value and
64 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
67 Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
68 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
69 Caller = CI->getParent()->getParent();
72 if (CI->getCalledFunction())
73 Context = &CI->getCalledFunction()->getContext();
75 // We never change the calling convention.
76 if (CI->getCallingConv() != llvm::CallingConv::C)
79 return CallOptimizer(CI->getCalledFunction(), CI, B);
82 } // End anonymous namespace.
85 //===----------------------------------------------------------------------===//
87 //===----------------------------------------------------------------------===//
89 static bool CallHasFloatingPointArgument(const CallInst *CI) {
90 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
92 if ((*it)->getType()->isFloatingPointTy())
99 //===----------------------------------------------------------------------===//
100 // Integer Optimizations
101 //===----------------------------------------------------------------------===//
103 //===---------------------------------------===//
104 // 'ffs*' Optimizations
106 struct FFSOpt : public LibCallOptimization {
107 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
108 FunctionType *FT = Callee->getFunctionType();
109 // Just make sure this has 2 arguments of the same FP type, which match the
111 if (FT->getNumParams() != 1 ||
112 !FT->getReturnType()->isIntegerTy(32) ||
113 !FT->getParamType(0)->isIntegerTy())
116 Value *Op = CI->getArgOperand(0);
119 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
120 if (CI->isZero()) // ffs(0) -> 0.
121 return B.getInt32(0);
122 // ffs(c) -> cttz(c)+1
123 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
126 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
127 Type *ArgType = Op->getType();
128 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
129 Intrinsic::cttz, ArgType);
130 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
131 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
132 V = B.CreateIntCast(V, B.getInt32Ty(), false);
134 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
135 return B.CreateSelect(Cond, V, B.getInt32(0));
139 //===---------------------------------------===//
140 // 'isdigit' Optimizations
142 struct IsDigitOpt : public LibCallOptimization {
143 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
144 FunctionType *FT = Callee->getFunctionType();
145 // We require integer(i32)
146 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
147 !FT->getParamType(0)->isIntegerTy(32))
150 // isdigit(c) -> (c-'0') <u 10
151 Value *Op = CI->getArgOperand(0);
152 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
153 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
154 return B.CreateZExt(Op, CI->getType());
158 //===---------------------------------------===//
159 // 'isascii' Optimizations
161 struct IsAsciiOpt : public LibCallOptimization {
162 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
163 FunctionType *FT = Callee->getFunctionType();
164 // We require integer(i32)
165 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
166 !FT->getParamType(0)->isIntegerTy(32))
169 // isascii(c) -> c <u 128
170 Value *Op = CI->getArgOperand(0);
171 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
172 return B.CreateZExt(Op, CI->getType());
176 //===---------------------------------------===//
177 // 'abs', 'labs', 'llabs' Optimizations
179 struct AbsOpt : public LibCallOptimization {
180 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
181 FunctionType *FT = Callee->getFunctionType();
182 // We require integer(integer) where the types agree.
183 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
184 FT->getParamType(0) != FT->getReturnType())
187 // abs(x) -> x >s -1 ? x : -x
188 Value *Op = CI->getArgOperand(0);
189 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
191 Value *Neg = B.CreateNeg(Op, "neg");
192 return B.CreateSelect(Pos, Op, Neg);
197 //===---------------------------------------===//
198 // 'toascii' Optimizations
200 struct ToAsciiOpt : public LibCallOptimization {
201 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
202 FunctionType *FT = Callee->getFunctionType();
203 // We require i32(i32)
204 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
205 !FT->getParamType(0)->isIntegerTy(32))
208 // isascii(c) -> c & 0x7f
209 return B.CreateAnd(CI->getArgOperand(0),
210 ConstantInt::get(CI->getType(),0x7F));
214 //===----------------------------------------------------------------------===//
215 // Formatting and IO Optimizations
216 //===----------------------------------------------------------------------===//
218 //===---------------------------------------===//
219 // 'printf' Optimizations
221 struct PrintFOpt : public LibCallOptimization {
222 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
224 // Check for a fixed format string.
226 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
229 // Empty format string -> noop.
230 if (FormatStr.empty()) // Tolerate printf's declared void.
231 return CI->use_empty() ? (Value*)CI :
232 ConstantInt::get(CI->getType(), 0);
234 // Do not do any of the following transformations if the printf return value
235 // is used, in general the printf return value is not compatible with either
236 // putchar() or puts().
237 if (!CI->use_empty())
240 // printf("x") -> putchar('x'), even for '%'.
241 if (FormatStr.size() == 1) {
242 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
243 if (CI->use_empty() || !Res) return Res;
244 return B.CreateIntCast(Res, CI->getType(), true);
247 // printf("foo\n") --> puts("foo")
248 if (FormatStr[FormatStr.size()-1] == '\n' &&
249 FormatStr.find('%') == std::string::npos) { // no format characters.
250 // Create a string literal with no \n on it. We expect the constant merge
251 // pass to be run after this pass, to merge duplicate strings.
252 FormatStr = FormatStr.drop_back();
253 Value *GV = B.CreateGlobalString(FormatStr, "str");
254 Value *NewCI = EmitPutS(GV, B, TD, TLI);
255 return (CI->use_empty() || !NewCI) ?
257 ConstantInt::get(CI->getType(), FormatStr.size()+1);
260 // Optimize specific format strings.
261 // printf("%c", chr) --> putchar(chr)
262 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
263 CI->getArgOperand(1)->getType()->isIntegerTy()) {
264 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
266 if (CI->use_empty() || !Res) return Res;
267 return B.CreateIntCast(Res, CI->getType(), true);
270 // printf("%s\n", str) --> puts(str)
271 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
272 CI->getArgOperand(1)->getType()->isPointerTy()) {
273 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
279 // Require one fixed pointer argument and an integer/void result.
280 FunctionType *FT = Callee->getFunctionType();
281 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
282 !(FT->getReturnType()->isIntegerTy() ||
283 FT->getReturnType()->isVoidTy()))
286 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
290 // printf(format, ...) -> iprintf(format, ...) if no floating point
292 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
293 Module *M = B.GetInsertBlock()->getParent()->getParent();
294 Constant *IPrintFFn =
295 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
296 CallInst *New = cast<CallInst>(CI->clone());
297 New->setCalledFunction(IPrintFFn);
305 //===---------------------------------------===//
306 // 'sprintf' Optimizations
308 struct SPrintFOpt : public LibCallOptimization {
309 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
311 // Check for a fixed format string.
313 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
316 // If we just have a format string (nothing else crazy) transform it.
317 if (CI->getNumArgOperands() == 2) {
318 // Make sure there's no % in the constant array. We could try to handle
319 // %% -> % in the future if we cared.
320 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
321 if (FormatStr[i] == '%')
322 return 0; // we found a format specifier, bail out.
324 // These optimizations require DataLayout.
327 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
328 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
329 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
330 FormatStr.size() + 1), 1); // nul byte.
331 return ConstantInt::get(CI->getType(), FormatStr.size());
334 // The remaining optimizations require the format string to be "%s" or "%c"
335 // and have an extra operand.
336 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
337 CI->getNumArgOperands() < 3)
340 // Decode the second character of the format string.
341 if (FormatStr[1] == 'c') {
342 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
343 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
344 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
345 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
346 B.CreateStore(V, Ptr);
347 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
348 B.CreateStore(B.getInt8(0), Ptr);
350 return ConstantInt::get(CI->getType(), 1);
353 if (FormatStr[1] == 's') {
354 // These optimizations require DataLayout.
357 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
358 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
360 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
363 Value *IncLen = B.CreateAdd(Len,
364 ConstantInt::get(Len->getType(), 1),
366 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
368 // The sprintf result is the unincremented number of bytes in the string.
369 return B.CreateIntCast(Len, CI->getType(), false);
374 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
375 // Require two fixed pointer arguments and an integer result.
376 FunctionType *FT = Callee->getFunctionType();
377 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
378 !FT->getParamType(1)->isPointerTy() ||
379 !FT->getReturnType()->isIntegerTy())
382 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
386 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
388 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
389 Module *M = B.GetInsertBlock()->getParent()->getParent();
390 Constant *SIPrintFFn =
391 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
392 CallInst *New = cast<CallInst>(CI->clone());
393 New->setCalledFunction(SIPrintFFn);
401 //===---------------------------------------===//
402 // 'fwrite' Optimizations
404 struct FWriteOpt : public LibCallOptimization {
405 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
406 // Require a pointer, an integer, an integer, a pointer, returning integer.
407 FunctionType *FT = Callee->getFunctionType();
408 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
409 !FT->getParamType(1)->isIntegerTy() ||
410 !FT->getParamType(2)->isIntegerTy() ||
411 !FT->getParamType(3)->isPointerTy() ||
412 !FT->getReturnType()->isIntegerTy())
415 // Get the element size and count.
416 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
417 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
418 if (!SizeC || !CountC) return 0;
419 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
421 // If this is writing zero records, remove the call (it's a noop).
423 return ConstantInt::get(CI->getType(), 0);
425 // If this is writing one byte, turn it into fputc.
426 // This optimisation is only valid, if the return value is unused.
427 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
428 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
429 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
430 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
437 //===---------------------------------------===//
438 // 'fputs' Optimizations
440 struct FPutsOpt : public LibCallOptimization {
441 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
442 // These optimizations require DataLayout.
445 // Require two pointers. Also, we can't optimize if return value is used.
446 FunctionType *FT = Callee->getFunctionType();
447 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
448 !FT->getParamType(1)->isPointerTy() ||
452 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
453 uint64_t Len = GetStringLength(CI->getArgOperand(0));
455 // Known to have no uses (see above).
456 return EmitFWrite(CI->getArgOperand(0),
457 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
458 CI->getArgOperand(1), B, TD, TLI);
462 //===---------------------------------------===//
463 // 'fprintf' Optimizations
465 struct FPrintFOpt : public LibCallOptimization {
466 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
468 // All the optimizations depend on the format string.
470 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
473 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
474 if (CI->getNumArgOperands() == 2) {
475 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
476 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
477 return 0; // We found a format specifier.
479 // These optimizations require DataLayout.
482 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
483 ConstantInt::get(TD->getIntPtrType(*Context),
485 CI->getArgOperand(0), B, TD, TLI);
486 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
489 // The remaining optimizations require the format string to be "%s" or "%c"
490 // and have an extra operand.
491 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
492 CI->getNumArgOperands() < 3)
495 // Decode the second character of the format string.
496 if (FormatStr[1] == 'c') {
497 // fprintf(F, "%c", chr) --> fputc(chr, F)
498 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
499 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
501 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
504 if (FormatStr[1] == 's') {
505 // fprintf(F, "%s", str) --> fputs(str, F)
506 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
508 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
513 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
514 // Require two fixed paramters as pointers and integer result.
515 FunctionType *FT = Callee->getFunctionType();
516 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
517 !FT->getParamType(1)->isPointerTy() ||
518 !FT->getReturnType()->isIntegerTy())
521 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
525 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
526 // floating point arguments.
527 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
528 Module *M = B.GetInsertBlock()->getParent()->getParent();
529 Constant *FIPrintFFn =
530 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
531 CallInst *New = cast<CallInst>(CI->clone());
532 New->setCalledFunction(FIPrintFFn);
540 //===---------------------------------------===//
541 // 'puts' Optimizations
543 struct PutsOpt : public LibCallOptimization {
544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
545 // Require one fixed pointer argument and an integer/void result.
546 FunctionType *FT = Callee->getFunctionType();
547 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
548 !(FT->getReturnType()->isIntegerTy() ||
549 FT->getReturnType()->isVoidTy()))
552 // Check for a constant string.
554 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
557 if (Str.empty() && CI->use_empty()) {
558 // puts("") -> putchar('\n')
559 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
560 if (CI->use_empty() || !Res) return Res;
561 return B.CreateIntCast(Res, CI->getType(), true);
568 } // end anonymous namespace.
570 //===----------------------------------------------------------------------===//
571 // SimplifyLibCalls Pass Implementation
572 //===----------------------------------------------------------------------===//
575 /// This pass optimizes well known library functions from libc and libm.
577 class SimplifyLibCalls : public FunctionPass {
578 TargetLibraryInfo *TLI;
580 StringMap<LibCallOptimization*> Optimizations;
581 // Integer Optimizations
582 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
584 // Formatting and IO Optimizations
585 SPrintFOpt SPrintF; PrintFOpt PrintF;
586 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
589 bool Modified; // This is only used by doInitialization.
591 static char ID; // Pass identification
592 SimplifyLibCalls() : FunctionPass(ID) {
593 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
595 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
596 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
598 void InitOptimizations();
599 bool runOnFunction(Function &F);
601 void setDoesNotAccessMemory(Function &F);
602 void setOnlyReadsMemory(Function &F);
603 void setDoesNotThrow(Function &F);
604 void setDoesNotCapture(Function &F, unsigned n);
605 void setDoesNotAlias(Function &F, unsigned n);
606 bool doInitialization(Module &M);
608 void inferPrototypeAttributes(Function &F);
609 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
610 AU.addRequired<TargetLibraryInfo>();
613 } // end anonymous namespace.
615 char SimplifyLibCalls::ID = 0;
617 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
618 "Simplify well-known library calls", false, false)
619 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
620 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
621 "Simplify well-known library calls", false, false)
623 // Public interface to the Simplify LibCalls pass.
624 FunctionPass *llvm::createSimplifyLibCallsPass() {
625 return new SimplifyLibCalls();
628 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
630 Optimizations[TLI->getName(F)] = Opt;
633 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
634 LibCallOptimization* Opt) {
635 if (TLI->has(F1) && TLI->has(F2))
636 Optimizations[TLI->getName(F1)] = Opt;
639 /// Optimizations - Populate the Optimizations map with all the optimizations
641 void SimplifyLibCalls::InitOptimizations() {
642 // Integer Optimizations
643 Optimizations["ffs"] = &FFS;
644 Optimizations["ffsl"] = &FFS;
645 Optimizations["ffsll"] = &FFS;
646 Optimizations["abs"] = &Abs;
647 Optimizations["labs"] = &Abs;
648 Optimizations["llabs"] = &Abs;
649 Optimizations["isdigit"] = &IsDigit;
650 Optimizations["isascii"] = &IsAscii;
651 Optimizations["toascii"] = &ToAscii;
653 // Formatting and IO Optimizations
654 Optimizations["sprintf"] = &SPrintF;
655 Optimizations["printf"] = &PrintF;
656 AddOpt(LibFunc::fwrite, &FWrite);
657 AddOpt(LibFunc::fputs, &FPuts);
658 Optimizations["fprintf"] = &FPrintF;
659 Optimizations["puts"] = &Puts;
663 /// runOnFunction - Top level algorithm.
665 bool SimplifyLibCalls::runOnFunction(Function &F) {
666 TLI = &getAnalysis<TargetLibraryInfo>();
668 if (Optimizations.empty())
671 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
673 IRBuilder<> Builder(F.getContext());
675 bool Changed = false;
676 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
677 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
679 CallInst *CI = dyn_cast<CallInst>(I++);
682 // Ignore indirect calls and calls to non-external functions.
683 Function *Callee = CI->getCalledFunction();
684 if (Callee == 0 || !Callee->isDeclaration() ||
685 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
688 // Ignore unknown calls.
689 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
692 // Set the builder to the instruction after the call.
693 Builder.SetInsertPoint(BB, I);
695 // Use debug location of CI for all new instructions.
696 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
698 // Try to optimize this call.
699 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
700 if (Result == 0) continue;
702 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
703 dbgs() << " into: " << *Result << "\n");
705 // Something changed!
709 // Inspect the instruction after the call (which was potentially just
713 if (CI != Result && !CI->use_empty()) {
714 CI->replaceAllUsesWith(Result);
715 if (!Result->hasName())
716 Result->takeName(CI);
718 CI->eraseFromParent();
724 // Utility methods for doInitialization.
726 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
727 if (!F.doesNotAccessMemory()) {
728 F.setDoesNotAccessMemory();
733 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
734 if (!F.onlyReadsMemory()) {
735 F.setOnlyReadsMemory();
740 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
741 if (!F.doesNotThrow()) {
747 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
748 if (!F.doesNotCapture(n)) {
749 F.setDoesNotCapture(n);
754 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
755 if (!F.doesNotAlias(n)) {
756 F.setDoesNotAlias(n);
763 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
764 FunctionType *FTy = F.getFunctionType();
766 StringRef Name = F.getName();
769 if (Name == "strlen") {
770 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
772 setOnlyReadsMemory(F);
774 setDoesNotCapture(F, 1);
775 } else if (Name == "strchr" ||
777 if (FTy->getNumParams() != 2 ||
778 !FTy->getParamType(0)->isPointerTy() ||
779 !FTy->getParamType(1)->isIntegerTy())
781 setOnlyReadsMemory(F);
783 } else if (Name == "strcpy" ||
795 Name == "strtoull") {
796 if (FTy->getNumParams() < 2 ||
797 !FTy->getParamType(1)->isPointerTy())
800 setDoesNotCapture(F, 2);
801 } else if (Name == "strxfrm") {
802 if (FTy->getNumParams() != 3 ||
803 !FTy->getParamType(0)->isPointerTy() ||
804 !FTy->getParamType(1)->isPointerTy())
807 setDoesNotCapture(F, 1);
808 setDoesNotCapture(F, 2);
809 } else if (Name == "strcmp" ||
814 Name == "strcasecmp" ||
815 Name == "strncasecmp") {
816 if (FTy->getNumParams() < 2 ||
817 !FTy->getParamType(0)->isPointerTy() ||
818 !FTy->getParamType(1)->isPointerTy())
820 setOnlyReadsMemory(F);
822 setDoesNotCapture(F, 1);
823 setDoesNotCapture(F, 2);
824 } else if (Name == "strstr" ||
826 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
828 setOnlyReadsMemory(F);
830 setDoesNotCapture(F, 2);
831 } else if (Name == "strtok" ||
832 Name == "strtok_r") {
833 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
836 setDoesNotCapture(F, 2);
837 } else if (Name == "scanf" ||
840 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
843 setDoesNotCapture(F, 1);
844 } else if (Name == "strdup" ||
846 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
847 !FTy->getParamType(0)->isPointerTy())
850 setDoesNotAlias(F, 0);
851 setDoesNotCapture(F, 1);
852 } else if (Name == "stat" ||
856 if (FTy->getNumParams() < 2 ||
857 !FTy->getParamType(0)->isPointerTy() ||
858 !FTy->getParamType(1)->isPointerTy())
861 setDoesNotCapture(F, 1);
862 setDoesNotCapture(F, 2);
863 } else if (Name == "snprintf") {
864 if (FTy->getNumParams() != 3 ||
865 !FTy->getParamType(0)->isPointerTy() ||
866 !FTy->getParamType(2)->isPointerTy())
869 setDoesNotCapture(F, 1);
870 setDoesNotCapture(F, 3);
871 } else if (Name == "setitimer") {
872 if (FTy->getNumParams() != 3 ||
873 !FTy->getParamType(1)->isPointerTy() ||
874 !FTy->getParamType(2)->isPointerTy())
877 setDoesNotCapture(F, 2);
878 setDoesNotCapture(F, 3);
879 } else if (Name == "system") {
880 if (FTy->getNumParams() != 1 ||
881 !FTy->getParamType(0)->isPointerTy())
883 // May throw; "system" is a valid pthread cancellation point.
884 setDoesNotCapture(F, 1);
888 if (Name == "malloc") {
889 if (FTy->getNumParams() != 1 ||
890 !FTy->getReturnType()->isPointerTy())
893 setDoesNotAlias(F, 0);
894 } else if (Name == "memcmp") {
895 if (FTy->getNumParams() != 3 ||
896 !FTy->getParamType(0)->isPointerTy() ||
897 !FTy->getParamType(1)->isPointerTy())
899 setOnlyReadsMemory(F);
901 setDoesNotCapture(F, 1);
902 setDoesNotCapture(F, 2);
903 } else if (Name == "memchr" ||
905 if (FTy->getNumParams() != 3)
907 setOnlyReadsMemory(F);
909 } else if (Name == "modf" ||
915 if (FTy->getNumParams() < 2 ||
916 !FTy->getParamType(1)->isPointerTy())
919 setDoesNotCapture(F, 2);
920 } else if (Name == "memalign") {
921 if (!FTy->getReturnType()->isPointerTy())
923 setDoesNotAlias(F, 0);
924 } else if (Name == "mkdir" ||
926 if (FTy->getNumParams() == 0 ||
927 !FTy->getParamType(0)->isPointerTy())
930 setDoesNotCapture(F, 1);
934 if (Name == "realloc") {
935 if (FTy->getNumParams() != 2 ||
936 !FTy->getParamType(0)->isPointerTy() ||
937 !FTy->getReturnType()->isPointerTy())
940 setDoesNotAlias(F, 0);
941 setDoesNotCapture(F, 1);
942 } else if (Name == "read") {
943 if (FTy->getNumParams() != 3 ||
944 !FTy->getParamType(1)->isPointerTy())
946 // May throw; "read" is a valid pthread cancellation point.
947 setDoesNotCapture(F, 2);
948 } else if (Name == "rmdir" ||
951 Name == "realpath") {
952 if (FTy->getNumParams() < 1 ||
953 !FTy->getParamType(0)->isPointerTy())
956 setDoesNotCapture(F, 1);
957 } else if (Name == "rename" ||
958 Name == "readlink") {
959 if (FTy->getNumParams() < 2 ||
960 !FTy->getParamType(0)->isPointerTy() ||
961 !FTy->getParamType(1)->isPointerTy())
964 setDoesNotCapture(F, 1);
965 setDoesNotCapture(F, 2);
969 if (Name == "write") {
970 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
972 // May throw; "write" is a valid pthread cancellation point.
973 setDoesNotCapture(F, 2);
977 if (Name == "bcopy") {
978 if (FTy->getNumParams() != 3 ||
979 !FTy->getParamType(0)->isPointerTy() ||
980 !FTy->getParamType(1)->isPointerTy())
983 setDoesNotCapture(F, 1);
984 setDoesNotCapture(F, 2);
985 } else if (Name == "bcmp") {
986 if (FTy->getNumParams() != 3 ||
987 !FTy->getParamType(0)->isPointerTy() ||
988 !FTy->getParamType(1)->isPointerTy())
991 setOnlyReadsMemory(F);
992 setDoesNotCapture(F, 1);
993 setDoesNotCapture(F, 2);
994 } else if (Name == "bzero") {
995 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
998 setDoesNotCapture(F, 1);
1002 if (Name == "calloc") {
1003 if (FTy->getNumParams() != 2 ||
1004 !FTy->getReturnType()->isPointerTy())
1007 setDoesNotAlias(F, 0);
1008 } else if (Name == "chmod" ||
1010 Name == "ctermid" ||
1011 Name == "clearerr" ||
1012 Name == "closedir") {
1013 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1016 setDoesNotCapture(F, 1);
1020 if (Name == "atoi" ||
1024 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1027 setOnlyReadsMemory(F);
1028 setDoesNotCapture(F, 1);
1029 } else if (Name == "access") {
1030 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1033 setDoesNotCapture(F, 1);
1037 if (Name == "fopen") {
1038 if (FTy->getNumParams() != 2 ||
1039 !FTy->getReturnType()->isPointerTy() ||
1040 !FTy->getParamType(0)->isPointerTy() ||
1041 !FTy->getParamType(1)->isPointerTy())
1044 setDoesNotAlias(F, 0);
1045 setDoesNotCapture(F, 1);
1046 setDoesNotCapture(F, 2);
1047 } else if (Name == "fdopen") {
1048 if (FTy->getNumParams() != 2 ||
1049 !FTy->getReturnType()->isPointerTy() ||
1050 !FTy->getParamType(1)->isPointerTy())
1053 setDoesNotAlias(F, 0);
1054 setDoesNotCapture(F, 2);
1055 } else if (Name == "feof" ||
1065 Name == "fsetpos" ||
1066 Name == "flockfile" ||
1067 Name == "funlockfile" ||
1068 Name == "ftrylockfile") {
1069 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1072 setDoesNotCapture(F, 1);
1073 } else if (Name == "ferror") {
1074 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1077 setDoesNotCapture(F, 1);
1078 setOnlyReadsMemory(F);
1079 } else if (Name == "fputc" ||
1084 Name == "fstatvfs") {
1085 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1088 setDoesNotCapture(F, 2);
1089 } else if (Name == "fgets") {
1090 if (FTy->getNumParams() != 3 ||
1091 !FTy->getParamType(0)->isPointerTy() ||
1092 !FTy->getParamType(2)->isPointerTy())
1095 setDoesNotCapture(F, 3);
1096 } else if (Name == "fread" ||
1098 if (FTy->getNumParams() != 4 ||
1099 !FTy->getParamType(0)->isPointerTy() ||
1100 !FTy->getParamType(3)->isPointerTy())
1103 setDoesNotCapture(F, 1);
1104 setDoesNotCapture(F, 4);
1105 } else if (Name == "fputs" ||
1107 Name == "fprintf" ||
1108 Name == "fgetpos") {
1109 if (FTy->getNumParams() < 2 ||
1110 !FTy->getParamType(0)->isPointerTy() ||
1111 !FTy->getParamType(1)->isPointerTy())
1114 setDoesNotCapture(F, 1);
1115 setDoesNotCapture(F, 2);
1119 if (Name == "getc" ||
1120 Name == "getlogin_r" ||
1121 Name == "getc_unlocked") {
1122 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1125 setDoesNotCapture(F, 1);
1126 } else if (Name == "getenv") {
1127 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1130 setOnlyReadsMemory(F);
1131 setDoesNotCapture(F, 1);
1132 } else if (Name == "gets" ||
1133 Name == "getchar") {
1135 } else if (Name == "getitimer") {
1136 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1139 setDoesNotCapture(F, 2);
1140 } else if (Name == "getpwnam") {
1141 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1144 setDoesNotCapture(F, 1);
1148 if (Name == "ungetc") {
1149 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1152 setDoesNotCapture(F, 2);
1153 } else if (Name == "uname" ||
1155 Name == "unsetenv") {
1156 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1159 setDoesNotCapture(F, 1);
1160 } else if (Name == "utime" ||
1162 if (FTy->getNumParams() != 2 ||
1163 !FTy->getParamType(0)->isPointerTy() ||
1164 !FTy->getParamType(1)->isPointerTy())
1167 setDoesNotCapture(F, 1);
1168 setDoesNotCapture(F, 2);
1172 if (Name == "putc") {
1173 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1176 setDoesNotCapture(F, 2);
1177 } else if (Name == "puts" ||
1180 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1183 setDoesNotCapture(F, 1);
1184 } else if (Name == "pread" ||
1186 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1188 // May throw; these are valid pthread cancellation points.
1189 setDoesNotCapture(F, 2);
1190 } else if (Name == "putchar") {
1192 } else if (Name == "popen") {
1193 if (FTy->getNumParams() != 2 ||
1194 !FTy->getReturnType()->isPointerTy() ||
1195 !FTy->getParamType(0)->isPointerTy() ||
1196 !FTy->getParamType(1)->isPointerTy())
1199 setDoesNotAlias(F, 0);
1200 setDoesNotCapture(F, 1);
1201 setDoesNotCapture(F, 2);
1202 } else if (Name == "pclose") {
1203 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1206 setDoesNotCapture(F, 1);
1210 if (Name == "vscanf") {
1211 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1214 setDoesNotCapture(F, 1);
1215 } else if (Name == "vsscanf" ||
1216 Name == "vfscanf") {
1217 if (FTy->getNumParams() != 3 ||
1218 !FTy->getParamType(1)->isPointerTy() ||
1219 !FTy->getParamType(2)->isPointerTy())
1222 setDoesNotCapture(F, 1);
1223 setDoesNotCapture(F, 2);
1224 } else if (Name == "valloc") {
1225 if (!FTy->getReturnType()->isPointerTy())
1228 setDoesNotAlias(F, 0);
1229 } else if (Name == "vprintf") {
1230 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1233 setDoesNotCapture(F, 1);
1234 } else if (Name == "vfprintf" ||
1235 Name == "vsprintf") {
1236 if (FTy->getNumParams() != 3 ||
1237 !FTy->getParamType(0)->isPointerTy() ||
1238 !FTy->getParamType(1)->isPointerTy())
1241 setDoesNotCapture(F, 1);
1242 setDoesNotCapture(F, 2);
1243 } else if (Name == "vsnprintf") {
1244 if (FTy->getNumParams() != 4 ||
1245 !FTy->getParamType(0)->isPointerTy() ||
1246 !FTy->getParamType(2)->isPointerTy())
1249 setDoesNotCapture(F, 1);
1250 setDoesNotCapture(F, 3);
1254 if (Name == "open") {
1255 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1257 // May throw; "open" is a valid pthread cancellation point.
1258 setDoesNotCapture(F, 1);
1259 } else if (Name == "opendir") {
1260 if (FTy->getNumParams() != 1 ||
1261 !FTy->getReturnType()->isPointerTy() ||
1262 !FTy->getParamType(0)->isPointerTy())
1265 setDoesNotAlias(F, 0);
1266 setDoesNotCapture(F, 1);
1270 if (Name == "tmpfile") {
1271 if (!FTy->getReturnType()->isPointerTy())
1274 setDoesNotAlias(F, 0);
1275 } else if (Name == "times") {
1276 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1279 setDoesNotCapture(F, 1);
1283 if (Name == "htonl" ||
1286 setDoesNotAccessMemory(F);
1290 if (Name == "ntohl" ||
1293 setDoesNotAccessMemory(F);
1297 if (Name == "lstat") {
1298 if (FTy->getNumParams() != 2 ||
1299 !FTy->getParamType(0)->isPointerTy() ||
1300 !FTy->getParamType(1)->isPointerTy())
1303 setDoesNotCapture(F, 1);
1304 setDoesNotCapture(F, 2);
1305 } else if (Name == "lchown") {
1306 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1309 setDoesNotCapture(F, 1);
1313 if (Name == "qsort") {
1314 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1316 // May throw; places call through function pointer.
1317 setDoesNotCapture(F, 4);
1321 if (Name == "__strdup" ||
1322 Name == "__strndup") {
1323 if (FTy->getNumParams() < 1 ||
1324 !FTy->getReturnType()->isPointerTy() ||
1325 !FTy->getParamType(0)->isPointerTy())
1328 setDoesNotAlias(F, 0);
1329 setDoesNotCapture(F, 1);
1330 } else if (Name == "__strtok_r") {
1331 if (FTy->getNumParams() != 3 ||
1332 !FTy->getParamType(1)->isPointerTy())
1335 setDoesNotCapture(F, 2);
1336 } else if (Name == "_IO_getc") {
1337 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1340 setDoesNotCapture(F, 1);
1341 } else if (Name == "_IO_putc") {
1342 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1345 setDoesNotCapture(F, 2);
1349 if (Name == "\1__isoc99_scanf") {
1350 if (FTy->getNumParams() < 1 ||
1351 !FTy->getParamType(0)->isPointerTy())
1354 setDoesNotCapture(F, 1);
1355 } else if (Name == "\1stat64" ||
1356 Name == "\1lstat64" ||
1357 Name == "\1statvfs64" ||
1358 Name == "\1__isoc99_sscanf") {
1359 if (FTy->getNumParams() < 1 ||
1360 !FTy->getParamType(0)->isPointerTy() ||
1361 !FTy->getParamType(1)->isPointerTy())
1364 setDoesNotCapture(F, 1);
1365 setDoesNotCapture(F, 2);
1366 } else if (Name == "\1fopen64") {
1367 if (FTy->getNumParams() != 2 ||
1368 !FTy->getReturnType()->isPointerTy() ||
1369 !FTy->getParamType(0)->isPointerTy() ||
1370 !FTy->getParamType(1)->isPointerTy())
1373 setDoesNotAlias(F, 0);
1374 setDoesNotCapture(F, 1);
1375 setDoesNotCapture(F, 2);
1376 } else if (Name == "\1fseeko64" ||
1377 Name == "\1ftello64") {
1378 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1381 setDoesNotCapture(F, 1);
1382 } else if (Name == "\1tmpfile64") {
1383 if (!FTy->getReturnType()->isPointerTy())
1386 setDoesNotAlias(F, 0);
1387 } else if (Name == "\1fstat64" ||
1388 Name == "\1fstatvfs64") {
1389 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1392 setDoesNotCapture(F, 2);
1393 } else if (Name == "\1open64") {
1394 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1396 // May throw; "open" is a valid pthread cancellation point.
1397 setDoesNotCapture(F, 1);
1403 /// doInitialization - Add attributes to well-known functions.
1405 bool SimplifyLibCalls::doInitialization(Module &M) {
1407 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1409 if (F.isDeclaration() && F.hasName())
1410 inferPrototypeAttributes(F);
1416 // Additional cases that we need to add to this file:
1419 // * cbrt(expN(X)) -> expN(x/3)
1420 // * cbrt(sqrt(x)) -> pow(x,1/6)
1421 // * cbrt(sqrt(x)) -> pow(x,1/9)
1424 // * exp(log(x)) -> x
1427 // * log(exp(x)) -> x
1428 // * log(x**y) -> y*log(x)
1429 // * log(exp(y)) -> y*log(e)
1430 // * log(exp2(y)) -> y*log(2)
1431 // * log(exp10(y)) -> y*log(10)
1432 // * log(sqrt(x)) -> 0.5*log(x)
1433 // * log(pow(x,y)) -> y*log(x)
1435 // lround, lroundf, lroundl:
1436 // * lround(cnst) -> cnst'
1439 // * pow(exp(x),y) -> exp(x*y)
1440 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1441 // * pow(pow(x,y),z)-> pow(x,y*z)
1443 // round, roundf, roundl:
1444 // * round(cnst) -> cnst'
1447 // * signbit(cnst) -> cnst'
1448 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1450 // sqrt, sqrtf, sqrtl:
1451 // * sqrt(expN(x)) -> expN(x*0.5)
1452 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1453 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1456 // * strchr(p, 0) -> strlen(p)
1458 // * tan(atan(x)) -> x
1460 // trunc, truncf, truncl:
1461 // * trunc(cnst) -> cnst'