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 // 'toascii' Optimizations
105 struct ToAsciiOpt : public LibCallOptimization {
106 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
107 FunctionType *FT = Callee->getFunctionType();
108 // We require i32(i32)
109 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
110 !FT->getParamType(0)->isIntegerTy(32))
113 // isascii(c) -> c & 0x7f
114 return B.CreateAnd(CI->getArgOperand(0),
115 ConstantInt::get(CI->getType(),0x7F));
119 //===----------------------------------------------------------------------===//
120 // Formatting and IO Optimizations
121 //===----------------------------------------------------------------------===//
123 //===---------------------------------------===//
124 // 'printf' Optimizations
126 struct PrintFOpt : public LibCallOptimization {
127 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
129 // Check for a fixed format string.
131 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
134 // Empty format string -> noop.
135 if (FormatStr.empty()) // Tolerate printf's declared void.
136 return CI->use_empty() ? (Value*)CI :
137 ConstantInt::get(CI->getType(), 0);
139 // Do not do any of the following transformations if the printf return value
140 // is used, in general the printf return value is not compatible with either
141 // putchar() or puts().
142 if (!CI->use_empty())
145 // printf("x") -> putchar('x'), even for '%'.
146 if (FormatStr.size() == 1) {
147 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
148 if (CI->use_empty() || !Res) return Res;
149 return B.CreateIntCast(Res, CI->getType(), true);
152 // printf("foo\n") --> puts("foo")
153 if (FormatStr[FormatStr.size()-1] == '\n' &&
154 FormatStr.find('%') == std::string::npos) { // no format characters.
155 // Create a string literal with no \n on it. We expect the constant merge
156 // pass to be run after this pass, to merge duplicate strings.
157 FormatStr = FormatStr.drop_back();
158 Value *GV = B.CreateGlobalString(FormatStr, "str");
159 Value *NewCI = EmitPutS(GV, B, TD, TLI);
160 return (CI->use_empty() || !NewCI) ?
162 ConstantInt::get(CI->getType(), FormatStr.size()+1);
165 // Optimize specific format strings.
166 // printf("%c", chr) --> putchar(chr)
167 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
168 CI->getArgOperand(1)->getType()->isIntegerTy()) {
169 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
171 if (CI->use_empty() || !Res) return Res;
172 return B.CreateIntCast(Res, CI->getType(), true);
175 // printf("%s\n", str) --> puts(str)
176 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
177 CI->getArgOperand(1)->getType()->isPointerTy()) {
178 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
183 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
184 // Require one fixed pointer argument and an integer/void result.
185 FunctionType *FT = Callee->getFunctionType();
186 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
187 !(FT->getReturnType()->isIntegerTy() ||
188 FT->getReturnType()->isVoidTy()))
191 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
195 // printf(format, ...) -> iprintf(format, ...) if no floating point
197 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
198 Module *M = B.GetInsertBlock()->getParent()->getParent();
199 Constant *IPrintFFn =
200 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
201 CallInst *New = cast<CallInst>(CI->clone());
202 New->setCalledFunction(IPrintFFn);
210 //===---------------------------------------===//
211 // 'sprintf' Optimizations
213 struct SPrintFOpt : public LibCallOptimization {
214 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
216 // Check for a fixed format string.
218 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
221 // If we just have a format string (nothing else crazy) transform it.
222 if (CI->getNumArgOperands() == 2) {
223 // Make sure there's no % in the constant array. We could try to handle
224 // %% -> % in the future if we cared.
225 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
226 if (FormatStr[i] == '%')
227 return 0; // we found a format specifier, bail out.
229 // These optimizations require DataLayout.
232 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
233 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
234 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
235 FormatStr.size() + 1), 1); // nul byte.
236 return ConstantInt::get(CI->getType(), FormatStr.size());
239 // The remaining optimizations require the format string to be "%s" or "%c"
240 // and have an extra operand.
241 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
242 CI->getNumArgOperands() < 3)
245 // Decode the second character of the format string.
246 if (FormatStr[1] == 'c') {
247 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
248 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
249 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
250 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
251 B.CreateStore(V, Ptr);
252 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
253 B.CreateStore(B.getInt8(0), Ptr);
255 return ConstantInt::get(CI->getType(), 1);
258 if (FormatStr[1] == 's') {
259 // These optimizations require DataLayout.
262 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
263 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
265 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
268 Value *IncLen = B.CreateAdd(Len,
269 ConstantInt::get(Len->getType(), 1),
271 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
273 // The sprintf result is the unincremented number of bytes in the string.
274 return B.CreateIntCast(Len, CI->getType(), false);
279 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
280 // Require two fixed pointer arguments and an integer result.
281 FunctionType *FT = Callee->getFunctionType();
282 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
283 !FT->getParamType(1)->isPointerTy() ||
284 !FT->getReturnType()->isIntegerTy())
287 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
291 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
293 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
294 Module *M = B.GetInsertBlock()->getParent()->getParent();
295 Constant *SIPrintFFn =
296 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
297 CallInst *New = cast<CallInst>(CI->clone());
298 New->setCalledFunction(SIPrintFFn);
306 //===---------------------------------------===//
307 // 'fwrite' Optimizations
309 struct FWriteOpt : public LibCallOptimization {
310 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
311 // Require a pointer, an integer, an integer, a pointer, returning integer.
312 FunctionType *FT = Callee->getFunctionType();
313 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
314 !FT->getParamType(1)->isIntegerTy() ||
315 !FT->getParamType(2)->isIntegerTy() ||
316 !FT->getParamType(3)->isPointerTy() ||
317 !FT->getReturnType()->isIntegerTy())
320 // Get the element size and count.
321 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
322 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
323 if (!SizeC || !CountC) return 0;
324 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
326 // If this is writing zero records, remove the call (it's a noop).
328 return ConstantInt::get(CI->getType(), 0);
330 // If this is writing one byte, turn it into fputc.
331 // This optimisation is only valid, if the return value is unused.
332 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
333 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
334 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
335 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
342 //===---------------------------------------===//
343 // 'fputs' Optimizations
345 struct FPutsOpt : public LibCallOptimization {
346 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
347 // These optimizations require DataLayout.
350 // Require two pointers. Also, we can't optimize if return value is used.
351 FunctionType *FT = Callee->getFunctionType();
352 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
353 !FT->getParamType(1)->isPointerTy() ||
357 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
358 uint64_t Len = GetStringLength(CI->getArgOperand(0));
360 // Known to have no uses (see above).
361 return EmitFWrite(CI->getArgOperand(0),
362 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
363 CI->getArgOperand(1), B, TD, TLI);
367 //===---------------------------------------===//
368 // 'fprintf' Optimizations
370 struct FPrintFOpt : public LibCallOptimization {
371 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
373 // All the optimizations depend on the format string.
375 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
378 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
379 if (CI->getNumArgOperands() == 2) {
380 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
381 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
382 return 0; // We found a format specifier.
384 // These optimizations require DataLayout.
387 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
388 ConstantInt::get(TD->getIntPtrType(*Context),
390 CI->getArgOperand(0), B, TD, TLI);
391 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
394 // The remaining optimizations require the format string to be "%s" or "%c"
395 // and have an extra operand.
396 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
397 CI->getNumArgOperands() < 3)
400 // Decode the second character of the format string.
401 if (FormatStr[1] == 'c') {
402 // fprintf(F, "%c", chr) --> fputc(chr, F)
403 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
404 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
406 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
409 if (FormatStr[1] == 's') {
410 // fprintf(F, "%s", str) --> fputs(str, F)
411 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
413 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
418 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
419 // Require two fixed paramters as pointers and integer result.
420 FunctionType *FT = Callee->getFunctionType();
421 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
422 !FT->getParamType(1)->isPointerTy() ||
423 !FT->getReturnType()->isIntegerTy())
426 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
430 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
431 // floating point arguments.
432 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
433 Module *M = B.GetInsertBlock()->getParent()->getParent();
434 Constant *FIPrintFFn =
435 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
436 CallInst *New = cast<CallInst>(CI->clone());
437 New->setCalledFunction(FIPrintFFn);
445 //===---------------------------------------===//
446 // 'puts' Optimizations
448 struct PutsOpt : public LibCallOptimization {
449 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
450 // Require one fixed pointer argument and an integer/void result.
451 FunctionType *FT = Callee->getFunctionType();
452 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
453 !(FT->getReturnType()->isIntegerTy() ||
454 FT->getReturnType()->isVoidTy()))
457 // Check for a constant string.
459 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
462 if (Str.empty() && CI->use_empty()) {
463 // puts("") -> putchar('\n')
464 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
465 if (CI->use_empty() || !Res) return Res;
466 return B.CreateIntCast(Res, CI->getType(), true);
473 } // end anonymous namespace.
475 //===----------------------------------------------------------------------===//
476 // SimplifyLibCalls Pass Implementation
477 //===----------------------------------------------------------------------===//
480 /// This pass optimizes well known library functions from libc and libm.
482 class SimplifyLibCalls : public FunctionPass {
483 TargetLibraryInfo *TLI;
485 StringMap<LibCallOptimization*> Optimizations;
486 // Integer Optimizations
488 // Formatting and IO Optimizations
489 SPrintFOpt SPrintF; PrintFOpt PrintF;
490 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
493 bool Modified; // This is only used by doInitialization.
495 static char ID; // Pass identification
496 SimplifyLibCalls() : FunctionPass(ID) {
497 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
499 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
500 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
502 void InitOptimizations();
503 bool runOnFunction(Function &F);
505 void setDoesNotAccessMemory(Function &F);
506 void setOnlyReadsMemory(Function &F);
507 void setDoesNotThrow(Function &F);
508 void setDoesNotCapture(Function &F, unsigned n);
509 void setDoesNotAlias(Function &F, unsigned n);
510 bool doInitialization(Module &M);
512 void inferPrototypeAttributes(Function &F);
513 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
514 AU.addRequired<TargetLibraryInfo>();
517 } // end anonymous namespace.
519 char SimplifyLibCalls::ID = 0;
521 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
522 "Simplify well-known library calls", false, false)
523 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
524 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
525 "Simplify well-known library calls", false, false)
527 // Public interface to the Simplify LibCalls pass.
528 FunctionPass *llvm::createSimplifyLibCallsPass() {
529 return new SimplifyLibCalls();
532 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
534 Optimizations[TLI->getName(F)] = Opt;
537 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
538 LibCallOptimization* Opt) {
539 if (TLI->has(F1) && TLI->has(F2))
540 Optimizations[TLI->getName(F1)] = Opt;
543 /// Optimizations - Populate the Optimizations map with all the optimizations
545 void SimplifyLibCalls::InitOptimizations() {
546 // Integer Optimizations
547 Optimizations["toascii"] = &ToAscii;
549 // Formatting and IO Optimizations
550 Optimizations["sprintf"] = &SPrintF;
551 Optimizations["printf"] = &PrintF;
552 AddOpt(LibFunc::fwrite, &FWrite);
553 AddOpt(LibFunc::fputs, &FPuts);
554 Optimizations["fprintf"] = &FPrintF;
555 Optimizations["puts"] = &Puts;
559 /// runOnFunction - Top level algorithm.
561 bool SimplifyLibCalls::runOnFunction(Function &F) {
562 TLI = &getAnalysis<TargetLibraryInfo>();
564 if (Optimizations.empty())
567 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
569 IRBuilder<> Builder(F.getContext());
571 bool Changed = false;
572 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
573 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
575 CallInst *CI = dyn_cast<CallInst>(I++);
578 // Ignore indirect calls and calls to non-external functions.
579 Function *Callee = CI->getCalledFunction();
580 if (Callee == 0 || !Callee->isDeclaration() ||
581 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
584 // Ignore unknown calls.
585 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
588 // Set the builder to the instruction after the call.
589 Builder.SetInsertPoint(BB, I);
591 // Use debug location of CI for all new instructions.
592 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
594 // Try to optimize this call.
595 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
596 if (Result == 0) continue;
598 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
599 dbgs() << " into: " << *Result << "\n");
601 // Something changed!
605 // Inspect the instruction after the call (which was potentially just
609 if (CI != Result && !CI->use_empty()) {
610 CI->replaceAllUsesWith(Result);
611 if (!Result->hasName())
612 Result->takeName(CI);
614 CI->eraseFromParent();
620 // Utility methods for doInitialization.
622 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
623 if (!F.doesNotAccessMemory()) {
624 F.setDoesNotAccessMemory();
629 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
630 if (!F.onlyReadsMemory()) {
631 F.setOnlyReadsMemory();
636 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
637 if (!F.doesNotThrow()) {
643 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
644 if (!F.doesNotCapture(n)) {
645 F.setDoesNotCapture(n);
650 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
651 if (!F.doesNotAlias(n)) {
652 F.setDoesNotAlias(n);
659 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
660 FunctionType *FTy = F.getFunctionType();
662 StringRef Name = F.getName();
665 if (Name == "strlen") {
666 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
668 setOnlyReadsMemory(F);
670 setDoesNotCapture(F, 1);
671 } else if (Name == "strchr" ||
673 if (FTy->getNumParams() != 2 ||
674 !FTy->getParamType(0)->isPointerTy() ||
675 !FTy->getParamType(1)->isIntegerTy())
677 setOnlyReadsMemory(F);
679 } else if (Name == "strcpy" ||
691 Name == "strtoull") {
692 if (FTy->getNumParams() < 2 ||
693 !FTy->getParamType(1)->isPointerTy())
696 setDoesNotCapture(F, 2);
697 } else if (Name == "strxfrm") {
698 if (FTy->getNumParams() != 3 ||
699 !FTy->getParamType(0)->isPointerTy() ||
700 !FTy->getParamType(1)->isPointerTy())
703 setDoesNotCapture(F, 1);
704 setDoesNotCapture(F, 2);
705 } else if (Name == "strcmp" ||
710 Name == "strcasecmp" ||
711 Name == "strncasecmp") {
712 if (FTy->getNumParams() < 2 ||
713 !FTy->getParamType(0)->isPointerTy() ||
714 !FTy->getParamType(1)->isPointerTy())
716 setOnlyReadsMemory(F);
718 setDoesNotCapture(F, 1);
719 setDoesNotCapture(F, 2);
720 } else if (Name == "strstr" ||
722 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
724 setOnlyReadsMemory(F);
726 setDoesNotCapture(F, 2);
727 } else if (Name == "strtok" ||
728 Name == "strtok_r") {
729 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
732 setDoesNotCapture(F, 2);
733 } else if (Name == "scanf" ||
736 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
739 setDoesNotCapture(F, 1);
740 } else if (Name == "strdup" ||
742 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
743 !FTy->getParamType(0)->isPointerTy())
746 setDoesNotAlias(F, 0);
747 setDoesNotCapture(F, 1);
748 } else if (Name == "stat" ||
752 if (FTy->getNumParams() < 2 ||
753 !FTy->getParamType(0)->isPointerTy() ||
754 !FTy->getParamType(1)->isPointerTy())
757 setDoesNotCapture(F, 1);
758 setDoesNotCapture(F, 2);
759 } else if (Name == "snprintf") {
760 if (FTy->getNumParams() != 3 ||
761 !FTy->getParamType(0)->isPointerTy() ||
762 !FTy->getParamType(2)->isPointerTy())
765 setDoesNotCapture(F, 1);
766 setDoesNotCapture(F, 3);
767 } else if (Name == "setitimer") {
768 if (FTy->getNumParams() != 3 ||
769 !FTy->getParamType(1)->isPointerTy() ||
770 !FTy->getParamType(2)->isPointerTy())
773 setDoesNotCapture(F, 2);
774 setDoesNotCapture(F, 3);
775 } else if (Name == "system") {
776 if (FTy->getNumParams() != 1 ||
777 !FTy->getParamType(0)->isPointerTy())
779 // May throw; "system" is a valid pthread cancellation point.
780 setDoesNotCapture(F, 1);
784 if (Name == "malloc") {
785 if (FTy->getNumParams() != 1 ||
786 !FTy->getReturnType()->isPointerTy())
789 setDoesNotAlias(F, 0);
790 } else if (Name == "memcmp") {
791 if (FTy->getNumParams() != 3 ||
792 !FTy->getParamType(0)->isPointerTy() ||
793 !FTy->getParamType(1)->isPointerTy())
795 setOnlyReadsMemory(F);
797 setDoesNotCapture(F, 1);
798 setDoesNotCapture(F, 2);
799 } else if (Name == "memchr" ||
801 if (FTy->getNumParams() != 3)
803 setOnlyReadsMemory(F);
805 } else if (Name == "modf" ||
811 if (FTy->getNumParams() < 2 ||
812 !FTy->getParamType(1)->isPointerTy())
815 setDoesNotCapture(F, 2);
816 } else if (Name == "memalign") {
817 if (!FTy->getReturnType()->isPointerTy())
819 setDoesNotAlias(F, 0);
820 } else if (Name == "mkdir" ||
822 if (FTy->getNumParams() == 0 ||
823 !FTy->getParamType(0)->isPointerTy())
826 setDoesNotCapture(F, 1);
830 if (Name == "realloc") {
831 if (FTy->getNumParams() != 2 ||
832 !FTy->getParamType(0)->isPointerTy() ||
833 !FTy->getReturnType()->isPointerTy())
836 setDoesNotAlias(F, 0);
837 setDoesNotCapture(F, 1);
838 } else if (Name == "read") {
839 if (FTy->getNumParams() != 3 ||
840 !FTy->getParamType(1)->isPointerTy())
842 // May throw; "read" is a valid pthread cancellation point.
843 setDoesNotCapture(F, 2);
844 } else if (Name == "rmdir" ||
847 Name == "realpath") {
848 if (FTy->getNumParams() < 1 ||
849 !FTy->getParamType(0)->isPointerTy())
852 setDoesNotCapture(F, 1);
853 } else if (Name == "rename" ||
854 Name == "readlink") {
855 if (FTy->getNumParams() < 2 ||
856 !FTy->getParamType(0)->isPointerTy() ||
857 !FTy->getParamType(1)->isPointerTy())
860 setDoesNotCapture(F, 1);
861 setDoesNotCapture(F, 2);
865 if (Name == "write") {
866 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
868 // May throw; "write" is a valid pthread cancellation point.
869 setDoesNotCapture(F, 2);
873 if (Name == "bcopy") {
874 if (FTy->getNumParams() != 3 ||
875 !FTy->getParamType(0)->isPointerTy() ||
876 !FTy->getParamType(1)->isPointerTy())
879 setDoesNotCapture(F, 1);
880 setDoesNotCapture(F, 2);
881 } else if (Name == "bcmp") {
882 if (FTy->getNumParams() != 3 ||
883 !FTy->getParamType(0)->isPointerTy() ||
884 !FTy->getParamType(1)->isPointerTy())
887 setOnlyReadsMemory(F);
888 setDoesNotCapture(F, 1);
889 setDoesNotCapture(F, 2);
890 } else if (Name == "bzero") {
891 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
894 setDoesNotCapture(F, 1);
898 if (Name == "calloc") {
899 if (FTy->getNumParams() != 2 ||
900 !FTy->getReturnType()->isPointerTy())
903 setDoesNotAlias(F, 0);
904 } else if (Name == "chmod" ||
907 Name == "clearerr" ||
908 Name == "closedir") {
909 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
912 setDoesNotCapture(F, 1);
916 if (Name == "atoi" ||
920 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
923 setOnlyReadsMemory(F);
924 setDoesNotCapture(F, 1);
925 } else if (Name == "access") {
926 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
929 setDoesNotCapture(F, 1);
933 if (Name == "fopen") {
934 if (FTy->getNumParams() != 2 ||
935 !FTy->getReturnType()->isPointerTy() ||
936 !FTy->getParamType(0)->isPointerTy() ||
937 !FTy->getParamType(1)->isPointerTy())
940 setDoesNotAlias(F, 0);
941 setDoesNotCapture(F, 1);
942 setDoesNotCapture(F, 2);
943 } else if (Name == "fdopen") {
944 if (FTy->getNumParams() != 2 ||
945 !FTy->getReturnType()->isPointerTy() ||
946 !FTy->getParamType(1)->isPointerTy())
949 setDoesNotAlias(F, 0);
950 setDoesNotCapture(F, 2);
951 } else if (Name == "feof" ||
962 Name == "flockfile" ||
963 Name == "funlockfile" ||
964 Name == "ftrylockfile") {
965 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
968 setDoesNotCapture(F, 1);
969 } else if (Name == "ferror") {
970 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
973 setDoesNotCapture(F, 1);
974 setOnlyReadsMemory(F);
975 } else if (Name == "fputc" ||
980 Name == "fstatvfs") {
981 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
984 setDoesNotCapture(F, 2);
985 } else if (Name == "fgets") {
986 if (FTy->getNumParams() != 3 ||
987 !FTy->getParamType(0)->isPointerTy() ||
988 !FTy->getParamType(2)->isPointerTy())
991 setDoesNotCapture(F, 3);
992 } else if (Name == "fread" ||
994 if (FTy->getNumParams() != 4 ||
995 !FTy->getParamType(0)->isPointerTy() ||
996 !FTy->getParamType(3)->isPointerTy())
999 setDoesNotCapture(F, 1);
1000 setDoesNotCapture(F, 4);
1001 } else if (Name == "fputs" ||
1003 Name == "fprintf" ||
1004 Name == "fgetpos") {
1005 if (FTy->getNumParams() < 2 ||
1006 !FTy->getParamType(0)->isPointerTy() ||
1007 !FTy->getParamType(1)->isPointerTy())
1010 setDoesNotCapture(F, 1);
1011 setDoesNotCapture(F, 2);
1015 if (Name == "getc" ||
1016 Name == "getlogin_r" ||
1017 Name == "getc_unlocked") {
1018 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1021 setDoesNotCapture(F, 1);
1022 } else if (Name == "getenv") {
1023 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1026 setOnlyReadsMemory(F);
1027 setDoesNotCapture(F, 1);
1028 } else if (Name == "gets" ||
1029 Name == "getchar") {
1031 } else if (Name == "getitimer") {
1032 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1035 setDoesNotCapture(F, 2);
1036 } else if (Name == "getpwnam") {
1037 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1040 setDoesNotCapture(F, 1);
1044 if (Name == "ungetc") {
1045 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1048 setDoesNotCapture(F, 2);
1049 } else if (Name == "uname" ||
1051 Name == "unsetenv") {
1052 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1055 setDoesNotCapture(F, 1);
1056 } else if (Name == "utime" ||
1058 if (FTy->getNumParams() != 2 ||
1059 !FTy->getParamType(0)->isPointerTy() ||
1060 !FTy->getParamType(1)->isPointerTy())
1063 setDoesNotCapture(F, 1);
1064 setDoesNotCapture(F, 2);
1068 if (Name == "putc") {
1069 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1072 setDoesNotCapture(F, 2);
1073 } else if (Name == "puts" ||
1076 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1079 setDoesNotCapture(F, 1);
1080 } else if (Name == "pread" ||
1082 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1084 // May throw; these are valid pthread cancellation points.
1085 setDoesNotCapture(F, 2);
1086 } else if (Name == "putchar") {
1088 } else if (Name == "popen") {
1089 if (FTy->getNumParams() != 2 ||
1090 !FTy->getReturnType()->isPointerTy() ||
1091 !FTy->getParamType(0)->isPointerTy() ||
1092 !FTy->getParamType(1)->isPointerTy())
1095 setDoesNotAlias(F, 0);
1096 setDoesNotCapture(F, 1);
1097 setDoesNotCapture(F, 2);
1098 } else if (Name == "pclose") {
1099 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1102 setDoesNotCapture(F, 1);
1106 if (Name == "vscanf") {
1107 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1110 setDoesNotCapture(F, 1);
1111 } else if (Name == "vsscanf" ||
1112 Name == "vfscanf") {
1113 if (FTy->getNumParams() != 3 ||
1114 !FTy->getParamType(1)->isPointerTy() ||
1115 !FTy->getParamType(2)->isPointerTy())
1118 setDoesNotCapture(F, 1);
1119 setDoesNotCapture(F, 2);
1120 } else if (Name == "valloc") {
1121 if (!FTy->getReturnType()->isPointerTy())
1124 setDoesNotAlias(F, 0);
1125 } else if (Name == "vprintf") {
1126 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1129 setDoesNotCapture(F, 1);
1130 } else if (Name == "vfprintf" ||
1131 Name == "vsprintf") {
1132 if (FTy->getNumParams() != 3 ||
1133 !FTy->getParamType(0)->isPointerTy() ||
1134 !FTy->getParamType(1)->isPointerTy())
1137 setDoesNotCapture(F, 1);
1138 setDoesNotCapture(F, 2);
1139 } else if (Name == "vsnprintf") {
1140 if (FTy->getNumParams() != 4 ||
1141 !FTy->getParamType(0)->isPointerTy() ||
1142 !FTy->getParamType(2)->isPointerTy())
1145 setDoesNotCapture(F, 1);
1146 setDoesNotCapture(F, 3);
1150 if (Name == "open") {
1151 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1153 // May throw; "open" is a valid pthread cancellation point.
1154 setDoesNotCapture(F, 1);
1155 } else if (Name == "opendir") {
1156 if (FTy->getNumParams() != 1 ||
1157 !FTy->getReturnType()->isPointerTy() ||
1158 !FTy->getParamType(0)->isPointerTy())
1161 setDoesNotAlias(F, 0);
1162 setDoesNotCapture(F, 1);
1166 if (Name == "tmpfile") {
1167 if (!FTy->getReturnType()->isPointerTy())
1170 setDoesNotAlias(F, 0);
1171 } else if (Name == "times") {
1172 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1175 setDoesNotCapture(F, 1);
1179 if (Name == "htonl" ||
1182 setDoesNotAccessMemory(F);
1186 if (Name == "ntohl" ||
1189 setDoesNotAccessMemory(F);
1193 if (Name == "lstat") {
1194 if (FTy->getNumParams() != 2 ||
1195 !FTy->getParamType(0)->isPointerTy() ||
1196 !FTy->getParamType(1)->isPointerTy())
1199 setDoesNotCapture(F, 1);
1200 setDoesNotCapture(F, 2);
1201 } else if (Name == "lchown") {
1202 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1205 setDoesNotCapture(F, 1);
1209 if (Name == "qsort") {
1210 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1212 // May throw; places call through function pointer.
1213 setDoesNotCapture(F, 4);
1217 if (Name == "__strdup" ||
1218 Name == "__strndup") {
1219 if (FTy->getNumParams() < 1 ||
1220 !FTy->getReturnType()->isPointerTy() ||
1221 !FTy->getParamType(0)->isPointerTy())
1224 setDoesNotAlias(F, 0);
1225 setDoesNotCapture(F, 1);
1226 } else if (Name == "__strtok_r") {
1227 if (FTy->getNumParams() != 3 ||
1228 !FTy->getParamType(1)->isPointerTy())
1231 setDoesNotCapture(F, 2);
1232 } else if (Name == "_IO_getc") {
1233 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1236 setDoesNotCapture(F, 1);
1237 } else if (Name == "_IO_putc") {
1238 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1241 setDoesNotCapture(F, 2);
1245 if (Name == "\1__isoc99_scanf") {
1246 if (FTy->getNumParams() < 1 ||
1247 !FTy->getParamType(0)->isPointerTy())
1250 setDoesNotCapture(F, 1);
1251 } else if (Name == "\1stat64" ||
1252 Name == "\1lstat64" ||
1253 Name == "\1statvfs64" ||
1254 Name == "\1__isoc99_sscanf") {
1255 if (FTy->getNumParams() < 1 ||
1256 !FTy->getParamType(0)->isPointerTy() ||
1257 !FTy->getParamType(1)->isPointerTy())
1260 setDoesNotCapture(F, 1);
1261 setDoesNotCapture(F, 2);
1262 } else if (Name == "\1fopen64") {
1263 if (FTy->getNumParams() != 2 ||
1264 !FTy->getReturnType()->isPointerTy() ||
1265 !FTy->getParamType(0)->isPointerTy() ||
1266 !FTy->getParamType(1)->isPointerTy())
1269 setDoesNotAlias(F, 0);
1270 setDoesNotCapture(F, 1);
1271 setDoesNotCapture(F, 2);
1272 } else if (Name == "\1fseeko64" ||
1273 Name == "\1ftello64") {
1274 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1277 setDoesNotCapture(F, 1);
1278 } else if (Name == "\1tmpfile64") {
1279 if (!FTy->getReturnType()->isPointerTy())
1282 setDoesNotAlias(F, 0);
1283 } else if (Name == "\1fstat64" ||
1284 Name == "\1fstatvfs64") {
1285 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1288 setDoesNotCapture(F, 2);
1289 } else if (Name == "\1open64") {
1290 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1292 // May throw; "open" is a valid pthread cancellation point.
1293 setDoesNotCapture(F, 1);
1299 /// doInitialization - Add attributes to well-known functions.
1301 bool SimplifyLibCalls::doInitialization(Module &M) {
1303 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1305 if (F.isDeclaration() && F.hasName())
1306 inferPrototypeAttributes(F);
1312 // Additional cases that we need to add to this file:
1315 // * cbrt(expN(X)) -> expN(x/3)
1316 // * cbrt(sqrt(x)) -> pow(x,1/6)
1317 // * cbrt(sqrt(x)) -> pow(x,1/9)
1320 // * exp(log(x)) -> x
1323 // * log(exp(x)) -> x
1324 // * log(x**y) -> y*log(x)
1325 // * log(exp(y)) -> y*log(e)
1326 // * log(exp2(y)) -> y*log(2)
1327 // * log(exp10(y)) -> y*log(10)
1328 // * log(sqrt(x)) -> 0.5*log(x)
1329 // * log(pow(x,y)) -> y*log(x)
1331 // lround, lroundf, lroundl:
1332 // * lround(cnst) -> cnst'
1335 // * pow(exp(x),y) -> exp(x*y)
1336 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1337 // * pow(pow(x,y),z)-> pow(x,y*z)
1339 // round, roundf, roundl:
1340 // * round(cnst) -> cnst'
1343 // * signbit(cnst) -> cnst'
1344 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1346 // sqrt, sqrtf, sqrtl:
1347 // * sqrt(expN(x)) -> expN(x*0.5)
1348 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1349 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1352 // * strchr(p, 0) -> strlen(p)
1354 // * tan(atan(x)) -> x
1356 // trunc, truncf, truncl:
1357 // * trunc(cnst) -> cnst'