1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
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 interprocedural pass which walks the
11 // call-graph, looking for functions which do not access or only read
12 // non-local memory, and marking them readnone/readonly. It does the
13 // same with function arguments independently, marking them readonly/
14 // readnone/nocapture. Finally, well-known library call declarations
15 // are marked with all attributes that are consistent with the
16 // function's standard definition. This pass is implemented as a
17 // bottom-up traversal of the call-graph.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/CallGraphSCCPass.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Analysis/TargetLibraryInfo.h"
43 #define DEBUG_TYPE "functionattrs"
45 STATISTIC(NumReadNone, "Number of functions marked readnone");
46 STATISTIC(NumReadOnly, "Number of functions marked readonly");
47 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
48 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
49 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
50 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
51 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
52 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
55 struct FunctionAttrs : public CallGraphSCCPass {
56 static char ID; // Pass identification, replacement for typeid
57 FunctionAttrs() : CallGraphSCCPass(ID) {
58 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
61 bool runOnSCC(CallGraphSCC &SCC) override;
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
65 AU.addRequired<AssumptionCacheTracker>();
66 AU.addRequired<TargetLibraryInfoWrapperPass>();
67 CallGraphSCCPass::getAnalysisUsage(AU);
71 TargetLibraryInfo *TLI;
73 bool AddReadAttrs(const CallGraphSCC &SCC);
74 bool AddArgumentAttrs(const CallGraphSCC &SCC);
75 bool IsFunctionMallocLike(Function *F, SmallPtrSet<Function *, 8> &) const;
76 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
77 bool ReturnsNonNull(Function *F, SmallPtrSet<Function *, 8> &,
78 bool &Speculative) const;
79 bool AddNonNullAttrs(const CallGraphSCC &SCC);
80 bool inferPrototypeAttributes(Function &F);
81 bool annotateLibraryCalls(const CallGraphSCC &SCC);
85 char FunctionAttrs::ID = 0;
86 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
87 "Deduce function attributes", false, false)
88 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
89 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
90 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
91 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
92 "Deduce function attributes", false, false)
94 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
96 /// Deduce readonly/readnone attributes for the SCC.
97 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
98 SmallPtrSet<Function *, 8> SCCNodes;
100 // Fill SCCNodes with the elements of the SCC. Used for quickly
101 // looking up whether a given CallGraphNode is in this SCC.
102 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
103 SCCNodes.insert((*I)->getFunction());
105 // Check if any of the functions in the SCC read or write memory. If they
106 // write memory then they can't be marked readnone or readonly.
107 bool ReadsMemory = false;
108 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
109 Function *F = (*I)->getFunction();
111 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
112 // External node or node we don't want to optimize - assume it may write
113 // memory and give up.
116 // We need to manually construct BasicAA directly in order to disable its
117 // use of other function analyses.
118 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
120 // Construct our own AA results for this function. We do this manually to
121 // work around the limitations of the legacy pass manager.
122 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
124 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
125 if (MRB == FMRB_DoesNotAccessMemory)
129 // Definitions with weak linkage may be overridden at linktime with
130 // something that writes memory, so treat them like declarations.
131 if (F->isDeclaration() || F->mayBeOverridden()) {
132 if (!AliasAnalysis::onlyReadsMemory(MRB))
133 // May write memory. Just give up.
140 // Scan the function body for instructions that may read or write memory.
141 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
142 Instruction *I = &*II;
144 // Some instructions can be ignored even if they read or write memory.
145 // Detect these now, skipping to the next instruction if one is found.
146 CallSite CS(cast<Value>(I));
148 // Ignore calls to functions in the same SCC.
149 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
151 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
152 // If the call doesn't access arbitrary memory, we may be able to
153 // figure out something.
154 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
155 // If the call does access argument pointees, check each argument.
156 if (AliasAnalysis::doesAccessArgPointees(MRB))
157 // Check whether all pointer arguments point to local memory, and
158 // ignore calls that only access local memory.
159 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
162 if (Arg->getType()->isPointerTy()) {
164 I->getAAMetadata(AAInfo);
166 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
167 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
169 // Writes non-local memory. Give up.
172 // Ok, it reads non-local memory.
179 // The call could access any memory. If that includes writes, give up.
182 // If it reads, note it.
186 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
187 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
188 if (!LI->isVolatile()) {
189 MemoryLocation Loc = MemoryLocation::get(LI);
190 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
193 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
194 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
195 if (!SI->isVolatile()) {
196 MemoryLocation Loc = MemoryLocation::get(SI);
197 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
200 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
201 // Ignore vaargs on local memory.
202 MemoryLocation Loc = MemoryLocation::get(VI);
203 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
207 // Any remaining instructions need to be taken seriously! Check if they
208 // read or write memory.
209 if (I->mayWriteToMemory())
210 // Writes memory. Just give up.
213 // If this instruction may read memory, remember that.
214 ReadsMemory |= I->mayReadFromMemory();
218 // Success! Functions in this SCC do not access memory, or only read memory.
219 // Give them the appropriate attribute.
220 bool MadeChange = false;
221 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
222 Function *F = (*I)->getFunction();
224 if (F->doesNotAccessMemory())
228 if (F->onlyReadsMemory() && ReadsMemory)
234 // Clear out any existing attributes.
236 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
238 AttributeSet::FunctionIndex,
239 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
241 // Add in the new attribute.
242 F->addAttribute(AttributeSet::FunctionIndex,
243 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
255 /// For a given pointer Argument, this retains a list of Arguments of functions
256 /// in the same SCC that the pointer data flows into. We use this to build an
257 /// SCC of the arguments.
258 struct ArgumentGraphNode {
259 Argument *Definition;
260 SmallVector<ArgumentGraphNode *, 4> Uses;
263 class ArgumentGraph {
264 // We store pointers to ArgumentGraphNode objects, so it's important that
265 // that they not move around upon insert.
266 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
268 ArgumentMapTy ArgumentMap;
270 // There is no root node for the argument graph, in fact:
271 // void f(int *x, int *y) { if (...) f(x, y); }
272 // is an example where the graph is disconnected. The SCCIterator requires a
273 // single entry point, so we maintain a fake ("synthetic") root node that
274 // uses every node. Because the graph is directed and nothing points into
275 // the root, it will not participate in any SCCs (except for its own).
276 ArgumentGraphNode SyntheticRoot;
279 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
281 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
283 iterator begin() { return SyntheticRoot.Uses.begin(); }
284 iterator end() { return SyntheticRoot.Uses.end(); }
285 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
287 ArgumentGraphNode *operator[](Argument *A) {
288 ArgumentGraphNode &Node = ArgumentMap[A];
290 SyntheticRoot.Uses.push_back(&Node);
295 /// This tracker checks whether callees are in the SCC, and if so it does not
296 /// consider that a capture, instead adding it to the "Uses" list and
297 /// continuing with the analysis.
298 struct ArgumentUsesTracker : public CaptureTracker {
299 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
300 : Captured(false), SCCNodes(SCCNodes) {}
302 void tooManyUses() override { Captured = true; }
304 bool captured(const Use *U) override {
305 CallSite CS(U->getUser());
306 if (!CS.getInstruction()) {
311 Function *F = CS.getCalledFunction();
312 if (!F || !SCCNodes.count(F)) {
318 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
319 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
320 PI != PE; ++PI, ++AI) {
322 assert(F->isVarArg() && "More params than args in non-varargs call");
332 assert(Found && "Capturing call-site captured nothing?");
337 bool Captured; // True only if certainly captured (used outside our SCC).
338 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
340 const SmallPtrSet<Function *, 8> &SCCNodes;
345 template <> struct GraphTraits<ArgumentGraphNode *> {
346 typedef ArgumentGraphNode NodeType;
347 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
349 static inline NodeType *getEntryNode(NodeType *A) { return A; }
350 static inline ChildIteratorType child_begin(NodeType *N) {
351 return N->Uses.begin();
353 static inline ChildIteratorType child_end(NodeType *N) {
354 return N->Uses.end();
358 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
359 static NodeType *getEntryNode(ArgumentGraph *AG) {
360 return AG->getEntryNode();
362 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
365 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
369 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
370 static Attribute::AttrKind
371 determinePointerReadAttrs(Argument *A,
372 const SmallPtrSet<Argument *, 8> &SCCNodes) {
374 SmallVector<Use *, 32> Worklist;
375 SmallSet<Use *, 32> Visited;
377 // inalloca arguments are always clobbered by the call.
378 if (A->hasInAllocaAttr())
379 return Attribute::None;
382 // We don't need to track IsWritten. If A is written to, return immediately.
384 for (Use &U : A->uses()) {
386 Worklist.push_back(&U);
389 while (!Worklist.empty()) {
390 Use *U = Worklist.pop_back_val();
391 Instruction *I = cast<Instruction>(U->getUser());
394 switch (I->getOpcode()) {
395 case Instruction::BitCast:
396 case Instruction::GetElementPtr:
397 case Instruction::PHI:
398 case Instruction::Select:
399 case Instruction::AddrSpaceCast:
400 // The original value is not read/written via this if the new value isn't.
401 for (Use &UU : I->uses())
402 if (Visited.insert(&UU).second)
403 Worklist.push_back(&UU);
406 case Instruction::Call:
407 case Instruction::Invoke: {
408 bool Captures = true;
410 if (I->getType()->isVoidTy())
413 auto AddUsersToWorklistIfCapturing = [&] {
415 for (Use &UU : I->uses())
416 if (Visited.insert(&UU).second)
417 Worklist.push_back(&UU);
421 if (CS.doesNotAccessMemory()) {
422 AddUsersToWorklistIfCapturing();
426 Function *F = CS.getCalledFunction();
428 if (CS.onlyReadsMemory()) {
430 AddUsersToWorklistIfCapturing();
433 return Attribute::None;
436 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
437 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
438 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
441 assert(F->isVarArg() &&
442 "More params than args in non-varargs call.");
443 return Attribute::None;
445 Captures &= !CS.doesNotCapture(A - B);
446 if (SCCNodes.count(AI))
448 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
449 return Attribute::None;
450 if (!CS.doesNotAccessMemory(A - B))
454 AddUsersToWorklistIfCapturing();
458 case Instruction::Load:
462 case Instruction::ICmp:
463 case Instruction::Ret:
467 return Attribute::None;
471 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
474 /// Deduce nocapture attributes for the SCC.
475 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
476 bool Changed = false;
478 SmallPtrSet<Function *, 8> SCCNodes;
480 // Fill SCCNodes with the elements of the SCC. Used for quickly
481 // looking up whether a given CallGraphNode is in this SCC.
482 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
483 Function *F = (*I)->getFunction();
484 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
485 !F->hasFnAttribute(Attribute::OptimizeNone))
492 B.addAttribute(Attribute::NoCapture);
494 // Check each function in turn, determining which pointer arguments are not
496 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
497 Function *F = (*I)->getFunction();
499 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
500 // External node or function we're trying not to optimize - only a problem
501 // for arguments that we pass to it.
504 // Definitions with weak linkage may be overridden at linktime with
505 // something that captures pointers, so treat them like declarations.
506 if (F->isDeclaration() || F->mayBeOverridden())
509 // Functions that are readonly (or readnone) and nounwind and don't return
510 // a value can't capture arguments. Don't analyze them.
511 if (F->onlyReadsMemory() && F->doesNotThrow() &&
512 F->getReturnType()->isVoidTy()) {
513 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
515 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
516 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
524 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
526 if (!A->getType()->isPointerTy())
528 bool HasNonLocalUses = false;
529 if (!A->hasNoCaptureAttr()) {
530 ArgumentUsesTracker Tracker(SCCNodes);
531 PointerMayBeCaptured(A, &Tracker);
532 if (!Tracker.Captured) {
533 if (Tracker.Uses.empty()) {
534 // If it's trivially not captured, mark it nocapture now.
536 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
540 // If it's not trivially captured and not trivially not captured,
541 // then it must be calling into another function in our SCC. Save
542 // its particulars for Argument-SCC analysis later.
543 ArgumentGraphNode *Node = AG[A];
544 for (SmallVectorImpl<Argument *>::iterator
545 UI = Tracker.Uses.begin(),
546 UE = Tracker.Uses.end();
548 Node->Uses.push_back(AG[*UI]);
550 HasNonLocalUses = true;
554 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
556 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
557 // Can we determine that it's readonly/readnone without doing an SCC?
558 // Note that we don't allow any calls at all here, or else our result
559 // will be dependent on the iteration order through the functions in the
561 SmallPtrSet<Argument *, 8> Self;
563 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
564 if (R != Attribute::None) {
567 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
569 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
575 // The graph we've collected is partial because we stopped scanning for
576 // argument uses once we solved the argument trivially. These partial nodes
577 // show up as ArgumentGraphNode objects with an empty Uses list, and for
578 // these nodes the final decision about whether they capture has already been
579 // made. If the definition doesn't have a 'nocapture' attribute by now, it
582 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
583 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
584 if (ArgumentSCC.size() == 1) {
585 if (!ArgumentSCC[0]->Definition)
586 continue; // synthetic root node
588 // eg. "void f(int* x) { if (...) f(x); }"
589 if (ArgumentSCC[0]->Uses.size() == 1 &&
590 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
591 Argument *A = ArgumentSCC[0]->Definition;
592 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
599 bool SCCCaptured = false;
600 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
601 I != E && !SCCCaptured; ++I) {
602 ArgumentGraphNode *Node = *I;
603 if (Node->Uses.empty()) {
604 if (!Node->Definition->hasNoCaptureAttr())
611 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
612 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
613 // quickly looking up whether a given Argument is in this ArgumentSCC.
614 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
615 ArgumentSCCNodes.insert((*I)->Definition);
618 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
619 I != E && !SCCCaptured; ++I) {
620 ArgumentGraphNode *N = *I;
621 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
624 Argument *A = (*UI)->Definition;
625 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
634 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
635 Argument *A = ArgumentSCC[i]->Definition;
636 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
641 // We also want to compute readonly/readnone. With a small number of false
642 // negatives, we can assume that any pointer which is captured isn't going
643 // to be provably readonly or readnone, since by definition we can't
644 // analyze all uses of a captured pointer.
646 // The false negatives happen when the pointer is captured by a function
647 // that promises readonly/readnone behaviour on the pointer, then the
648 // pointer's lifetime ends before anything that writes to arbitrary memory.
649 // Also, a readonly/readnone pointer may be returned, but returning a
650 // pointer is capturing it.
652 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
653 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
654 Argument *A = ArgumentSCC[i]->Definition;
655 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
656 if (K == Attribute::ReadNone)
658 if (K == Attribute::ReadOnly) {
659 ReadAttr = Attribute::ReadOnly;
666 if (ReadAttr != Attribute::None) {
668 B.addAttribute(ReadAttr);
669 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
670 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
671 Argument *A = ArgumentSCC[i]->Definition;
672 // Clear out existing readonly/readnone attributes
673 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
674 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
675 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
684 /// Tests whether a function is "malloc-like".
686 /// A function is "malloc-like" if it returns either null or a pointer that
687 /// doesn't alias any other pointer visible to the caller.
688 bool FunctionAttrs::IsFunctionMallocLike(
689 Function *F, SmallPtrSet<Function *, 8> &SCCNodes) const {
690 SmallSetVector<Value *, 8> FlowsToReturn;
691 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
692 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
693 FlowsToReturn.insert(Ret->getReturnValue());
695 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
696 Value *RetVal = FlowsToReturn[i];
698 if (Constant *C = dyn_cast<Constant>(RetVal)) {
699 if (!C->isNullValue() && !isa<UndefValue>(C))
705 if (isa<Argument>(RetVal))
708 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
709 switch (RVI->getOpcode()) {
710 // Extend the analysis by looking upwards.
711 case Instruction::BitCast:
712 case Instruction::GetElementPtr:
713 case Instruction::AddrSpaceCast:
714 FlowsToReturn.insert(RVI->getOperand(0));
716 case Instruction::Select: {
717 SelectInst *SI = cast<SelectInst>(RVI);
718 FlowsToReturn.insert(SI->getTrueValue());
719 FlowsToReturn.insert(SI->getFalseValue());
722 case Instruction::PHI: {
723 PHINode *PN = cast<PHINode>(RVI);
724 for (Value *IncValue : PN->incoming_values())
725 FlowsToReturn.insert(IncValue);
729 // Check whether the pointer came from an allocation.
730 case Instruction::Alloca:
732 case Instruction::Call:
733 case Instruction::Invoke: {
735 if (CS.paramHasAttr(0, Attribute::NoAlias))
737 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
741 return false; // Did not come from an allocation.
744 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
751 /// Deduce noalias attributes for the SCC.
752 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
753 SmallPtrSet<Function *, 8> SCCNodes;
755 // Fill SCCNodes with the elements of the SCC. Used for quickly
756 // looking up whether a given CallGraphNode is in this SCC.
757 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
758 SCCNodes.insert((*I)->getFunction());
760 // Check each function in turn, determining which functions return noalias
762 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
763 Function *F = (*I)->getFunction();
765 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
766 // External node or node we don't want to optimize - skip it;
770 if (F->doesNotAlias(0))
773 // Definitions with weak linkage may be overridden at linktime, so
774 // treat them like declarations.
775 if (F->isDeclaration() || F->mayBeOverridden())
778 // We annotate noalias return values, which are only applicable to
780 if (!F->getReturnType()->isPointerTy())
783 if (!IsFunctionMallocLike(F, SCCNodes))
787 bool MadeChange = false;
788 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
789 Function *F = (*I)->getFunction();
790 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
793 F->setDoesNotAlias(0);
801 /// Tests whether this function is known to not return null.
802 bool FunctionAttrs::ReturnsNonNull(Function *F,
803 SmallPtrSet<Function *, 8> &SCCNodes,
804 bool &Speculative) const {
805 assert(F->getReturnType()->isPointerTy() &&
806 "nonnull only meaningful on pointer types");
809 SmallSetVector<Value *, 8> FlowsToReturn;
810 for (BasicBlock &BB : *F)
811 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
812 FlowsToReturn.insert(Ret->getReturnValue());
814 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
815 Value *RetVal = FlowsToReturn[i];
817 // If this value is locally known to be non-null, we're good
818 if (isKnownNonNull(RetVal, TLI))
821 // Otherwise, we need to look upwards since we can't make any local
823 Instruction *RVI = dyn_cast<Instruction>(RetVal);
826 switch (RVI->getOpcode()) {
827 // Extend the analysis by looking upwards.
828 case Instruction::BitCast:
829 case Instruction::GetElementPtr:
830 case Instruction::AddrSpaceCast:
831 FlowsToReturn.insert(RVI->getOperand(0));
833 case Instruction::Select: {
834 SelectInst *SI = cast<SelectInst>(RVI);
835 FlowsToReturn.insert(SI->getTrueValue());
836 FlowsToReturn.insert(SI->getFalseValue());
839 case Instruction::PHI: {
840 PHINode *PN = cast<PHINode>(RVI);
841 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
842 FlowsToReturn.insert(PN->getIncomingValue(i));
845 case Instruction::Call:
846 case Instruction::Invoke: {
848 Function *Callee = CS.getCalledFunction();
849 // A call to a node within the SCC is assumed to return null until
851 if (Callee && SCCNodes.count(Callee)) {
858 return false; // Unknown source, may be null
860 llvm_unreachable("should have either continued or returned");
866 /// Deduce nonnull attributes for the SCC.
867 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
868 SmallPtrSet<Function *, 8> SCCNodes;
870 // Fill SCCNodes with the elements of the SCC. Used for quickly
871 // looking up whether a given CallGraphNode is in this SCC.
872 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
873 SCCNodes.insert((*I)->getFunction());
875 // Speculative that all functions in the SCC return only nonnull
876 // pointers. We may refute this as we analyze functions.
877 bool SCCReturnsNonNull = true;
879 bool MadeChange = false;
881 // Check each function in turn, determining which functions return nonnull
883 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
884 Function *F = (*I)->getFunction();
886 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
887 // External node or node we don't want to optimize - skip it;
891 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
895 // Definitions with weak linkage may be overridden at linktime, so
896 // treat them like declarations.
897 if (F->isDeclaration() || F->mayBeOverridden())
900 // We annotate nonnull return values, which are only applicable to
902 if (!F->getReturnType()->isPointerTy())
905 bool Speculative = false;
906 if (ReturnsNonNull(F, SCCNodes, Speculative)) {
908 // Mark the function eagerly since we may discover a function
909 // which prevents us from speculating about the entire SCC
910 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
911 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
917 // At least one function returns something which could be null, can't
918 // speculate any more.
919 SCCReturnsNonNull = false;
922 if (SCCReturnsNonNull) {
923 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
924 Function *F = (*I)->getFunction();
925 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
926 Attribute::NonNull) ||
927 !F->getReturnType()->isPointerTy())
930 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
931 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
940 static void setDoesNotAccessMemory(Function &F) {
941 if (!F.doesNotAccessMemory()) {
942 F.setDoesNotAccessMemory();
947 static void setOnlyReadsMemory(Function &F) {
948 if (!F.onlyReadsMemory()) {
949 F.setOnlyReadsMemory();
954 static void setDoesNotThrow(Function &F) {
955 if (!F.doesNotThrow()) {
961 static void setDoesNotCapture(Function &F, unsigned n) {
962 if (!F.doesNotCapture(n)) {
963 F.setDoesNotCapture(n);
968 static void setOnlyReadsMemory(Function &F, unsigned n) {
969 if (!F.onlyReadsMemory(n)) {
970 F.setOnlyReadsMemory(n);
975 static void setDoesNotAlias(Function &F, unsigned n) {
976 if (!F.doesNotAlias(n)) {
977 F.setDoesNotAlias(n);
982 /// Analyze the name and prototype of the given function and set any applicable
985 /// Returns true if any attributes were set and false otherwise.
986 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
987 if (F.hasFnAttribute(Attribute::OptimizeNone))
990 FunctionType *FTy = F.getFunctionType();
991 LibFunc::Func TheLibFunc;
992 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
995 switch (TheLibFunc) {
996 case LibFunc::strlen:
997 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
999 setOnlyReadsMemory(F);
1001 setDoesNotCapture(F, 1);
1003 case LibFunc::strchr:
1004 case LibFunc::strrchr:
1005 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1006 !FTy->getParamType(1)->isIntegerTy())
1008 setOnlyReadsMemory(F);
1011 case LibFunc::strtol:
1012 case LibFunc::strtod:
1013 case LibFunc::strtof:
1014 case LibFunc::strtoul:
1015 case LibFunc::strtoll:
1016 case LibFunc::strtold:
1017 case LibFunc::strtoull:
1018 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1021 setDoesNotCapture(F, 2);
1022 setOnlyReadsMemory(F, 1);
1024 case LibFunc::strcpy:
1025 case LibFunc::stpcpy:
1026 case LibFunc::strcat:
1027 case LibFunc::strncat:
1028 case LibFunc::strncpy:
1029 case LibFunc::stpncpy:
1030 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1033 setDoesNotCapture(F, 2);
1034 setOnlyReadsMemory(F, 2);
1036 case LibFunc::strxfrm:
1037 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1038 !FTy->getParamType(1)->isPointerTy())
1041 setDoesNotCapture(F, 1);
1042 setDoesNotCapture(F, 2);
1043 setOnlyReadsMemory(F, 2);
1045 case LibFunc::strcmp: // 0,1
1046 case LibFunc::strspn: // 0,1
1047 case LibFunc::strncmp: // 0,1
1048 case LibFunc::strcspn: // 0,1
1049 case LibFunc::strcoll: // 0,1
1050 case LibFunc::strcasecmp: // 0,1
1051 case LibFunc::strncasecmp: //
1052 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1053 !FTy->getParamType(1)->isPointerTy())
1055 setOnlyReadsMemory(F);
1057 setDoesNotCapture(F, 1);
1058 setDoesNotCapture(F, 2);
1060 case LibFunc::strstr:
1061 case LibFunc::strpbrk:
1062 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1064 setOnlyReadsMemory(F);
1066 setDoesNotCapture(F, 2);
1068 case LibFunc::strtok:
1069 case LibFunc::strtok_r:
1070 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1073 setDoesNotCapture(F, 2);
1074 setOnlyReadsMemory(F, 2);
1076 case LibFunc::scanf:
1077 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1080 setDoesNotCapture(F, 1);
1081 setOnlyReadsMemory(F, 1);
1083 case LibFunc::setbuf:
1084 case LibFunc::setvbuf:
1085 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1088 setDoesNotCapture(F, 1);
1090 case LibFunc::strdup:
1091 case LibFunc::strndup:
1092 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1093 !FTy->getParamType(0)->isPointerTy())
1096 setDoesNotAlias(F, 0);
1097 setDoesNotCapture(F, 1);
1098 setOnlyReadsMemory(F, 1);
1101 case LibFunc::statvfs:
1102 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1103 !FTy->getParamType(1)->isPointerTy())
1106 setDoesNotCapture(F, 1);
1107 setDoesNotCapture(F, 2);
1108 setOnlyReadsMemory(F, 1);
1110 case LibFunc::sscanf:
1111 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1112 !FTy->getParamType(1)->isPointerTy())
1115 setDoesNotCapture(F, 1);
1116 setDoesNotCapture(F, 2);
1117 setOnlyReadsMemory(F, 1);
1118 setOnlyReadsMemory(F, 2);
1120 case LibFunc::sprintf:
1121 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1122 !FTy->getParamType(1)->isPointerTy())
1125 setDoesNotCapture(F, 1);
1126 setDoesNotCapture(F, 2);
1127 setOnlyReadsMemory(F, 2);
1129 case LibFunc::snprintf:
1130 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1131 !FTy->getParamType(2)->isPointerTy())
1134 setDoesNotCapture(F, 1);
1135 setDoesNotCapture(F, 3);
1136 setOnlyReadsMemory(F, 3);
1138 case LibFunc::setitimer:
1139 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1140 !FTy->getParamType(2)->isPointerTy())
1143 setDoesNotCapture(F, 2);
1144 setDoesNotCapture(F, 3);
1145 setOnlyReadsMemory(F, 2);
1147 case LibFunc::system:
1148 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1150 // May throw; "system" is a valid pthread cancellation point.
1151 setDoesNotCapture(F, 1);
1152 setOnlyReadsMemory(F, 1);
1154 case LibFunc::malloc:
1155 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1158 setDoesNotAlias(F, 0);
1160 case LibFunc::memcmp:
1161 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1162 !FTy->getParamType(1)->isPointerTy())
1164 setOnlyReadsMemory(F);
1166 setDoesNotCapture(F, 1);
1167 setDoesNotCapture(F, 2);
1169 case LibFunc::memchr:
1170 case LibFunc::memrchr:
1171 if (FTy->getNumParams() != 3)
1173 setOnlyReadsMemory(F);
1177 case LibFunc::modff:
1178 case LibFunc::modfl:
1179 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1182 setDoesNotCapture(F, 2);
1184 case LibFunc::memcpy:
1185 case LibFunc::memccpy:
1186 case LibFunc::memmove:
1187 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1190 setDoesNotCapture(F, 2);
1191 setOnlyReadsMemory(F, 2);
1193 case LibFunc::memalign:
1194 if (!FTy->getReturnType()->isPointerTy())
1196 setDoesNotAlias(F, 0);
1198 case LibFunc::mkdir:
1199 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1202 setDoesNotCapture(F, 1);
1203 setOnlyReadsMemory(F, 1);
1205 case LibFunc::mktime:
1206 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1209 setDoesNotCapture(F, 1);
1211 case LibFunc::realloc:
1212 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1213 !FTy->getReturnType()->isPointerTy())
1216 setDoesNotAlias(F, 0);
1217 setDoesNotCapture(F, 1);
1220 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1222 // May throw; "read" is a valid pthread cancellation point.
1223 setDoesNotCapture(F, 2);
1225 case LibFunc::rewind:
1226 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1229 setDoesNotCapture(F, 1);
1231 case LibFunc::rmdir:
1232 case LibFunc::remove:
1233 case LibFunc::realpath:
1234 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1237 setDoesNotCapture(F, 1);
1238 setOnlyReadsMemory(F, 1);
1240 case LibFunc::rename:
1241 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1242 !FTy->getParamType(1)->isPointerTy())
1245 setDoesNotCapture(F, 1);
1246 setDoesNotCapture(F, 2);
1247 setOnlyReadsMemory(F, 1);
1248 setOnlyReadsMemory(F, 2);
1250 case LibFunc::readlink:
1251 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1252 !FTy->getParamType(1)->isPointerTy())
1255 setDoesNotCapture(F, 1);
1256 setDoesNotCapture(F, 2);
1257 setOnlyReadsMemory(F, 1);
1259 case LibFunc::write:
1260 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1262 // May throw; "write" is a valid pthread cancellation point.
1263 setDoesNotCapture(F, 2);
1264 setOnlyReadsMemory(F, 2);
1266 case LibFunc::bcopy:
1267 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1268 !FTy->getParamType(1)->isPointerTy())
1271 setDoesNotCapture(F, 1);
1272 setDoesNotCapture(F, 2);
1273 setOnlyReadsMemory(F, 1);
1276 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1277 !FTy->getParamType(1)->isPointerTy())
1280 setOnlyReadsMemory(F);
1281 setDoesNotCapture(F, 1);
1282 setDoesNotCapture(F, 2);
1284 case LibFunc::bzero:
1285 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1288 setDoesNotCapture(F, 1);
1290 case LibFunc::calloc:
1291 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1294 setDoesNotAlias(F, 0);
1296 case LibFunc::chmod:
1297 case LibFunc::chown:
1298 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1301 setDoesNotCapture(F, 1);
1302 setOnlyReadsMemory(F, 1);
1304 case LibFunc::ctermid:
1305 case LibFunc::clearerr:
1306 case LibFunc::closedir:
1307 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1310 setDoesNotCapture(F, 1);
1315 case LibFunc::atoll:
1316 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1319 setOnlyReadsMemory(F);
1320 setDoesNotCapture(F, 1);
1322 case LibFunc::access:
1323 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1326 setDoesNotCapture(F, 1);
1327 setOnlyReadsMemory(F, 1);
1329 case LibFunc::fopen:
1330 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1331 !FTy->getParamType(0)->isPointerTy() ||
1332 !FTy->getParamType(1)->isPointerTy())
1335 setDoesNotAlias(F, 0);
1336 setDoesNotCapture(F, 1);
1337 setDoesNotCapture(F, 2);
1338 setOnlyReadsMemory(F, 1);
1339 setOnlyReadsMemory(F, 2);
1341 case LibFunc::fdopen:
1342 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1343 !FTy->getParamType(1)->isPointerTy())
1346 setDoesNotAlias(F, 0);
1347 setDoesNotCapture(F, 2);
1348 setOnlyReadsMemory(F, 2);
1352 case LibFunc::fseek:
1353 case LibFunc::ftell:
1354 case LibFunc::fgetc:
1355 case LibFunc::fseeko:
1356 case LibFunc::ftello:
1357 case LibFunc::fileno:
1358 case LibFunc::fflush:
1359 case LibFunc::fclose:
1360 case LibFunc::fsetpos:
1361 case LibFunc::flockfile:
1362 case LibFunc::funlockfile:
1363 case LibFunc::ftrylockfile:
1364 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1367 setDoesNotCapture(F, 1);
1369 case LibFunc::ferror:
1370 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1373 setDoesNotCapture(F, 1);
1374 setOnlyReadsMemory(F);
1376 case LibFunc::fputc:
1377 case LibFunc::fstat:
1378 case LibFunc::frexp:
1379 case LibFunc::frexpf:
1380 case LibFunc::frexpl:
1381 case LibFunc::fstatvfs:
1382 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1385 setDoesNotCapture(F, 2);
1387 case LibFunc::fgets:
1388 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1389 !FTy->getParamType(2)->isPointerTy())
1392 setDoesNotCapture(F, 3);
1394 case LibFunc::fread:
1395 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1396 !FTy->getParamType(3)->isPointerTy())
1399 setDoesNotCapture(F, 1);
1400 setDoesNotCapture(F, 4);
1402 case LibFunc::fwrite:
1403 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1404 !FTy->getParamType(3)->isPointerTy())
1407 setDoesNotCapture(F, 1);
1408 setDoesNotCapture(F, 4);
1410 case LibFunc::fputs:
1411 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1412 !FTy->getParamType(1)->isPointerTy())
1415 setDoesNotCapture(F, 1);
1416 setDoesNotCapture(F, 2);
1417 setOnlyReadsMemory(F, 1);
1419 case LibFunc::fscanf:
1420 case LibFunc::fprintf:
1421 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1422 !FTy->getParamType(1)->isPointerTy())
1425 setDoesNotCapture(F, 1);
1426 setDoesNotCapture(F, 2);
1427 setOnlyReadsMemory(F, 2);
1429 case LibFunc::fgetpos:
1430 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1431 !FTy->getParamType(1)->isPointerTy())
1434 setDoesNotCapture(F, 1);
1435 setDoesNotCapture(F, 2);
1438 case LibFunc::getlogin_r:
1439 case LibFunc::getc_unlocked:
1440 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1443 setDoesNotCapture(F, 1);
1445 case LibFunc::getenv:
1446 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1449 setOnlyReadsMemory(F);
1450 setDoesNotCapture(F, 1);
1453 case LibFunc::getchar:
1456 case LibFunc::getitimer:
1457 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1460 setDoesNotCapture(F, 2);
1462 case LibFunc::getpwnam:
1463 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1466 setDoesNotCapture(F, 1);
1467 setOnlyReadsMemory(F, 1);
1469 case LibFunc::ungetc:
1470 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1473 setDoesNotCapture(F, 2);
1475 case LibFunc::uname:
1476 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1479 setDoesNotCapture(F, 1);
1481 case LibFunc::unlink:
1482 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1485 setDoesNotCapture(F, 1);
1486 setOnlyReadsMemory(F, 1);
1488 case LibFunc::unsetenv:
1489 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1492 setDoesNotCapture(F, 1);
1493 setOnlyReadsMemory(F, 1);
1495 case LibFunc::utime:
1496 case LibFunc::utimes:
1497 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1498 !FTy->getParamType(1)->isPointerTy())
1501 setDoesNotCapture(F, 1);
1502 setDoesNotCapture(F, 2);
1503 setOnlyReadsMemory(F, 1);
1504 setOnlyReadsMemory(F, 2);
1507 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1510 setDoesNotCapture(F, 2);
1513 case LibFunc::printf:
1514 case LibFunc::perror:
1515 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1518 setDoesNotCapture(F, 1);
1519 setOnlyReadsMemory(F, 1);
1521 case LibFunc::pread:
1522 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1524 // May throw; "pread" is a valid pthread cancellation point.
1525 setDoesNotCapture(F, 2);
1527 case LibFunc::pwrite:
1528 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1530 // May throw; "pwrite" is a valid pthread cancellation point.
1531 setDoesNotCapture(F, 2);
1532 setOnlyReadsMemory(F, 2);
1534 case LibFunc::putchar:
1537 case LibFunc::popen:
1538 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1539 !FTy->getParamType(0)->isPointerTy() ||
1540 !FTy->getParamType(1)->isPointerTy())
1543 setDoesNotAlias(F, 0);
1544 setDoesNotCapture(F, 1);
1545 setDoesNotCapture(F, 2);
1546 setOnlyReadsMemory(F, 1);
1547 setOnlyReadsMemory(F, 2);
1549 case LibFunc::pclose:
1550 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1553 setDoesNotCapture(F, 1);
1555 case LibFunc::vscanf:
1556 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1559 setDoesNotCapture(F, 1);
1560 setOnlyReadsMemory(F, 1);
1562 case LibFunc::vsscanf:
1563 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1564 !FTy->getParamType(2)->isPointerTy())
1567 setDoesNotCapture(F, 1);
1568 setDoesNotCapture(F, 2);
1569 setOnlyReadsMemory(F, 1);
1570 setOnlyReadsMemory(F, 2);
1572 case LibFunc::vfscanf:
1573 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1574 !FTy->getParamType(2)->isPointerTy())
1577 setDoesNotCapture(F, 1);
1578 setDoesNotCapture(F, 2);
1579 setOnlyReadsMemory(F, 2);
1581 case LibFunc::valloc:
1582 if (!FTy->getReturnType()->isPointerTy())
1585 setDoesNotAlias(F, 0);
1587 case LibFunc::vprintf:
1588 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1591 setDoesNotCapture(F, 1);
1592 setOnlyReadsMemory(F, 1);
1594 case LibFunc::vfprintf:
1595 case LibFunc::vsprintf:
1596 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1597 !FTy->getParamType(1)->isPointerTy())
1600 setDoesNotCapture(F, 1);
1601 setDoesNotCapture(F, 2);
1602 setOnlyReadsMemory(F, 2);
1604 case LibFunc::vsnprintf:
1605 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1606 !FTy->getParamType(2)->isPointerTy())
1609 setDoesNotCapture(F, 1);
1610 setDoesNotCapture(F, 3);
1611 setOnlyReadsMemory(F, 3);
1614 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1616 // May throw; "open" is a valid pthread cancellation point.
1617 setDoesNotCapture(F, 1);
1618 setOnlyReadsMemory(F, 1);
1620 case LibFunc::opendir:
1621 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1622 !FTy->getParamType(0)->isPointerTy())
1625 setDoesNotAlias(F, 0);
1626 setDoesNotCapture(F, 1);
1627 setOnlyReadsMemory(F, 1);
1629 case LibFunc::tmpfile:
1630 if (!FTy->getReturnType()->isPointerTy())
1633 setDoesNotAlias(F, 0);
1635 case LibFunc::times:
1636 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1639 setDoesNotCapture(F, 1);
1641 case LibFunc::htonl:
1642 case LibFunc::htons:
1643 case LibFunc::ntohl:
1644 case LibFunc::ntohs:
1646 setDoesNotAccessMemory(F);
1648 case LibFunc::lstat:
1649 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1650 !FTy->getParamType(1)->isPointerTy())
1653 setDoesNotCapture(F, 1);
1654 setDoesNotCapture(F, 2);
1655 setOnlyReadsMemory(F, 1);
1657 case LibFunc::lchown:
1658 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1661 setDoesNotCapture(F, 1);
1662 setOnlyReadsMemory(F, 1);
1664 case LibFunc::qsort:
1665 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1667 // May throw; places call through function pointer.
1668 setDoesNotCapture(F, 4);
1670 case LibFunc::dunder_strdup:
1671 case LibFunc::dunder_strndup:
1672 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1673 !FTy->getParamType(0)->isPointerTy())
1676 setDoesNotAlias(F, 0);
1677 setDoesNotCapture(F, 1);
1678 setOnlyReadsMemory(F, 1);
1680 case LibFunc::dunder_strtok_r:
1681 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1684 setDoesNotCapture(F, 2);
1685 setOnlyReadsMemory(F, 2);
1687 case LibFunc::under_IO_getc:
1688 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1691 setDoesNotCapture(F, 1);
1693 case LibFunc::under_IO_putc:
1694 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1697 setDoesNotCapture(F, 2);
1699 case LibFunc::dunder_isoc99_scanf:
1700 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1703 setDoesNotCapture(F, 1);
1704 setOnlyReadsMemory(F, 1);
1706 case LibFunc::stat64:
1707 case LibFunc::lstat64:
1708 case LibFunc::statvfs64:
1709 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1710 !FTy->getParamType(1)->isPointerTy())
1713 setDoesNotCapture(F, 1);
1714 setDoesNotCapture(F, 2);
1715 setOnlyReadsMemory(F, 1);
1717 case LibFunc::dunder_isoc99_sscanf:
1718 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1719 !FTy->getParamType(1)->isPointerTy())
1722 setDoesNotCapture(F, 1);
1723 setDoesNotCapture(F, 2);
1724 setOnlyReadsMemory(F, 1);
1725 setOnlyReadsMemory(F, 2);
1727 case LibFunc::fopen64:
1728 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1729 !FTy->getParamType(0)->isPointerTy() ||
1730 !FTy->getParamType(1)->isPointerTy())
1733 setDoesNotAlias(F, 0);
1734 setDoesNotCapture(F, 1);
1735 setDoesNotCapture(F, 2);
1736 setOnlyReadsMemory(F, 1);
1737 setOnlyReadsMemory(F, 2);
1739 case LibFunc::fseeko64:
1740 case LibFunc::ftello64:
1741 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1744 setDoesNotCapture(F, 1);
1746 case LibFunc::tmpfile64:
1747 if (!FTy->getReturnType()->isPointerTy())
1750 setDoesNotAlias(F, 0);
1752 case LibFunc::fstat64:
1753 case LibFunc::fstatvfs64:
1754 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1757 setDoesNotCapture(F, 2);
1759 case LibFunc::open64:
1760 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1762 // May throw; "open" is a valid pthread cancellation point.
1763 setDoesNotCapture(F, 1);
1764 setOnlyReadsMemory(F, 1);
1766 case LibFunc::gettimeofday:
1767 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1768 !FTy->getParamType(1)->isPointerTy())
1770 // Currently some platforms have the restrict keyword on the arguments to
1771 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1774 setDoesNotCapture(F, 1);
1775 setDoesNotCapture(F, 2);
1778 // Didn't mark any attributes.
1785 /// Adds attributes to well-known standard library call declarations.
1786 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1787 bool MadeChange = false;
1789 // Check each function in turn annotating well-known library function
1790 // declarations with attributes.
1791 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1792 Function *F = (*I)->getFunction();
1794 if (F && F->isDeclaration())
1795 MadeChange |= inferPrototypeAttributes(*F);
1801 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1802 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1804 bool Changed = annotateLibraryCalls(SCC);
1805 Changed |= AddReadAttrs(SCC);
1806 Changed |= AddArgumentAttrs(SCC);
1807 Changed |= AddNoAliasAttrs(SCC);
1808 Changed |= AddNonNullAttrs(SCC);