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 AddNonNullAttrs(const CallGraphSCC &SCC);
78 bool annotateLibraryCalls(const CallGraphSCC &SCC);
82 char FunctionAttrs::ID = 0;
83 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
84 "Deduce function attributes", false, false)
85 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
86 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
87 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
88 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
89 "Deduce function attributes", false, false)
91 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
93 /// Deduce readonly/readnone attributes for the SCC.
94 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
95 SmallPtrSet<Function *, 8> SCCNodes;
97 // Fill SCCNodes with the elements of the SCC. Used for quickly
98 // looking up whether a given CallGraphNode is in this SCC.
99 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
100 SCCNodes.insert((*I)->getFunction());
102 // Check if any of the functions in the SCC read or write memory. If they
103 // write memory then they can't be marked readnone or readonly.
104 bool ReadsMemory = false;
105 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
106 Function *F = (*I)->getFunction();
108 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
109 // External node or node we don't want to optimize - assume it may write
110 // memory and give up.
113 // We need to manually construct BasicAA directly in order to disable its
114 // use of other function analyses.
115 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
117 // Construct our own AA results for this function. We do this manually to
118 // work around the limitations of the legacy pass manager.
119 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
121 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
122 if (MRB == FMRB_DoesNotAccessMemory)
126 // Definitions with weak linkage may be overridden at linktime with
127 // something that writes memory, so treat them like declarations.
128 if (F->isDeclaration() || F->mayBeOverridden()) {
129 if (!AliasAnalysis::onlyReadsMemory(MRB))
130 // May write memory. Just give up.
137 // Scan the function body for instructions that may read or write memory.
138 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
139 Instruction *I = &*II;
141 // Some instructions can be ignored even if they read or write memory.
142 // Detect these now, skipping to the next instruction if one is found.
143 CallSite CS(cast<Value>(I));
145 // Ignore calls to functions in the same SCC.
146 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
148 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
149 // If the call doesn't access arbitrary memory, we may be able to
150 // figure out something.
151 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
152 // If the call does access argument pointees, check each argument.
153 if (AliasAnalysis::doesAccessArgPointees(MRB))
154 // Check whether all pointer arguments point to local memory, and
155 // ignore calls that only access local memory.
156 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
159 if (Arg->getType()->isPointerTy()) {
161 I->getAAMetadata(AAInfo);
163 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
164 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
166 // Writes non-local memory. Give up.
169 // Ok, it reads non-local memory.
176 // The call could access any memory. If that includes writes, give up.
179 // If it reads, note it.
183 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
184 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
185 if (!LI->isVolatile()) {
186 MemoryLocation Loc = MemoryLocation::get(LI);
187 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
190 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
191 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
192 if (!SI->isVolatile()) {
193 MemoryLocation Loc = MemoryLocation::get(SI);
194 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
197 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
198 // Ignore vaargs on local memory.
199 MemoryLocation Loc = MemoryLocation::get(VI);
200 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
204 // Any remaining instructions need to be taken seriously! Check if they
205 // read or write memory.
206 if (I->mayWriteToMemory())
207 // Writes memory. Just give up.
210 // If this instruction may read memory, remember that.
211 ReadsMemory |= I->mayReadFromMemory();
215 // Success! Functions in this SCC do not access memory, or only read memory.
216 // Give them the appropriate attribute.
217 bool MadeChange = false;
218 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
219 Function *F = (*I)->getFunction();
221 if (F->doesNotAccessMemory())
225 if (F->onlyReadsMemory() && ReadsMemory)
231 // Clear out any existing attributes.
233 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
235 AttributeSet::FunctionIndex,
236 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
238 // Add in the new attribute.
239 F->addAttribute(AttributeSet::FunctionIndex,
240 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
252 /// For a given pointer Argument, this retains a list of Arguments of functions
253 /// in the same SCC that the pointer data flows into. We use this to build an
254 /// SCC of the arguments.
255 struct ArgumentGraphNode {
256 Argument *Definition;
257 SmallVector<ArgumentGraphNode *, 4> Uses;
260 class ArgumentGraph {
261 // We store pointers to ArgumentGraphNode objects, so it's important that
262 // that they not move around upon insert.
263 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
265 ArgumentMapTy ArgumentMap;
267 // There is no root node for the argument graph, in fact:
268 // void f(int *x, int *y) { if (...) f(x, y); }
269 // is an example where the graph is disconnected. The SCCIterator requires a
270 // single entry point, so we maintain a fake ("synthetic") root node that
271 // uses every node. Because the graph is directed and nothing points into
272 // the root, it will not participate in any SCCs (except for its own).
273 ArgumentGraphNode SyntheticRoot;
276 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
278 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
280 iterator begin() { return SyntheticRoot.Uses.begin(); }
281 iterator end() { return SyntheticRoot.Uses.end(); }
282 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
284 ArgumentGraphNode *operator[](Argument *A) {
285 ArgumentGraphNode &Node = ArgumentMap[A];
287 SyntheticRoot.Uses.push_back(&Node);
292 /// This tracker checks whether callees are in the SCC, and if so it does not
293 /// consider that a capture, instead adding it to the "Uses" list and
294 /// continuing with the analysis.
295 struct ArgumentUsesTracker : public CaptureTracker {
296 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
297 : Captured(false), SCCNodes(SCCNodes) {}
299 void tooManyUses() override { Captured = true; }
301 bool captured(const Use *U) override {
302 CallSite CS(U->getUser());
303 if (!CS.getInstruction()) {
308 Function *F = CS.getCalledFunction();
309 if (!F || !SCCNodes.count(F)) {
315 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
316 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
317 PI != PE; ++PI, ++AI) {
319 assert(F->isVarArg() && "More params than args in non-varargs call");
329 assert(Found && "Capturing call-site captured nothing?");
334 bool Captured; // True only if certainly captured (used outside our SCC).
335 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
337 const SmallPtrSet<Function *, 8> &SCCNodes;
342 template <> struct GraphTraits<ArgumentGraphNode *> {
343 typedef ArgumentGraphNode NodeType;
344 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
346 static inline NodeType *getEntryNode(NodeType *A) { return A; }
347 static inline ChildIteratorType child_begin(NodeType *N) {
348 return N->Uses.begin();
350 static inline ChildIteratorType child_end(NodeType *N) {
351 return N->Uses.end();
355 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
356 static NodeType *getEntryNode(ArgumentGraph *AG) {
357 return AG->getEntryNode();
359 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
362 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
366 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
367 static Attribute::AttrKind
368 determinePointerReadAttrs(Argument *A,
369 const SmallPtrSet<Argument *, 8> &SCCNodes) {
371 SmallVector<Use *, 32> Worklist;
372 SmallSet<Use *, 32> Visited;
374 // inalloca arguments are always clobbered by the call.
375 if (A->hasInAllocaAttr())
376 return Attribute::None;
379 // We don't need to track IsWritten. If A is written to, return immediately.
381 for (Use &U : A->uses()) {
383 Worklist.push_back(&U);
386 while (!Worklist.empty()) {
387 Use *U = Worklist.pop_back_val();
388 Instruction *I = cast<Instruction>(U->getUser());
391 switch (I->getOpcode()) {
392 case Instruction::BitCast:
393 case Instruction::GetElementPtr:
394 case Instruction::PHI:
395 case Instruction::Select:
396 case Instruction::AddrSpaceCast:
397 // The original value is not read/written via this if the new value isn't.
398 for (Use &UU : I->uses())
399 if (Visited.insert(&UU).second)
400 Worklist.push_back(&UU);
403 case Instruction::Call:
404 case Instruction::Invoke: {
405 bool Captures = true;
407 if (I->getType()->isVoidTy())
410 auto AddUsersToWorklistIfCapturing = [&] {
412 for (Use &UU : I->uses())
413 if (Visited.insert(&UU).second)
414 Worklist.push_back(&UU);
418 if (CS.doesNotAccessMemory()) {
419 AddUsersToWorklistIfCapturing();
423 Function *F = CS.getCalledFunction();
425 if (CS.onlyReadsMemory()) {
427 AddUsersToWorklistIfCapturing();
430 return Attribute::None;
433 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
434 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
435 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
438 assert(F->isVarArg() &&
439 "More params than args in non-varargs call.");
440 return Attribute::None;
442 Captures &= !CS.doesNotCapture(A - B);
443 if (SCCNodes.count(AI))
445 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
446 return Attribute::None;
447 if (!CS.doesNotAccessMemory(A - B))
451 AddUsersToWorklistIfCapturing();
455 case Instruction::Load:
459 case Instruction::ICmp:
460 case Instruction::Ret:
464 return Attribute::None;
468 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
471 /// Deduce nocapture attributes for the SCC.
472 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
473 bool Changed = false;
475 SmallPtrSet<Function *, 8> SCCNodes;
477 // Fill SCCNodes with the elements of the SCC. Used for quickly
478 // looking up whether a given CallGraphNode is in this SCC.
479 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
480 Function *F = (*I)->getFunction();
481 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
482 !F->hasFnAttribute(Attribute::OptimizeNone))
489 B.addAttribute(Attribute::NoCapture);
491 // Check each function in turn, determining which pointer arguments are not
493 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
494 Function *F = (*I)->getFunction();
496 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
497 // External node or function we're trying not to optimize - only a problem
498 // for arguments that we pass to it.
501 // Definitions with weak linkage may be overridden at linktime with
502 // something that captures pointers, so treat them like declarations.
503 if (F->isDeclaration() || F->mayBeOverridden())
506 // Functions that are readonly (or readnone) and nounwind and don't return
507 // a value can't capture arguments. Don't analyze them.
508 if (F->onlyReadsMemory() && F->doesNotThrow() &&
509 F->getReturnType()->isVoidTy()) {
510 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
512 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
513 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
521 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
523 if (!A->getType()->isPointerTy())
525 bool HasNonLocalUses = false;
526 if (!A->hasNoCaptureAttr()) {
527 ArgumentUsesTracker Tracker(SCCNodes);
528 PointerMayBeCaptured(A, &Tracker);
529 if (!Tracker.Captured) {
530 if (Tracker.Uses.empty()) {
531 // If it's trivially not captured, mark it nocapture now.
533 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
537 // If it's not trivially captured and not trivially not captured,
538 // then it must be calling into another function in our SCC. Save
539 // its particulars for Argument-SCC analysis later.
540 ArgumentGraphNode *Node = AG[A];
541 for (SmallVectorImpl<Argument *>::iterator
542 UI = Tracker.Uses.begin(),
543 UE = Tracker.Uses.end();
545 Node->Uses.push_back(AG[*UI]);
547 HasNonLocalUses = true;
551 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
553 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
554 // Can we determine that it's readonly/readnone without doing an SCC?
555 // Note that we don't allow any calls at all here, or else our result
556 // will be dependent on the iteration order through the functions in the
558 SmallPtrSet<Argument *, 8> Self;
560 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
561 if (R != Attribute::None) {
564 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
566 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
572 // The graph we've collected is partial because we stopped scanning for
573 // argument uses once we solved the argument trivially. These partial nodes
574 // show up as ArgumentGraphNode objects with an empty Uses list, and for
575 // these nodes the final decision about whether they capture has already been
576 // made. If the definition doesn't have a 'nocapture' attribute by now, it
579 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
580 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
581 if (ArgumentSCC.size() == 1) {
582 if (!ArgumentSCC[0]->Definition)
583 continue; // synthetic root node
585 // eg. "void f(int* x) { if (...) f(x); }"
586 if (ArgumentSCC[0]->Uses.size() == 1 &&
587 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
588 Argument *A = ArgumentSCC[0]->Definition;
589 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
596 bool SCCCaptured = false;
597 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
598 I != E && !SCCCaptured; ++I) {
599 ArgumentGraphNode *Node = *I;
600 if (Node->Uses.empty()) {
601 if (!Node->Definition->hasNoCaptureAttr())
608 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
609 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
610 // quickly looking up whether a given Argument is in this ArgumentSCC.
611 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
612 ArgumentSCCNodes.insert((*I)->Definition);
615 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
616 I != E && !SCCCaptured; ++I) {
617 ArgumentGraphNode *N = *I;
618 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
621 Argument *A = (*UI)->Definition;
622 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
631 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
632 Argument *A = ArgumentSCC[i]->Definition;
633 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
638 // We also want to compute readonly/readnone. With a small number of false
639 // negatives, we can assume that any pointer which is captured isn't going
640 // to be provably readonly or readnone, since by definition we can't
641 // analyze all uses of a captured pointer.
643 // The false negatives happen when the pointer is captured by a function
644 // that promises readonly/readnone behaviour on the pointer, then the
645 // pointer's lifetime ends before anything that writes to arbitrary memory.
646 // Also, a readonly/readnone pointer may be returned, but returning a
647 // pointer is capturing it.
649 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
650 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
651 Argument *A = ArgumentSCC[i]->Definition;
652 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
653 if (K == Attribute::ReadNone)
655 if (K == Attribute::ReadOnly) {
656 ReadAttr = Attribute::ReadOnly;
663 if (ReadAttr != Attribute::None) {
665 B.addAttribute(ReadAttr);
666 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
667 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
668 Argument *A = ArgumentSCC[i]->Definition;
669 // Clear out existing readonly/readnone attributes
670 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
671 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
672 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
681 /// Tests whether a function is "malloc-like".
683 /// A function is "malloc-like" if it returns either null or a pointer that
684 /// doesn't alias any other pointer visible to the caller.
685 bool FunctionAttrs::IsFunctionMallocLike(
686 Function *F, SmallPtrSet<Function *, 8> &SCCNodes) const {
687 SmallSetVector<Value *, 8> FlowsToReturn;
688 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
689 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
690 FlowsToReturn.insert(Ret->getReturnValue());
692 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
693 Value *RetVal = FlowsToReturn[i];
695 if (Constant *C = dyn_cast<Constant>(RetVal)) {
696 if (!C->isNullValue() && !isa<UndefValue>(C))
702 if (isa<Argument>(RetVal))
705 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
706 switch (RVI->getOpcode()) {
707 // Extend the analysis by looking upwards.
708 case Instruction::BitCast:
709 case Instruction::GetElementPtr:
710 case Instruction::AddrSpaceCast:
711 FlowsToReturn.insert(RVI->getOperand(0));
713 case Instruction::Select: {
714 SelectInst *SI = cast<SelectInst>(RVI);
715 FlowsToReturn.insert(SI->getTrueValue());
716 FlowsToReturn.insert(SI->getFalseValue());
719 case Instruction::PHI: {
720 PHINode *PN = cast<PHINode>(RVI);
721 for (Value *IncValue : PN->incoming_values())
722 FlowsToReturn.insert(IncValue);
726 // Check whether the pointer came from an allocation.
727 case Instruction::Alloca:
729 case Instruction::Call:
730 case Instruction::Invoke: {
732 if (CS.paramHasAttr(0, Attribute::NoAlias))
734 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
738 return false; // Did not come from an allocation.
741 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
748 /// Deduce noalias attributes for the SCC.
749 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
750 SmallPtrSet<Function *, 8> SCCNodes;
752 // Fill SCCNodes with the elements of the SCC. Used for quickly
753 // looking up whether a given CallGraphNode is in this SCC.
754 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
755 SCCNodes.insert((*I)->getFunction());
757 // Check each function in turn, determining which functions return noalias
759 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
760 Function *F = (*I)->getFunction();
762 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
763 // External node or node we don't want to optimize - skip it;
767 if (F->doesNotAlias(0))
770 // Definitions with weak linkage may be overridden at linktime, so
771 // treat them like declarations.
772 if (F->isDeclaration() || F->mayBeOverridden())
775 // We annotate noalias return values, which are only applicable to
777 if (!F->getReturnType()->isPointerTy())
780 if (!IsFunctionMallocLike(F, SCCNodes))
784 bool MadeChange = false;
785 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
786 Function *F = (*I)->getFunction();
787 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
790 F->setDoesNotAlias(0);
798 /// Tests whether this function is known to not return null.
800 /// Requires that the function returns a pointer.
802 /// Returns true if it believes the function will not return a null, and sets
803 /// \p Speculative based on whether the returned conclusion is a speculative
804 /// conclusion due to SCC calls.
805 static bool isReturnNonNull(Function *F, SmallPtrSet<Function *, 8> &SCCNodes,
806 const TargetLibraryInfo &TLI, bool &Speculative) {
807 assert(F->getReturnType()->isPointerTy() &&
808 "nonnull only meaningful on pointer types");
811 SmallSetVector<Value *, 8> FlowsToReturn;
812 for (BasicBlock &BB : *F)
813 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
814 FlowsToReturn.insert(Ret->getReturnValue());
816 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
817 Value *RetVal = FlowsToReturn[i];
819 // If this value is locally known to be non-null, we're good
820 if (isKnownNonNull(RetVal, &TLI))
823 // Otherwise, we need to look upwards since we can't make any local
825 Instruction *RVI = dyn_cast<Instruction>(RetVal);
828 switch (RVI->getOpcode()) {
829 // Extend the analysis by looking upwards.
830 case Instruction::BitCast:
831 case Instruction::GetElementPtr:
832 case Instruction::AddrSpaceCast:
833 FlowsToReturn.insert(RVI->getOperand(0));
835 case Instruction::Select: {
836 SelectInst *SI = cast<SelectInst>(RVI);
837 FlowsToReturn.insert(SI->getTrueValue());
838 FlowsToReturn.insert(SI->getFalseValue());
841 case Instruction::PHI: {
842 PHINode *PN = cast<PHINode>(RVI);
843 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
844 FlowsToReturn.insert(PN->getIncomingValue(i));
847 case Instruction::Call:
848 case Instruction::Invoke: {
850 Function *Callee = CS.getCalledFunction();
851 // A call to a node within the SCC is assumed to return null until
853 if (Callee && SCCNodes.count(Callee)) {
860 return false; // Unknown source, may be null
862 llvm_unreachable("should have either continued or returned");
868 /// Deduce nonnull attributes for the SCC.
869 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
870 SmallPtrSet<Function *, 8> SCCNodes;
872 // Fill SCCNodes with the elements of the SCC. Used for quickly
873 // looking up whether a given CallGraphNode is in this SCC.
874 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
875 SCCNodes.insert((*I)->getFunction());
877 // Speculative that all functions in the SCC return only nonnull
878 // pointers. We may refute this as we analyze functions.
879 bool SCCReturnsNonNull = true;
881 bool MadeChange = false;
883 // Check each function in turn, determining which functions return nonnull
885 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
886 Function *F = (*I)->getFunction();
888 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
889 // External node or node we don't want to optimize - skip it;
893 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
897 // Definitions with weak linkage may be overridden at linktime, so
898 // treat them like declarations.
899 if (F->isDeclaration() || F->mayBeOverridden())
902 // We annotate nonnull return values, which are only applicable to
904 if (!F->getReturnType()->isPointerTy())
907 bool Speculative = false;
908 if (isReturnNonNull(F, SCCNodes, *TLI, Speculative)) {
910 // Mark the function eagerly since we may discover a function
911 // which prevents us from speculating about the entire SCC
912 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
913 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
919 // At least one function returns something which could be null, can't
920 // speculate any more.
921 SCCReturnsNonNull = false;
924 if (SCCReturnsNonNull) {
925 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
926 Function *F = (*I)->getFunction();
927 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
928 Attribute::NonNull) ||
929 !F->getReturnType()->isPointerTy())
932 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
933 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
942 static void setDoesNotAccessMemory(Function &F) {
943 if (!F.doesNotAccessMemory()) {
944 F.setDoesNotAccessMemory();
949 static void setOnlyReadsMemory(Function &F) {
950 if (!F.onlyReadsMemory()) {
951 F.setOnlyReadsMemory();
956 static void setDoesNotThrow(Function &F) {
957 if (!F.doesNotThrow()) {
963 static void setDoesNotCapture(Function &F, unsigned n) {
964 if (!F.doesNotCapture(n)) {
965 F.setDoesNotCapture(n);
970 static void setOnlyReadsMemory(Function &F, unsigned n) {
971 if (!F.onlyReadsMemory(n)) {
972 F.setOnlyReadsMemory(n);
977 static void setDoesNotAlias(Function &F, unsigned n) {
978 if (!F.doesNotAlias(n)) {
979 F.setDoesNotAlias(n);
984 /// Analyze the name and prototype of the given function and set any applicable
987 /// Returns true if any attributes were set and false otherwise.
988 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
989 if (F.hasFnAttribute(Attribute::OptimizeNone))
992 FunctionType *FTy = F.getFunctionType();
993 LibFunc::Func TheLibFunc;
994 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
997 switch (TheLibFunc) {
998 case LibFunc::strlen:
999 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1001 setOnlyReadsMemory(F);
1003 setDoesNotCapture(F, 1);
1005 case LibFunc::strchr:
1006 case LibFunc::strrchr:
1007 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1008 !FTy->getParamType(1)->isIntegerTy())
1010 setOnlyReadsMemory(F);
1013 case LibFunc::strtol:
1014 case LibFunc::strtod:
1015 case LibFunc::strtof:
1016 case LibFunc::strtoul:
1017 case LibFunc::strtoll:
1018 case LibFunc::strtold:
1019 case LibFunc::strtoull:
1020 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1023 setDoesNotCapture(F, 2);
1024 setOnlyReadsMemory(F, 1);
1026 case LibFunc::strcpy:
1027 case LibFunc::stpcpy:
1028 case LibFunc::strcat:
1029 case LibFunc::strncat:
1030 case LibFunc::strncpy:
1031 case LibFunc::stpncpy:
1032 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1035 setDoesNotCapture(F, 2);
1036 setOnlyReadsMemory(F, 2);
1038 case LibFunc::strxfrm:
1039 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1040 !FTy->getParamType(1)->isPointerTy())
1043 setDoesNotCapture(F, 1);
1044 setDoesNotCapture(F, 2);
1045 setOnlyReadsMemory(F, 2);
1047 case LibFunc::strcmp: // 0,1
1048 case LibFunc::strspn: // 0,1
1049 case LibFunc::strncmp: // 0,1
1050 case LibFunc::strcspn: // 0,1
1051 case LibFunc::strcoll: // 0,1
1052 case LibFunc::strcasecmp: // 0,1
1053 case LibFunc::strncasecmp: //
1054 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1055 !FTy->getParamType(1)->isPointerTy())
1057 setOnlyReadsMemory(F);
1059 setDoesNotCapture(F, 1);
1060 setDoesNotCapture(F, 2);
1062 case LibFunc::strstr:
1063 case LibFunc::strpbrk:
1064 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1066 setOnlyReadsMemory(F);
1068 setDoesNotCapture(F, 2);
1070 case LibFunc::strtok:
1071 case LibFunc::strtok_r:
1072 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1075 setDoesNotCapture(F, 2);
1076 setOnlyReadsMemory(F, 2);
1078 case LibFunc::scanf:
1079 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1082 setDoesNotCapture(F, 1);
1083 setOnlyReadsMemory(F, 1);
1085 case LibFunc::setbuf:
1086 case LibFunc::setvbuf:
1087 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1090 setDoesNotCapture(F, 1);
1092 case LibFunc::strdup:
1093 case LibFunc::strndup:
1094 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1095 !FTy->getParamType(0)->isPointerTy())
1098 setDoesNotAlias(F, 0);
1099 setDoesNotCapture(F, 1);
1100 setOnlyReadsMemory(F, 1);
1103 case LibFunc::statvfs:
1104 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1105 !FTy->getParamType(1)->isPointerTy())
1108 setDoesNotCapture(F, 1);
1109 setDoesNotCapture(F, 2);
1110 setOnlyReadsMemory(F, 1);
1112 case LibFunc::sscanf:
1113 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1114 !FTy->getParamType(1)->isPointerTy())
1117 setDoesNotCapture(F, 1);
1118 setDoesNotCapture(F, 2);
1119 setOnlyReadsMemory(F, 1);
1120 setOnlyReadsMemory(F, 2);
1122 case LibFunc::sprintf:
1123 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1124 !FTy->getParamType(1)->isPointerTy())
1127 setDoesNotCapture(F, 1);
1128 setDoesNotCapture(F, 2);
1129 setOnlyReadsMemory(F, 2);
1131 case LibFunc::snprintf:
1132 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1133 !FTy->getParamType(2)->isPointerTy())
1136 setDoesNotCapture(F, 1);
1137 setDoesNotCapture(F, 3);
1138 setOnlyReadsMemory(F, 3);
1140 case LibFunc::setitimer:
1141 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1142 !FTy->getParamType(2)->isPointerTy())
1145 setDoesNotCapture(F, 2);
1146 setDoesNotCapture(F, 3);
1147 setOnlyReadsMemory(F, 2);
1149 case LibFunc::system:
1150 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1152 // May throw; "system" is a valid pthread cancellation point.
1153 setDoesNotCapture(F, 1);
1154 setOnlyReadsMemory(F, 1);
1156 case LibFunc::malloc:
1157 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1160 setDoesNotAlias(F, 0);
1162 case LibFunc::memcmp:
1163 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1164 !FTy->getParamType(1)->isPointerTy())
1166 setOnlyReadsMemory(F);
1168 setDoesNotCapture(F, 1);
1169 setDoesNotCapture(F, 2);
1171 case LibFunc::memchr:
1172 case LibFunc::memrchr:
1173 if (FTy->getNumParams() != 3)
1175 setOnlyReadsMemory(F);
1179 case LibFunc::modff:
1180 case LibFunc::modfl:
1181 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1184 setDoesNotCapture(F, 2);
1186 case LibFunc::memcpy:
1187 case LibFunc::memccpy:
1188 case LibFunc::memmove:
1189 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1192 setDoesNotCapture(F, 2);
1193 setOnlyReadsMemory(F, 2);
1195 case LibFunc::memalign:
1196 if (!FTy->getReturnType()->isPointerTy())
1198 setDoesNotAlias(F, 0);
1200 case LibFunc::mkdir:
1201 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1204 setDoesNotCapture(F, 1);
1205 setOnlyReadsMemory(F, 1);
1207 case LibFunc::mktime:
1208 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1211 setDoesNotCapture(F, 1);
1213 case LibFunc::realloc:
1214 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1215 !FTy->getReturnType()->isPointerTy())
1218 setDoesNotAlias(F, 0);
1219 setDoesNotCapture(F, 1);
1222 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1224 // May throw; "read" is a valid pthread cancellation point.
1225 setDoesNotCapture(F, 2);
1227 case LibFunc::rewind:
1228 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1231 setDoesNotCapture(F, 1);
1233 case LibFunc::rmdir:
1234 case LibFunc::remove:
1235 case LibFunc::realpath:
1236 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1239 setDoesNotCapture(F, 1);
1240 setOnlyReadsMemory(F, 1);
1242 case LibFunc::rename:
1243 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1244 !FTy->getParamType(1)->isPointerTy())
1247 setDoesNotCapture(F, 1);
1248 setDoesNotCapture(F, 2);
1249 setOnlyReadsMemory(F, 1);
1250 setOnlyReadsMemory(F, 2);
1252 case LibFunc::readlink:
1253 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1254 !FTy->getParamType(1)->isPointerTy())
1257 setDoesNotCapture(F, 1);
1258 setDoesNotCapture(F, 2);
1259 setOnlyReadsMemory(F, 1);
1261 case LibFunc::write:
1262 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1264 // May throw; "write" is a valid pthread cancellation point.
1265 setDoesNotCapture(F, 2);
1266 setOnlyReadsMemory(F, 2);
1268 case LibFunc::bcopy:
1269 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1270 !FTy->getParamType(1)->isPointerTy())
1273 setDoesNotCapture(F, 1);
1274 setDoesNotCapture(F, 2);
1275 setOnlyReadsMemory(F, 1);
1278 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1279 !FTy->getParamType(1)->isPointerTy())
1282 setOnlyReadsMemory(F);
1283 setDoesNotCapture(F, 1);
1284 setDoesNotCapture(F, 2);
1286 case LibFunc::bzero:
1287 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1290 setDoesNotCapture(F, 1);
1292 case LibFunc::calloc:
1293 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1296 setDoesNotAlias(F, 0);
1298 case LibFunc::chmod:
1299 case LibFunc::chown:
1300 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1303 setDoesNotCapture(F, 1);
1304 setOnlyReadsMemory(F, 1);
1306 case LibFunc::ctermid:
1307 case LibFunc::clearerr:
1308 case LibFunc::closedir:
1309 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1312 setDoesNotCapture(F, 1);
1317 case LibFunc::atoll:
1318 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1321 setOnlyReadsMemory(F);
1322 setDoesNotCapture(F, 1);
1324 case LibFunc::access:
1325 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1328 setDoesNotCapture(F, 1);
1329 setOnlyReadsMemory(F, 1);
1331 case LibFunc::fopen:
1332 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1333 !FTy->getParamType(0)->isPointerTy() ||
1334 !FTy->getParamType(1)->isPointerTy())
1337 setDoesNotAlias(F, 0);
1338 setDoesNotCapture(F, 1);
1339 setDoesNotCapture(F, 2);
1340 setOnlyReadsMemory(F, 1);
1341 setOnlyReadsMemory(F, 2);
1343 case LibFunc::fdopen:
1344 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1345 !FTy->getParamType(1)->isPointerTy())
1348 setDoesNotAlias(F, 0);
1349 setDoesNotCapture(F, 2);
1350 setOnlyReadsMemory(F, 2);
1354 case LibFunc::fseek:
1355 case LibFunc::ftell:
1356 case LibFunc::fgetc:
1357 case LibFunc::fseeko:
1358 case LibFunc::ftello:
1359 case LibFunc::fileno:
1360 case LibFunc::fflush:
1361 case LibFunc::fclose:
1362 case LibFunc::fsetpos:
1363 case LibFunc::flockfile:
1364 case LibFunc::funlockfile:
1365 case LibFunc::ftrylockfile:
1366 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1369 setDoesNotCapture(F, 1);
1371 case LibFunc::ferror:
1372 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1375 setDoesNotCapture(F, 1);
1376 setOnlyReadsMemory(F);
1378 case LibFunc::fputc:
1379 case LibFunc::fstat:
1380 case LibFunc::frexp:
1381 case LibFunc::frexpf:
1382 case LibFunc::frexpl:
1383 case LibFunc::fstatvfs:
1384 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1387 setDoesNotCapture(F, 2);
1389 case LibFunc::fgets:
1390 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1391 !FTy->getParamType(2)->isPointerTy())
1394 setDoesNotCapture(F, 3);
1396 case LibFunc::fread:
1397 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1398 !FTy->getParamType(3)->isPointerTy())
1401 setDoesNotCapture(F, 1);
1402 setDoesNotCapture(F, 4);
1404 case LibFunc::fwrite:
1405 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1406 !FTy->getParamType(3)->isPointerTy())
1409 setDoesNotCapture(F, 1);
1410 setDoesNotCapture(F, 4);
1412 case LibFunc::fputs:
1413 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1414 !FTy->getParamType(1)->isPointerTy())
1417 setDoesNotCapture(F, 1);
1418 setDoesNotCapture(F, 2);
1419 setOnlyReadsMemory(F, 1);
1421 case LibFunc::fscanf:
1422 case LibFunc::fprintf:
1423 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1424 !FTy->getParamType(1)->isPointerTy())
1427 setDoesNotCapture(F, 1);
1428 setDoesNotCapture(F, 2);
1429 setOnlyReadsMemory(F, 2);
1431 case LibFunc::fgetpos:
1432 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1433 !FTy->getParamType(1)->isPointerTy())
1436 setDoesNotCapture(F, 1);
1437 setDoesNotCapture(F, 2);
1440 case LibFunc::getlogin_r:
1441 case LibFunc::getc_unlocked:
1442 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1445 setDoesNotCapture(F, 1);
1447 case LibFunc::getenv:
1448 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1451 setOnlyReadsMemory(F);
1452 setDoesNotCapture(F, 1);
1455 case LibFunc::getchar:
1458 case LibFunc::getitimer:
1459 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1462 setDoesNotCapture(F, 2);
1464 case LibFunc::getpwnam:
1465 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1468 setDoesNotCapture(F, 1);
1469 setOnlyReadsMemory(F, 1);
1471 case LibFunc::ungetc:
1472 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1475 setDoesNotCapture(F, 2);
1477 case LibFunc::uname:
1478 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1481 setDoesNotCapture(F, 1);
1483 case LibFunc::unlink:
1484 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1487 setDoesNotCapture(F, 1);
1488 setOnlyReadsMemory(F, 1);
1490 case LibFunc::unsetenv:
1491 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1494 setDoesNotCapture(F, 1);
1495 setOnlyReadsMemory(F, 1);
1497 case LibFunc::utime:
1498 case LibFunc::utimes:
1499 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1500 !FTy->getParamType(1)->isPointerTy())
1503 setDoesNotCapture(F, 1);
1504 setDoesNotCapture(F, 2);
1505 setOnlyReadsMemory(F, 1);
1506 setOnlyReadsMemory(F, 2);
1509 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1512 setDoesNotCapture(F, 2);
1515 case LibFunc::printf:
1516 case LibFunc::perror:
1517 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1520 setDoesNotCapture(F, 1);
1521 setOnlyReadsMemory(F, 1);
1523 case LibFunc::pread:
1524 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1526 // May throw; "pread" is a valid pthread cancellation point.
1527 setDoesNotCapture(F, 2);
1529 case LibFunc::pwrite:
1530 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1532 // May throw; "pwrite" is a valid pthread cancellation point.
1533 setDoesNotCapture(F, 2);
1534 setOnlyReadsMemory(F, 2);
1536 case LibFunc::putchar:
1539 case LibFunc::popen:
1540 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1541 !FTy->getParamType(0)->isPointerTy() ||
1542 !FTy->getParamType(1)->isPointerTy())
1545 setDoesNotAlias(F, 0);
1546 setDoesNotCapture(F, 1);
1547 setDoesNotCapture(F, 2);
1548 setOnlyReadsMemory(F, 1);
1549 setOnlyReadsMemory(F, 2);
1551 case LibFunc::pclose:
1552 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1555 setDoesNotCapture(F, 1);
1557 case LibFunc::vscanf:
1558 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1561 setDoesNotCapture(F, 1);
1562 setOnlyReadsMemory(F, 1);
1564 case LibFunc::vsscanf:
1565 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1566 !FTy->getParamType(2)->isPointerTy())
1569 setDoesNotCapture(F, 1);
1570 setDoesNotCapture(F, 2);
1571 setOnlyReadsMemory(F, 1);
1572 setOnlyReadsMemory(F, 2);
1574 case LibFunc::vfscanf:
1575 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1576 !FTy->getParamType(2)->isPointerTy())
1579 setDoesNotCapture(F, 1);
1580 setDoesNotCapture(F, 2);
1581 setOnlyReadsMemory(F, 2);
1583 case LibFunc::valloc:
1584 if (!FTy->getReturnType()->isPointerTy())
1587 setDoesNotAlias(F, 0);
1589 case LibFunc::vprintf:
1590 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1593 setDoesNotCapture(F, 1);
1594 setOnlyReadsMemory(F, 1);
1596 case LibFunc::vfprintf:
1597 case LibFunc::vsprintf:
1598 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1599 !FTy->getParamType(1)->isPointerTy())
1602 setDoesNotCapture(F, 1);
1603 setDoesNotCapture(F, 2);
1604 setOnlyReadsMemory(F, 2);
1606 case LibFunc::vsnprintf:
1607 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1608 !FTy->getParamType(2)->isPointerTy())
1611 setDoesNotCapture(F, 1);
1612 setDoesNotCapture(F, 3);
1613 setOnlyReadsMemory(F, 3);
1616 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1618 // May throw; "open" is a valid pthread cancellation point.
1619 setDoesNotCapture(F, 1);
1620 setOnlyReadsMemory(F, 1);
1622 case LibFunc::opendir:
1623 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1624 !FTy->getParamType(0)->isPointerTy())
1627 setDoesNotAlias(F, 0);
1628 setDoesNotCapture(F, 1);
1629 setOnlyReadsMemory(F, 1);
1631 case LibFunc::tmpfile:
1632 if (!FTy->getReturnType()->isPointerTy())
1635 setDoesNotAlias(F, 0);
1637 case LibFunc::times:
1638 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1641 setDoesNotCapture(F, 1);
1643 case LibFunc::htonl:
1644 case LibFunc::htons:
1645 case LibFunc::ntohl:
1646 case LibFunc::ntohs:
1648 setDoesNotAccessMemory(F);
1650 case LibFunc::lstat:
1651 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1652 !FTy->getParamType(1)->isPointerTy())
1655 setDoesNotCapture(F, 1);
1656 setDoesNotCapture(F, 2);
1657 setOnlyReadsMemory(F, 1);
1659 case LibFunc::lchown:
1660 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1663 setDoesNotCapture(F, 1);
1664 setOnlyReadsMemory(F, 1);
1666 case LibFunc::qsort:
1667 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1669 // May throw; places call through function pointer.
1670 setDoesNotCapture(F, 4);
1672 case LibFunc::dunder_strdup:
1673 case LibFunc::dunder_strndup:
1674 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1675 !FTy->getParamType(0)->isPointerTy())
1678 setDoesNotAlias(F, 0);
1679 setDoesNotCapture(F, 1);
1680 setOnlyReadsMemory(F, 1);
1682 case LibFunc::dunder_strtok_r:
1683 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1686 setDoesNotCapture(F, 2);
1687 setOnlyReadsMemory(F, 2);
1689 case LibFunc::under_IO_getc:
1690 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1693 setDoesNotCapture(F, 1);
1695 case LibFunc::under_IO_putc:
1696 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1699 setDoesNotCapture(F, 2);
1701 case LibFunc::dunder_isoc99_scanf:
1702 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1705 setDoesNotCapture(F, 1);
1706 setOnlyReadsMemory(F, 1);
1708 case LibFunc::stat64:
1709 case LibFunc::lstat64:
1710 case LibFunc::statvfs64:
1711 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1712 !FTy->getParamType(1)->isPointerTy())
1715 setDoesNotCapture(F, 1);
1716 setDoesNotCapture(F, 2);
1717 setOnlyReadsMemory(F, 1);
1719 case LibFunc::dunder_isoc99_sscanf:
1720 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1721 !FTy->getParamType(1)->isPointerTy())
1724 setDoesNotCapture(F, 1);
1725 setDoesNotCapture(F, 2);
1726 setOnlyReadsMemory(F, 1);
1727 setOnlyReadsMemory(F, 2);
1729 case LibFunc::fopen64:
1730 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1731 !FTy->getParamType(0)->isPointerTy() ||
1732 !FTy->getParamType(1)->isPointerTy())
1735 setDoesNotAlias(F, 0);
1736 setDoesNotCapture(F, 1);
1737 setDoesNotCapture(F, 2);
1738 setOnlyReadsMemory(F, 1);
1739 setOnlyReadsMemory(F, 2);
1741 case LibFunc::fseeko64:
1742 case LibFunc::ftello64:
1743 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1746 setDoesNotCapture(F, 1);
1748 case LibFunc::tmpfile64:
1749 if (!FTy->getReturnType()->isPointerTy())
1752 setDoesNotAlias(F, 0);
1754 case LibFunc::fstat64:
1755 case LibFunc::fstatvfs64:
1756 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1759 setDoesNotCapture(F, 2);
1761 case LibFunc::open64:
1762 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1764 // May throw; "open" is a valid pthread cancellation point.
1765 setDoesNotCapture(F, 1);
1766 setOnlyReadsMemory(F, 1);
1768 case LibFunc::gettimeofday:
1769 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1770 !FTy->getParamType(1)->isPointerTy())
1772 // Currently some platforms have the restrict keyword on the arguments to
1773 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1776 setDoesNotCapture(F, 1);
1777 setDoesNotCapture(F, 2);
1780 // Didn't mark any attributes.
1787 /// Adds attributes to well-known standard library call declarations.
1788 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1789 bool MadeChange = false;
1791 // Check each function in turn annotating well-known library function
1792 // declarations with attributes.
1793 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1794 Function *F = (*I)->getFunction();
1796 if (F && F->isDeclaration())
1797 MadeChange |= inferPrototypeAttributes(*F, *TLI);
1803 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1804 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1806 bool Changed = annotateLibraryCalls(SCC);
1807 Changed |= AddReadAttrs(SCC);
1808 Changed |= AddArgumentAttrs(SCC);
1809 Changed |= AddNoAliasAttrs(SCC);
1810 Changed |= AddNonNullAttrs(SCC);