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/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/DataLayout.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
38 STATISTIC(NumSimplified, "Number of library calls simplified");
39 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41 //===----------------------------------------------------------------------===//
42 // Optimizer Base Class
43 //===----------------------------------------------------------------------===//
45 /// This class is the abstract base class for the set of optimizations that
46 /// corresponds to one library call.
48 class LibCallOptimization {
52 const TargetLibraryInfo *TLI;
55 LibCallOptimization() { }
56 virtual ~LibCallOptimization() {}
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
63 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
66 Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
68 Caller = CI->getParent()->getParent();
71 if (CI->getCalledFunction())
72 Context = &CI->getCalledFunction()->getContext();
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
78 return CallOptimizer(CI->getCalledFunction(), CI, B);
81 } // End anonymous namespace.
84 //===----------------------------------------------------------------------===//
86 //===----------------------------------------------------------------------===//
88 static bool CallHasFloatingPointArgument(const CallInst *CI) {
89 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
91 if ((*it)->getType()->isFloatingPointTy())
98 //===----------------------------------------------------------------------===//
99 // Integer Optimizations
100 //===----------------------------------------------------------------------===//
102 //===---------------------------------------===//
103 // 'isdigit' Optimizations
105 struct IsDigitOpt : public LibCallOptimization {
106 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
107 FunctionType *FT = Callee->getFunctionType();
108 // We require integer(i32)
109 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
110 !FT->getParamType(0)->isIntegerTy(32))
113 // isdigit(c) -> (c-'0') <u 10
114 Value *Op = CI->getArgOperand(0);
115 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
116 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
117 return B.CreateZExt(Op, CI->getType());
121 //===---------------------------------------===//
122 // 'isascii' Optimizations
124 struct IsAsciiOpt : public LibCallOptimization {
125 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
126 FunctionType *FT = Callee->getFunctionType();
127 // We require integer(i32)
128 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
129 !FT->getParamType(0)->isIntegerTy(32))
132 // isascii(c) -> c <u 128
133 Value *Op = CI->getArgOperand(0);
134 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
135 return B.CreateZExt(Op, CI->getType());
139 //===---------------------------------------===//
140 // 'abs', 'labs', 'llabs' Optimizations
142 struct AbsOpt : public LibCallOptimization {
143 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
144 FunctionType *FT = Callee->getFunctionType();
145 // We require integer(integer) where the types agree.
146 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
147 FT->getParamType(0) != FT->getReturnType())
150 // abs(x) -> x >s -1 ? x : -x
151 Value *Op = CI->getArgOperand(0);
152 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
154 Value *Neg = B.CreateNeg(Op, "neg");
155 return B.CreateSelect(Pos, Op, Neg);
160 //===---------------------------------------===//
161 // 'toascii' Optimizations
163 struct ToAsciiOpt : public LibCallOptimization {
164 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
165 FunctionType *FT = Callee->getFunctionType();
166 // We require i32(i32)
167 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
168 !FT->getParamType(0)->isIntegerTy(32))
171 // isascii(c) -> c & 0x7f
172 return B.CreateAnd(CI->getArgOperand(0),
173 ConstantInt::get(CI->getType(),0x7F));
177 //===----------------------------------------------------------------------===//
178 // Formatting and IO Optimizations
179 //===----------------------------------------------------------------------===//
181 //===---------------------------------------===//
182 // 'printf' Optimizations
184 struct PrintFOpt : public LibCallOptimization {
185 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
187 // Check for a fixed format string.
189 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
192 // Empty format string -> noop.
193 if (FormatStr.empty()) // Tolerate printf's declared void.
194 return CI->use_empty() ? (Value*)CI :
195 ConstantInt::get(CI->getType(), 0);
197 // Do not do any of the following transformations if the printf return value
198 // is used, in general the printf return value is not compatible with either
199 // putchar() or puts().
200 if (!CI->use_empty())
203 // printf("x") -> putchar('x'), even for '%'.
204 if (FormatStr.size() == 1) {
205 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
206 if (CI->use_empty() || !Res) return Res;
207 return B.CreateIntCast(Res, CI->getType(), true);
210 // printf("foo\n") --> puts("foo")
211 if (FormatStr[FormatStr.size()-1] == '\n' &&
212 FormatStr.find('%') == std::string::npos) { // no format characters.
213 // Create a string literal with no \n on it. We expect the constant merge
214 // pass to be run after this pass, to merge duplicate strings.
215 FormatStr = FormatStr.drop_back();
216 Value *GV = B.CreateGlobalString(FormatStr, "str");
217 Value *NewCI = EmitPutS(GV, B, TD, TLI);
218 return (CI->use_empty() || !NewCI) ?
220 ConstantInt::get(CI->getType(), FormatStr.size()+1);
223 // Optimize specific format strings.
224 // printf("%c", chr) --> putchar(chr)
225 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
226 CI->getArgOperand(1)->getType()->isIntegerTy()) {
227 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
229 if (CI->use_empty() || !Res) return Res;
230 return B.CreateIntCast(Res, CI->getType(), true);
233 // printf("%s\n", str) --> puts(str)
234 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
235 CI->getArgOperand(1)->getType()->isPointerTy()) {
236 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
241 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
242 // Require one fixed pointer argument and an integer/void result.
243 FunctionType *FT = Callee->getFunctionType();
244 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
245 !(FT->getReturnType()->isIntegerTy() ||
246 FT->getReturnType()->isVoidTy()))
249 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
253 // printf(format, ...) -> iprintf(format, ...) if no floating point
255 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
256 Module *M = B.GetInsertBlock()->getParent()->getParent();
257 Constant *IPrintFFn =
258 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
259 CallInst *New = cast<CallInst>(CI->clone());
260 New->setCalledFunction(IPrintFFn);
268 //===---------------------------------------===//
269 // 'sprintf' Optimizations
271 struct SPrintFOpt : public LibCallOptimization {
272 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
274 // Check for a fixed format string.
276 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
279 // If we just have a format string (nothing else crazy) transform it.
280 if (CI->getNumArgOperands() == 2) {
281 // Make sure there's no % in the constant array. We could try to handle
282 // %% -> % in the future if we cared.
283 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
284 if (FormatStr[i] == '%')
285 return 0; // we found a format specifier, bail out.
287 // These optimizations require DataLayout.
290 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
291 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
292 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
293 FormatStr.size() + 1), 1); // nul byte.
294 return ConstantInt::get(CI->getType(), FormatStr.size());
297 // The remaining optimizations require the format string to be "%s" or "%c"
298 // and have an extra operand.
299 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
300 CI->getNumArgOperands() < 3)
303 // Decode the second character of the format string.
304 if (FormatStr[1] == 'c') {
305 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
306 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
307 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
308 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
309 B.CreateStore(V, Ptr);
310 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
311 B.CreateStore(B.getInt8(0), Ptr);
313 return ConstantInt::get(CI->getType(), 1);
316 if (FormatStr[1] == 's') {
317 // These optimizations require DataLayout.
320 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
321 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
323 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
326 Value *IncLen = B.CreateAdd(Len,
327 ConstantInt::get(Len->getType(), 1),
329 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
331 // The sprintf result is the unincremented number of bytes in the string.
332 return B.CreateIntCast(Len, CI->getType(), false);
337 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
338 // Require two fixed pointer arguments and an integer result.
339 FunctionType *FT = Callee->getFunctionType();
340 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
341 !FT->getParamType(1)->isPointerTy() ||
342 !FT->getReturnType()->isIntegerTy())
345 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
349 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
351 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
352 Module *M = B.GetInsertBlock()->getParent()->getParent();
353 Constant *SIPrintFFn =
354 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
355 CallInst *New = cast<CallInst>(CI->clone());
356 New->setCalledFunction(SIPrintFFn);
364 //===---------------------------------------===//
365 // 'fwrite' Optimizations
367 struct FWriteOpt : public LibCallOptimization {
368 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
369 // Require a pointer, an integer, an integer, a pointer, returning integer.
370 FunctionType *FT = Callee->getFunctionType();
371 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
372 !FT->getParamType(1)->isIntegerTy() ||
373 !FT->getParamType(2)->isIntegerTy() ||
374 !FT->getParamType(3)->isPointerTy() ||
375 !FT->getReturnType()->isIntegerTy())
378 // Get the element size and count.
379 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
380 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
381 if (!SizeC || !CountC) return 0;
382 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
384 // If this is writing zero records, remove the call (it's a noop).
386 return ConstantInt::get(CI->getType(), 0);
388 // If this is writing one byte, turn it into fputc.
389 // This optimisation is only valid, if the return value is unused.
390 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
391 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
392 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
393 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
400 //===---------------------------------------===//
401 // 'fputs' Optimizations
403 struct FPutsOpt : public LibCallOptimization {
404 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
405 // These optimizations require DataLayout.
408 // Require two pointers. Also, we can't optimize if return value is used.
409 FunctionType *FT = Callee->getFunctionType();
410 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
411 !FT->getParamType(1)->isPointerTy() ||
415 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
416 uint64_t Len = GetStringLength(CI->getArgOperand(0));
418 // Known to have no uses (see above).
419 return EmitFWrite(CI->getArgOperand(0),
420 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
421 CI->getArgOperand(1), B, TD, TLI);
425 //===---------------------------------------===//
426 // 'fprintf' Optimizations
428 struct FPrintFOpt : public LibCallOptimization {
429 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
431 // All the optimizations depend on the format string.
433 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
436 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
437 if (CI->getNumArgOperands() == 2) {
438 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
439 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
440 return 0; // We found a format specifier.
442 // These optimizations require DataLayout.
445 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
446 ConstantInt::get(TD->getIntPtrType(*Context),
448 CI->getArgOperand(0), B, TD, TLI);
449 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
452 // The remaining optimizations require the format string to be "%s" or "%c"
453 // and have an extra operand.
454 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
455 CI->getNumArgOperands() < 3)
458 // Decode the second character of the format string.
459 if (FormatStr[1] == 'c') {
460 // fprintf(F, "%c", chr) --> fputc(chr, F)
461 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
462 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
464 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
467 if (FormatStr[1] == 's') {
468 // fprintf(F, "%s", str) --> fputs(str, F)
469 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
471 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
476 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
477 // Require two fixed paramters as pointers and integer result.
478 FunctionType *FT = Callee->getFunctionType();
479 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
480 !FT->getParamType(1)->isPointerTy() ||
481 !FT->getReturnType()->isIntegerTy())
484 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
488 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
489 // floating point arguments.
490 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
491 Module *M = B.GetInsertBlock()->getParent()->getParent();
492 Constant *FIPrintFFn =
493 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
494 CallInst *New = cast<CallInst>(CI->clone());
495 New->setCalledFunction(FIPrintFFn);
503 //===---------------------------------------===//
504 // 'puts' Optimizations
506 struct PutsOpt : public LibCallOptimization {
507 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
508 // Require one fixed pointer argument and an integer/void result.
509 FunctionType *FT = Callee->getFunctionType();
510 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
511 !(FT->getReturnType()->isIntegerTy() ||
512 FT->getReturnType()->isVoidTy()))
515 // Check for a constant string.
517 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
520 if (Str.empty() && CI->use_empty()) {
521 // puts("") -> putchar('\n')
522 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
523 if (CI->use_empty() || !Res) return Res;
524 return B.CreateIntCast(Res, CI->getType(), true);
531 } // end anonymous namespace.
533 //===----------------------------------------------------------------------===//
534 // SimplifyLibCalls Pass Implementation
535 //===----------------------------------------------------------------------===//
538 /// This pass optimizes well known library functions from libc and libm.
540 class SimplifyLibCalls : public FunctionPass {
541 TargetLibraryInfo *TLI;
543 StringMap<LibCallOptimization*> Optimizations;
544 // Integer Optimizations
545 AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
547 // Formatting and IO Optimizations
548 SPrintFOpt SPrintF; PrintFOpt PrintF;
549 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
552 bool Modified; // This is only used by doInitialization.
554 static char ID; // Pass identification
555 SimplifyLibCalls() : FunctionPass(ID) {
556 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
558 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
559 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
561 void InitOptimizations();
562 bool runOnFunction(Function &F);
564 void setDoesNotAccessMemory(Function &F);
565 void setOnlyReadsMemory(Function &F);
566 void setDoesNotThrow(Function &F);
567 void setDoesNotCapture(Function &F, unsigned n);
568 void setDoesNotAlias(Function &F, unsigned n);
569 bool doInitialization(Module &M);
571 void inferPrototypeAttributes(Function &F);
572 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
573 AU.addRequired<TargetLibraryInfo>();
576 } // end anonymous namespace.
578 char SimplifyLibCalls::ID = 0;
580 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
581 "Simplify well-known library calls", false, false)
582 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
583 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
584 "Simplify well-known library calls", false, false)
586 // Public interface to the Simplify LibCalls pass.
587 FunctionPass *llvm::createSimplifyLibCallsPass() {
588 return new SimplifyLibCalls();
591 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
593 Optimizations[TLI->getName(F)] = Opt;
596 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
597 LibCallOptimization* Opt) {
598 if (TLI->has(F1) && TLI->has(F2))
599 Optimizations[TLI->getName(F1)] = Opt;
602 /// Optimizations - Populate the Optimizations map with all the optimizations
604 void SimplifyLibCalls::InitOptimizations() {
605 // Integer Optimizations
606 Optimizations["abs"] = &Abs;
607 Optimizations["labs"] = &Abs;
608 Optimizations["llabs"] = &Abs;
609 Optimizations["isdigit"] = &IsDigit;
610 Optimizations["isascii"] = &IsAscii;
611 Optimizations["toascii"] = &ToAscii;
613 // Formatting and IO Optimizations
614 Optimizations["sprintf"] = &SPrintF;
615 Optimizations["printf"] = &PrintF;
616 AddOpt(LibFunc::fwrite, &FWrite);
617 AddOpt(LibFunc::fputs, &FPuts);
618 Optimizations["fprintf"] = &FPrintF;
619 Optimizations["puts"] = &Puts;
623 /// runOnFunction - Top level algorithm.
625 bool SimplifyLibCalls::runOnFunction(Function &F) {
626 TLI = &getAnalysis<TargetLibraryInfo>();
628 if (Optimizations.empty())
631 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
633 IRBuilder<> Builder(F.getContext());
635 bool Changed = false;
636 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
637 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
639 CallInst *CI = dyn_cast<CallInst>(I++);
642 // Ignore indirect calls and calls to non-external functions.
643 Function *Callee = CI->getCalledFunction();
644 if (Callee == 0 || !Callee->isDeclaration() ||
645 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
648 // Ignore unknown calls.
649 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
652 // Set the builder to the instruction after the call.
653 Builder.SetInsertPoint(BB, I);
655 // Use debug location of CI for all new instructions.
656 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
658 // Try to optimize this call.
659 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
660 if (Result == 0) continue;
662 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
663 dbgs() << " into: " << *Result << "\n");
665 // Something changed!
669 // Inspect the instruction after the call (which was potentially just
673 if (CI != Result && !CI->use_empty()) {
674 CI->replaceAllUsesWith(Result);
675 if (!Result->hasName())
676 Result->takeName(CI);
678 CI->eraseFromParent();
684 // Utility methods for doInitialization.
686 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
687 if (!F.doesNotAccessMemory()) {
688 F.setDoesNotAccessMemory();
693 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
694 if (!F.onlyReadsMemory()) {
695 F.setOnlyReadsMemory();
700 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
701 if (!F.doesNotThrow()) {
707 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
708 if (!F.doesNotCapture(n)) {
709 F.setDoesNotCapture(n);
714 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
715 if (!F.doesNotAlias(n)) {
716 F.setDoesNotAlias(n);
723 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
724 FunctionType *FTy = F.getFunctionType();
726 StringRef Name = F.getName();
729 if (Name == "strlen") {
730 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
732 setOnlyReadsMemory(F);
734 setDoesNotCapture(F, 1);
735 } else if (Name == "strchr" ||
737 if (FTy->getNumParams() != 2 ||
738 !FTy->getParamType(0)->isPointerTy() ||
739 !FTy->getParamType(1)->isIntegerTy())
741 setOnlyReadsMemory(F);
743 } else if (Name == "strcpy" ||
755 Name == "strtoull") {
756 if (FTy->getNumParams() < 2 ||
757 !FTy->getParamType(1)->isPointerTy())
760 setDoesNotCapture(F, 2);
761 } else if (Name == "strxfrm") {
762 if (FTy->getNumParams() != 3 ||
763 !FTy->getParamType(0)->isPointerTy() ||
764 !FTy->getParamType(1)->isPointerTy())
767 setDoesNotCapture(F, 1);
768 setDoesNotCapture(F, 2);
769 } else if (Name == "strcmp" ||
774 Name == "strcasecmp" ||
775 Name == "strncasecmp") {
776 if (FTy->getNumParams() < 2 ||
777 !FTy->getParamType(0)->isPointerTy() ||
778 !FTy->getParamType(1)->isPointerTy())
780 setOnlyReadsMemory(F);
782 setDoesNotCapture(F, 1);
783 setDoesNotCapture(F, 2);
784 } else if (Name == "strstr" ||
786 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
788 setOnlyReadsMemory(F);
790 setDoesNotCapture(F, 2);
791 } else if (Name == "strtok" ||
792 Name == "strtok_r") {
793 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
796 setDoesNotCapture(F, 2);
797 } else if (Name == "scanf" ||
800 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
803 setDoesNotCapture(F, 1);
804 } else if (Name == "strdup" ||
806 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
807 !FTy->getParamType(0)->isPointerTy())
810 setDoesNotAlias(F, 0);
811 setDoesNotCapture(F, 1);
812 } else if (Name == "stat" ||
816 if (FTy->getNumParams() < 2 ||
817 !FTy->getParamType(0)->isPointerTy() ||
818 !FTy->getParamType(1)->isPointerTy())
821 setDoesNotCapture(F, 1);
822 setDoesNotCapture(F, 2);
823 } else if (Name == "snprintf") {
824 if (FTy->getNumParams() != 3 ||
825 !FTy->getParamType(0)->isPointerTy() ||
826 !FTy->getParamType(2)->isPointerTy())
829 setDoesNotCapture(F, 1);
830 setDoesNotCapture(F, 3);
831 } else if (Name == "setitimer") {
832 if (FTy->getNumParams() != 3 ||
833 !FTy->getParamType(1)->isPointerTy() ||
834 !FTy->getParamType(2)->isPointerTy())
837 setDoesNotCapture(F, 2);
838 setDoesNotCapture(F, 3);
839 } else if (Name == "system") {
840 if (FTy->getNumParams() != 1 ||
841 !FTy->getParamType(0)->isPointerTy())
843 // May throw; "system" is a valid pthread cancellation point.
844 setDoesNotCapture(F, 1);
848 if (Name == "malloc") {
849 if (FTy->getNumParams() != 1 ||
850 !FTy->getReturnType()->isPointerTy())
853 setDoesNotAlias(F, 0);
854 } else if (Name == "memcmp") {
855 if (FTy->getNumParams() != 3 ||
856 !FTy->getParamType(0)->isPointerTy() ||
857 !FTy->getParamType(1)->isPointerTy())
859 setOnlyReadsMemory(F);
861 setDoesNotCapture(F, 1);
862 setDoesNotCapture(F, 2);
863 } else if (Name == "memchr" ||
865 if (FTy->getNumParams() != 3)
867 setOnlyReadsMemory(F);
869 } else if (Name == "modf" ||
875 if (FTy->getNumParams() < 2 ||
876 !FTy->getParamType(1)->isPointerTy())
879 setDoesNotCapture(F, 2);
880 } else if (Name == "memalign") {
881 if (!FTy->getReturnType()->isPointerTy())
883 setDoesNotAlias(F, 0);
884 } else if (Name == "mkdir" ||
886 if (FTy->getNumParams() == 0 ||
887 !FTy->getParamType(0)->isPointerTy())
890 setDoesNotCapture(F, 1);
894 if (Name == "realloc") {
895 if (FTy->getNumParams() != 2 ||
896 !FTy->getParamType(0)->isPointerTy() ||
897 !FTy->getReturnType()->isPointerTy())
900 setDoesNotAlias(F, 0);
901 setDoesNotCapture(F, 1);
902 } else if (Name == "read") {
903 if (FTy->getNumParams() != 3 ||
904 !FTy->getParamType(1)->isPointerTy())
906 // May throw; "read" is a valid pthread cancellation point.
907 setDoesNotCapture(F, 2);
908 } else if (Name == "rmdir" ||
911 Name == "realpath") {
912 if (FTy->getNumParams() < 1 ||
913 !FTy->getParamType(0)->isPointerTy())
916 setDoesNotCapture(F, 1);
917 } else if (Name == "rename" ||
918 Name == "readlink") {
919 if (FTy->getNumParams() < 2 ||
920 !FTy->getParamType(0)->isPointerTy() ||
921 !FTy->getParamType(1)->isPointerTy())
924 setDoesNotCapture(F, 1);
925 setDoesNotCapture(F, 2);
929 if (Name == "write") {
930 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
932 // May throw; "write" is a valid pthread cancellation point.
933 setDoesNotCapture(F, 2);
937 if (Name == "bcopy") {
938 if (FTy->getNumParams() != 3 ||
939 !FTy->getParamType(0)->isPointerTy() ||
940 !FTy->getParamType(1)->isPointerTy())
943 setDoesNotCapture(F, 1);
944 setDoesNotCapture(F, 2);
945 } else if (Name == "bcmp") {
946 if (FTy->getNumParams() != 3 ||
947 !FTy->getParamType(0)->isPointerTy() ||
948 !FTy->getParamType(1)->isPointerTy())
951 setOnlyReadsMemory(F);
952 setDoesNotCapture(F, 1);
953 setDoesNotCapture(F, 2);
954 } else if (Name == "bzero") {
955 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
958 setDoesNotCapture(F, 1);
962 if (Name == "calloc") {
963 if (FTy->getNumParams() != 2 ||
964 !FTy->getReturnType()->isPointerTy())
967 setDoesNotAlias(F, 0);
968 } else if (Name == "chmod" ||
971 Name == "clearerr" ||
972 Name == "closedir") {
973 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
976 setDoesNotCapture(F, 1);
980 if (Name == "atoi" ||
984 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
987 setOnlyReadsMemory(F);
988 setDoesNotCapture(F, 1);
989 } else if (Name == "access") {
990 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
993 setDoesNotCapture(F, 1);
997 if (Name == "fopen") {
998 if (FTy->getNumParams() != 2 ||
999 !FTy->getReturnType()->isPointerTy() ||
1000 !FTy->getParamType(0)->isPointerTy() ||
1001 !FTy->getParamType(1)->isPointerTy())
1004 setDoesNotAlias(F, 0);
1005 setDoesNotCapture(F, 1);
1006 setDoesNotCapture(F, 2);
1007 } else if (Name == "fdopen") {
1008 if (FTy->getNumParams() != 2 ||
1009 !FTy->getReturnType()->isPointerTy() ||
1010 !FTy->getParamType(1)->isPointerTy())
1013 setDoesNotAlias(F, 0);
1014 setDoesNotCapture(F, 2);
1015 } else if (Name == "feof" ||
1025 Name == "fsetpos" ||
1026 Name == "flockfile" ||
1027 Name == "funlockfile" ||
1028 Name == "ftrylockfile") {
1029 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1032 setDoesNotCapture(F, 1);
1033 } else if (Name == "ferror") {
1034 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1037 setDoesNotCapture(F, 1);
1038 setOnlyReadsMemory(F);
1039 } else if (Name == "fputc" ||
1044 Name == "fstatvfs") {
1045 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1048 setDoesNotCapture(F, 2);
1049 } else if (Name == "fgets") {
1050 if (FTy->getNumParams() != 3 ||
1051 !FTy->getParamType(0)->isPointerTy() ||
1052 !FTy->getParamType(2)->isPointerTy())
1055 setDoesNotCapture(F, 3);
1056 } else if (Name == "fread" ||
1058 if (FTy->getNumParams() != 4 ||
1059 !FTy->getParamType(0)->isPointerTy() ||
1060 !FTy->getParamType(3)->isPointerTy())
1063 setDoesNotCapture(F, 1);
1064 setDoesNotCapture(F, 4);
1065 } else if (Name == "fputs" ||
1067 Name == "fprintf" ||
1068 Name == "fgetpos") {
1069 if (FTy->getNumParams() < 2 ||
1070 !FTy->getParamType(0)->isPointerTy() ||
1071 !FTy->getParamType(1)->isPointerTy())
1074 setDoesNotCapture(F, 1);
1075 setDoesNotCapture(F, 2);
1079 if (Name == "getc" ||
1080 Name == "getlogin_r" ||
1081 Name == "getc_unlocked") {
1082 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1085 setDoesNotCapture(F, 1);
1086 } else if (Name == "getenv") {
1087 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1090 setOnlyReadsMemory(F);
1091 setDoesNotCapture(F, 1);
1092 } else if (Name == "gets" ||
1093 Name == "getchar") {
1095 } else if (Name == "getitimer") {
1096 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1099 setDoesNotCapture(F, 2);
1100 } else if (Name == "getpwnam") {
1101 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1104 setDoesNotCapture(F, 1);
1108 if (Name == "ungetc") {
1109 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1112 setDoesNotCapture(F, 2);
1113 } else if (Name == "uname" ||
1115 Name == "unsetenv") {
1116 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1119 setDoesNotCapture(F, 1);
1120 } else if (Name == "utime" ||
1122 if (FTy->getNumParams() != 2 ||
1123 !FTy->getParamType(0)->isPointerTy() ||
1124 !FTy->getParamType(1)->isPointerTy())
1127 setDoesNotCapture(F, 1);
1128 setDoesNotCapture(F, 2);
1132 if (Name == "putc") {
1133 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1136 setDoesNotCapture(F, 2);
1137 } else if (Name == "puts" ||
1140 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1143 setDoesNotCapture(F, 1);
1144 } else if (Name == "pread" ||
1146 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1148 // May throw; these are valid pthread cancellation points.
1149 setDoesNotCapture(F, 2);
1150 } else if (Name == "putchar") {
1152 } else if (Name == "popen") {
1153 if (FTy->getNumParams() != 2 ||
1154 !FTy->getReturnType()->isPointerTy() ||
1155 !FTy->getParamType(0)->isPointerTy() ||
1156 !FTy->getParamType(1)->isPointerTy())
1159 setDoesNotAlias(F, 0);
1160 setDoesNotCapture(F, 1);
1161 setDoesNotCapture(F, 2);
1162 } else if (Name == "pclose") {
1163 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1166 setDoesNotCapture(F, 1);
1170 if (Name == "vscanf") {
1171 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1174 setDoesNotCapture(F, 1);
1175 } else if (Name == "vsscanf" ||
1176 Name == "vfscanf") {
1177 if (FTy->getNumParams() != 3 ||
1178 !FTy->getParamType(1)->isPointerTy() ||
1179 !FTy->getParamType(2)->isPointerTy())
1182 setDoesNotCapture(F, 1);
1183 setDoesNotCapture(F, 2);
1184 } else if (Name == "valloc") {
1185 if (!FTy->getReturnType()->isPointerTy())
1188 setDoesNotAlias(F, 0);
1189 } else if (Name == "vprintf") {
1190 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1193 setDoesNotCapture(F, 1);
1194 } else if (Name == "vfprintf" ||
1195 Name == "vsprintf") {
1196 if (FTy->getNumParams() != 3 ||
1197 !FTy->getParamType(0)->isPointerTy() ||
1198 !FTy->getParamType(1)->isPointerTy())
1201 setDoesNotCapture(F, 1);
1202 setDoesNotCapture(F, 2);
1203 } else if (Name == "vsnprintf") {
1204 if (FTy->getNumParams() != 4 ||
1205 !FTy->getParamType(0)->isPointerTy() ||
1206 !FTy->getParamType(2)->isPointerTy())
1209 setDoesNotCapture(F, 1);
1210 setDoesNotCapture(F, 3);
1214 if (Name == "open") {
1215 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1217 // May throw; "open" is a valid pthread cancellation point.
1218 setDoesNotCapture(F, 1);
1219 } else if (Name == "opendir") {
1220 if (FTy->getNumParams() != 1 ||
1221 !FTy->getReturnType()->isPointerTy() ||
1222 !FTy->getParamType(0)->isPointerTy())
1225 setDoesNotAlias(F, 0);
1226 setDoesNotCapture(F, 1);
1230 if (Name == "tmpfile") {
1231 if (!FTy->getReturnType()->isPointerTy())
1234 setDoesNotAlias(F, 0);
1235 } else if (Name == "times") {
1236 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1239 setDoesNotCapture(F, 1);
1243 if (Name == "htonl" ||
1246 setDoesNotAccessMemory(F);
1250 if (Name == "ntohl" ||
1253 setDoesNotAccessMemory(F);
1257 if (Name == "lstat") {
1258 if (FTy->getNumParams() != 2 ||
1259 !FTy->getParamType(0)->isPointerTy() ||
1260 !FTy->getParamType(1)->isPointerTy())
1263 setDoesNotCapture(F, 1);
1264 setDoesNotCapture(F, 2);
1265 } else if (Name == "lchown") {
1266 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1269 setDoesNotCapture(F, 1);
1273 if (Name == "qsort") {
1274 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1276 // May throw; places call through function pointer.
1277 setDoesNotCapture(F, 4);
1281 if (Name == "__strdup" ||
1282 Name == "__strndup") {
1283 if (FTy->getNumParams() < 1 ||
1284 !FTy->getReturnType()->isPointerTy() ||
1285 !FTy->getParamType(0)->isPointerTy())
1288 setDoesNotAlias(F, 0);
1289 setDoesNotCapture(F, 1);
1290 } else if (Name == "__strtok_r") {
1291 if (FTy->getNumParams() != 3 ||
1292 !FTy->getParamType(1)->isPointerTy())
1295 setDoesNotCapture(F, 2);
1296 } else if (Name == "_IO_getc") {
1297 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1300 setDoesNotCapture(F, 1);
1301 } else if (Name == "_IO_putc") {
1302 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1305 setDoesNotCapture(F, 2);
1309 if (Name == "\1__isoc99_scanf") {
1310 if (FTy->getNumParams() < 1 ||
1311 !FTy->getParamType(0)->isPointerTy())
1314 setDoesNotCapture(F, 1);
1315 } else if (Name == "\1stat64" ||
1316 Name == "\1lstat64" ||
1317 Name == "\1statvfs64" ||
1318 Name == "\1__isoc99_sscanf") {
1319 if (FTy->getNumParams() < 1 ||
1320 !FTy->getParamType(0)->isPointerTy() ||
1321 !FTy->getParamType(1)->isPointerTy())
1324 setDoesNotCapture(F, 1);
1325 setDoesNotCapture(F, 2);
1326 } else if (Name == "\1fopen64") {
1327 if (FTy->getNumParams() != 2 ||
1328 !FTy->getReturnType()->isPointerTy() ||
1329 !FTy->getParamType(0)->isPointerTy() ||
1330 !FTy->getParamType(1)->isPointerTy())
1333 setDoesNotAlias(F, 0);
1334 setDoesNotCapture(F, 1);
1335 setDoesNotCapture(F, 2);
1336 } else if (Name == "\1fseeko64" ||
1337 Name == "\1ftello64") {
1338 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1341 setDoesNotCapture(F, 1);
1342 } else if (Name == "\1tmpfile64") {
1343 if (!FTy->getReturnType()->isPointerTy())
1346 setDoesNotAlias(F, 0);
1347 } else if (Name == "\1fstat64" ||
1348 Name == "\1fstatvfs64") {
1349 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1352 setDoesNotCapture(F, 2);
1353 } else if (Name == "\1open64") {
1354 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1356 // May throw; "open" is a valid pthread cancellation point.
1357 setDoesNotCapture(F, 1);
1363 /// doInitialization - Add attributes to well-known functions.
1365 bool SimplifyLibCalls::doInitialization(Module &M) {
1367 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1369 if (F.isDeclaration() && F.hasName())
1370 inferPrototypeAttributes(F);
1376 // Additional cases that we need to add to this file:
1379 // * cbrt(expN(X)) -> expN(x/3)
1380 // * cbrt(sqrt(x)) -> pow(x,1/6)
1381 // * cbrt(sqrt(x)) -> pow(x,1/9)
1384 // * exp(log(x)) -> x
1387 // * log(exp(x)) -> x
1388 // * log(x**y) -> y*log(x)
1389 // * log(exp(y)) -> y*log(e)
1390 // * log(exp2(y)) -> y*log(2)
1391 // * log(exp10(y)) -> y*log(10)
1392 // * log(sqrt(x)) -> 0.5*log(x)
1393 // * log(pow(x,y)) -> y*log(x)
1395 // lround, lroundf, lroundl:
1396 // * lround(cnst) -> cnst'
1399 // * pow(exp(x),y) -> exp(x*y)
1400 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1401 // * pow(pow(x,y),z)-> pow(x,y*z)
1403 // round, roundf, roundl:
1404 // * round(cnst) -> cnst'
1407 // * signbit(cnst) -> cnst'
1408 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1410 // sqrt, sqrtf, sqrtl:
1411 // * sqrt(expN(x)) -> expN(x*0.5)
1412 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1413 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1416 // * strchr(p, 0) -> strlen(p)
1418 // * tan(atan(x)) -> x
1420 // trunc, truncf, truncl:
1421 // * trunc(cnst) -> cnst'