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 bool AddReadAttrs(const CallGraphSCC &SCC);
64 bool AddArgumentAttrs(const CallGraphSCC &SCC);
65 bool IsFunctionMallocLike(Function *F, SmallPtrSet<Function *, 8> &) const;
66 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
67 bool ReturnsNonNull(Function *F, SmallPtrSet<Function *, 8> &,
68 bool &Speculative) const;
69 bool AddNonNullAttrs(const CallGraphSCC &SCC);
71 // Utility methods used by inferPrototypeAttributes to add attributes
72 // and maintain annotation statistics.
74 void setDoesNotAccessMemory(Function &F) {
75 if (!F.doesNotAccessMemory()) {
76 F.setDoesNotAccessMemory();
81 void setOnlyReadsMemory(Function &F) {
82 if (!F.onlyReadsMemory()) {
83 F.setOnlyReadsMemory();
88 void setDoesNotThrow(Function &F) {
89 if (!F.doesNotThrow()) {
95 void setDoesNotCapture(Function &F, unsigned n) {
96 if (!F.doesNotCapture(n)) {
97 F.setDoesNotCapture(n);
102 void setOnlyReadsMemory(Function &F, unsigned n) {
103 if (!F.onlyReadsMemory(n)) {
104 F.setOnlyReadsMemory(n);
109 void setDoesNotAlias(Function &F, unsigned n) {
110 if (!F.doesNotAlias(n)) {
111 F.setDoesNotAlias(n);
116 bool inferPrototypeAttributes(Function &F);
118 bool annotateLibraryCalls(const CallGraphSCC &SCC);
120 void getAnalysisUsage(AnalysisUsage &AU) const override {
121 AU.setPreservesCFG();
122 AU.addRequired<AssumptionCacheTracker>();
123 AU.addRequired<TargetLibraryInfoWrapperPass>();
124 CallGraphSCCPass::getAnalysisUsage(AU);
128 TargetLibraryInfo *TLI;
132 char FunctionAttrs::ID = 0;
133 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
134 "Deduce function attributes", false, false)
135 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
136 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
137 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
138 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
139 "Deduce function attributes", false, false)
141 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
143 /// Deduce readonly/readnone attributes for the SCC.
144 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
145 SmallPtrSet<Function *, 8> SCCNodes;
147 // Fill SCCNodes with the elements of the SCC. Used for quickly
148 // looking up whether a given CallGraphNode is in this SCC.
149 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
150 SCCNodes.insert((*I)->getFunction());
152 // Check if any of the functions in the SCC read or write memory. If they
153 // write memory then they can't be marked readnone or readonly.
154 bool ReadsMemory = false;
155 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
156 Function *F = (*I)->getFunction();
158 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
159 // External node or node we don't want to optimize - assume it may write
160 // memory and give up.
163 // We need to manually construct BasicAA directly in order to disable its
164 // use of other function analyses.
165 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
167 // Construct our own AA results for this function. We do this manually to
168 // work around the limitations of the legacy pass manager.
169 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
171 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
172 if (MRB == FMRB_DoesNotAccessMemory)
176 // Definitions with weak linkage may be overridden at linktime with
177 // something that writes memory, so treat them like declarations.
178 if (F->isDeclaration() || F->mayBeOverridden()) {
179 if (!AliasAnalysis::onlyReadsMemory(MRB))
180 // May write memory. Just give up.
187 // Scan the function body for instructions that may read or write memory.
188 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
189 Instruction *I = &*II;
191 // Some instructions can be ignored even if they read or write memory.
192 // Detect these now, skipping to the next instruction if one is found.
193 CallSite CS(cast<Value>(I));
195 // Ignore calls to functions in the same SCC.
196 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
198 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
199 // If the call doesn't access arbitrary memory, we may be able to
200 // figure out something.
201 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
202 // If the call does access argument pointees, check each argument.
203 if (AliasAnalysis::doesAccessArgPointees(MRB))
204 // Check whether all pointer arguments point to local memory, and
205 // ignore calls that only access local memory.
206 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
209 if (Arg->getType()->isPointerTy()) {
211 I->getAAMetadata(AAInfo);
213 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
214 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
216 // Writes non-local memory. Give up.
219 // Ok, it reads non-local memory.
226 // The call could access any memory. If that includes writes, give up.
229 // If it reads, note it.
233 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
234 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
235 if (!LI->isVolatile()) {
236 MemoryLocation Loc = MemoryLocation::get(LI);
237 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
240 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
241 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
242 if (!SI->isVolatile()) {
243 MemoryLocation Loc = MemoryLocation::get(SI);
244 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
247 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
248 // Ignore vaargs on local memory.
249 MemoryLocation Loc = MemoryLocation::get(VI);
250 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
254 // Any remaining instructions need to be taken seriously! Check if they
255 // read or write memory.
256 if (I->mayWriteToMemory())
257 // Writes memory. Just give up.
260 // If this instruction may read memory, remember that.
261 ReadsMemory |= I->mayReadFromMemory();
265 // Success! Functions in this SCC do not access memory, or only read memory.
266 // Give them the appropriate attribute.
267 bool MadeChange = false;
268 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
269 Function *F = (*I)->getFunction();
271 if (F->doesNotAccessMemory())
275 if (F->onlyReadsMemory() && ReadsMemory)
281 // Clear out any existing attributes.
283 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
285 AttributeSet::FunctionIndex,
286 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
288 // Add in the new attribute.
289 F->addAttribute(AttributeSet::FunctionIndex,
290 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
302 /// For a given pointer Argument, this retains a list of Arguments of functions
303 /// in the same SCC that the pointer data flows into. We use this to build an
304 /// SCC of the arguments.
305 struct ArgumentGraphNode {
306 Argument *Definition;
307 SmallVector<ArgumentGraphNode *, 4> Uses;
310 class ArgumentGraph {
311 // We store pointers to ArgumentGraphNode objects, so it's important that
312 // that they not move around upon insert.
313 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
315 ArgumentMapTy ArgumentMap;
317 // There is no root node for the argument graph, in fact:
318 // void f(int *x, int *y) { if (...) f(x, y); }
319 // is an example where the graph is disconnected. The SCCIterator requires a
320 // single entry point, so we maintain a fake ("synthetic") root node that
321 // uses every node. Because the graph is directed and nothing points into
322 // the root, it will not participate in any SCCs (except for its own).
323 ArgumentGraphNode SyntheticRoot;
326 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
328 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
330 iterator begin() { return SyntheticRoot.Uses.begin(); }
331 iterator end() { return SyntheticRoot.Uses.end(); }
332 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
334 ArgumentGraphNode *operator[](Argument *A) {
335 ArgumentGraphNode &Node = ArgumentMap[A];
337 SyntheticRoot.Uses.push_back(&Node);
342 /// This tracker checks whether callees are in the SCC, and if so it does not
343 /// consider that a capture, instead adding it to the "Uses" list and
344 /// continuing with the analysis.
345 struct ArgumentUsesTracker : public CaptureTracker {
346 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
347 : Captured(false), SCCNodes(SCCNodes) {}
349 void tooManyUses() override { Captured = true; }
351 bool captured(const Use *U) override {
352 CallSite CS(U->getUser());
353 if (!CS.getInstruction()) {
358 Function *F = CS.getCalledFunction();
359 if (!F || !SCCNodes.count(F)) {
365 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
366 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
367 PI != PE; ++PI, ++AI) {
369 assert(F->isVarArg() && "More params than args in non-varargs call");
379 assert(Found && "Capturing call-site captured nothing?");
384 bool Captured; // True only if certainly captured (used outside our SCC).
385 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
387 const SmallPtrSet<Function *, 8> &SCCNodes;
392 template <> struct GraphTraits<ArgumentGraphNode *> {
393 typedef ArgumentGraphNode NodeType;
394 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
396 static inline NodeType *getEntryNode(NodeType *A) { return A; }
397 static inline ChildIteratorType child_begin(NodeType *N) {
398 return N->Uses.begin();
400 static inline ChildIteratorType child_end(NodeType *N) {
401 return N->Uses.end();
405 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
406 static NodeType *getEntryNode(ArgumentGraph *AG) {
407 return AG->getEntryNode();
409 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
412 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
416 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
417 static Attribute::AttrKind
418 determinePointerReadAttrs(Argument *A,
419 const SmallPtrSet<Argument *, 8> &SCCNodes) {
421 SmallVector<Use *, 32> Worklist;
422 SmallSet<Use *, 32> Visited;
424 // inalloca arguments are always clobbered by the call.
425 if (A->hasInAllocaAttr())
426 return Attribute::None;
429 // We don't need to track IsWritten. If A is written to, return immediately.
431 for (Use &U : A->uses()) {
433 Worklist.push_back(&U);
436 while (!Worklist.empty()) {
437 Use *U = Worklist.pop_back_val();
438 Instruction *I = cast<Instruction>(U->getUser());
441 switch (I->getOpcode()) {
442 case Instruction::BitCast:
443 case Instruction::GetElementPtr:
444 case Instruction::PHI:
445 case Instruction::Select:
446 case Instruction::AddrSpaceCast:
447 // The original value is not read/written via this if the new value isn't.
448 for (Use &UU : I->uses())
449 if (Visited.insert(&UU).second)
450 Worklist.push_back(&UU);
453 case Instruction::Call:
454 case Instruction::Invoke: {
455 bool Captures = true;
457 if (I->getType()->isVoidTy())
460 auto AddUsersToWorklistIfCapturing = [&] {
462 for (Use &UU : I->uses())
463 if (Visited.insert(&UU).second)
464 Worklist.push_back(&UU);
468 if (CS.doesNotAccessMemory()) {
469 AddUsersToWorklistIfCapturing();
473 Function *F = CS.getCalledFunction();
475 if (CS.onlyReadsMemory()) {
477 AddUsersToWorklistIfCapturing();
480 return Attribute::None;
483 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
484 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
485 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
488 assert(F->isVarArg() &&
489 "More params than args in non-varargs call.");
490 return Attribute::None;
492 Captures &= !CS.doesNotCapture(A - B);
493 if (SCCNodes.count(AI))
495 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
496 return Attribute::None;
497 if (!CS.doesNotAccessMemory(A - B))
501 AddUsersToWorklistIfCapturing();
505 case Instruction::Load:
509 case Instruction::ICmp:
510 case Instruction::Ret:
514 return Attribute::None;
518 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
521 /// Deduce nocapture attributes for the SCC.
522 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
523 bool Changed = false;
525 SmallPtrSet<Function *, 8> SCCNodes;
527 // Fill SCCNodes with the elements of the SCC. Used for quickly
528 // looking up whether a given CallGraphNode is in this SCC.
529 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
530 Function *F = (*I)->getFunction();
531 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
532 !F->hasFnAttribute(Attribute::OptimizeNone))
539 B.addAttribute(Attribute::NoCapture);
541 // Check each function in turn, determining which pointer arguments are not
543 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
544 Function *F = (*I)->getFunction();
546 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
547 // External node or function we're trying not to optimize - only a problem
548 // for arguments that we pass to it.
551 // Definitions with weak linkage may be overridden at linktime with
552 // something that captures pointers, so treat them like declarations.
553 if (F->isDeclaration() || F->mayBeOverridden())
556 // Functions that are readonly (or readnone) and nounwind and don't return
557 // a value can't capture arguments. Don't analyze them.
558 if (F->onlyReadsMemory() && F->doesNotThrow() &&
559 F->getReturnType()->isVoidTy()) {
560 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
562 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
563 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
571 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
573 if (!A->getType()->isPointerTy())
575 bool HasNonLocalUses = false;
576 if (!A->hasNoCaptureAttr()) {
577 ArgumentUsesTracker Tracker(SCCNodes);
578 PointerMayBeCaptured(A, &Tracker);
579 if (!Tracker.Captured) {
580 if (Tracker.Uses.empty()) {
581 // If it's trivially not captured, mark it nocapture now.
583 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
587 // If it's not trivially captured and not trivially not captured,
588 // then it must be calling into another function in our SCC. Save
589 // its particulars for Argument-SCC analysis later.
590 ArgumentGraphNode *Node = AG[A];
591 for (SmallVectorImpl<Argument *>::iterator
592 UI = Tracker.Uses.begin(),
593 UE = Tracker.Uses.end();
595 Node->Uses.push_back(AG[*UI]);
597 HasNonLocalUses = true;
601 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
603 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
604 // Can we determine that it's readonly/readnone without doing an SCC?
605 // Note that we don't allow any calls at all here, or else our result
606 // will be dependent on the iteration order through the functions in the
608 SmallPtrSet<Argument *, 8> Self;
610 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
611 if (R != Attribute::None) {
614 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
616 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
622 // The graph we've collected is partial because we stopped scanning for
623 // argument uses once we solved the argument trivially. These partial nodes
624 // show up as ArgumentGraphNode objects with an empty Uses list, and for
625 // these nodes the final decision about whether they capture has already been
626 // made. If the definition doesn't have a 'nocapture' attribute by now, it
629 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
630 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
631 if (ArgumentSCC.size() == 1) {
632 if (!ArgumentSCC[0]->Definition)
633 continue; // synthetic root node
635 // eg. "void f(int* x) { if (...) f(x); }"
636 if (ArgumentSCC[0]->Uses.size() == 1 &&
637 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
638 Argument *A = ArgumentSCC[0]->Definition;
639 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
646 bool SCCCaptured = false;
647 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
648 I != E && !SCCCaptured; ++I) {
649 ArgumentGraphNode *Node = *I;
650 if (Node->Uses.empty()) {
651 if (!Node->Definition->hasNoCaptureAttr())
658 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
659 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
660 // quickly looking up whether a given Argument is in this ArgumentSCC.
661 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
662 ArgumentSCCNodes.insert((*I)->Definition);
665 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
666 I != E && !SCCCaptured; ++I) {
667 ArgumentGraphNode *N = *I;
668 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
671 Argument *A = (*UI)->Definition;
672 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
681 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
682 Argument *A = ArgumentSCC[i]->Definition;
683 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
688 // We also want to compute readonly/readnone. With a small number of false
689 // negatives, we can assume that any pointer which is captured isn't going
690 // to be provably readonly or readnone, since by definition we can't
691 // analyze all uses of a captured pointer.
693 // The false negatives happen when the pointer is captured by a function
694 // that promises readonly/readnone behaviour on the pointer, then the
695 // pointer's lifetime ends before anything that writes to arbitrary memory.
696 // Also, a readonly/readnone pointer may be returned, but returning a
697 // pointer is capturing it.
699 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
700 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
701 Argument *A = ArgumentSCC[i]->Definition;
702 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
703 if (K == Attribute::ReadNone)
705 if (K == Attribute::ReadOnly) {
706 ReadAttr = Attribute::ReadOnly;
713 if (ReadAttr != Attribute::None) {
715 B.addAttribute(ReadAttr);
716 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
717 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
718 Argument *A = ArgumentSCC[i]->Definition;
719 // Clear out existing readonly/readnone attributes
720 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
721 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
722 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
731 /// Tests whether a function is "malloc-like".
733 /// A function is "malloc-like" if it returns either null or a pointer that
734 /// doesn't alias any other pointer visible to the caller.
735 bool FunctionAttrs::IsFunctionMallocLike(
736 Function *F, SmallPtrSet<Function *, 8> &SCCNodes) const {
737 SmallSetVector<Value *, 8> FlowsToReturn;
738 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
739 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
740 FlowsToReturn.insert(Ret->getReturnValue());
742 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
743 Value *RetVal = FlowsToReturn[i];
745 if (Constant *C = dyn_cast<Constant>(RetVal)) {
746 if (!C->isNullValue() && !isa<UndefValue>(C))
752 if (isa<Argument>(RetVal))
755 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
756 switch (RVI->getOpcode()) {
757 // Extend the analysis by looking upwards.
758 case Instruction::BitCast:
759 case Instruction::GetElementPtr:
760 case Instruction::AddrSpaceCast:
761 FlowsToReturn.insert(RVI->getOperand(0));
763 case Instruction::Select: {
764 SelectInst *SI = cast<SelectInst>(RVI);
765 FlowsToReturn.insert(SI->getTrueValue());
766 FlowsToReturn.insert(SI->getFalseValue());
769 case Instruction::PHI: {
770 PHINode *PN = cast<PHINode>(RVI);
771 for (Value *IncValue : PN->incoming_values())
772 FlowsToReturn.insert(IncValue);
776 // Check whether the pointer came from an allocation.
777 case Instruction::Alloca:
779 case Instruction::Call:
780 case Instruction::Invoke: {
782 if (CS.paramHasAttr(0, Attribute::NoAlias))
784 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
788 return false; // Did not come from an allocation.
791 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
798 /// Deduce noalias attributes for the SCC.
799 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
800 SmallPtrSet<Function *, 8> SCCNodes;
802 // Fill SCCNodes with the elements of the SCC. Used for quickly
803 // looking up whether a given CallGraphNode is in this SCC.
804 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
805 SCCNodes.insert((*I)->getFunction());
807 // Check each function in turn, determining which functions return noalias
809 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
810 Function *F = (*I)->getFunction();
812 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
813 // External node or node we don't want to optimize - skip it;
817 if (F->doesNotAlias(0))
820 // Definitions with weak linkage may be overridden at linktime, so
821 // treat them like declarations.
822 if (F->isDeclaration() || F->mayBeOverridden())
825 // We annotate noalias return values, which are only applicable to
827 if (!F->getReturnType()->isPointerTy())
830 if (!IsFunctionMallocLike(F, SCCNodes))
834 bool MadeChange = false;
835 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
836 Function *F = (*I)->getFunction();
837 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
840 F->setDoesNotAlias(0);
848 /// Tests whether this function is known to not return null.
849 bool FunctionAttrs::ReturnsNonNull(Function *F,
850 SmallPtrSet<Function *, 8> &SCCNodes,
851 bool &Speculative) const {
852 assert(F->getReturnType()->isPointerTy() &&
853 "nonnull only meaningful on pointer types");
856 SmallSetVector<Value *, 8> FlowsToReturn;
857 for (BasicBlock &BB : *F)
858 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
859 FlowsToReturn.insert(Ret->getReturnValue());
861 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
862 Value *RetVal = FlowsToReturn[i];
864 // If this value is locally known to be non-null, we're good
865 if (isKnownNonNull(RetVal, TLI))
868 // Otherwise, we need to look upwards since we can't make any local
870 Instruction *RVI = dyn_cast<Instruction>(RetVal);
873 switch (RVI->getOpcode()) {
874 // Extend the analysis by looking upwards.
875 case Instruction::BitCast:
876 case Instruction::GetElementPtr:
877 case Instruction::AddrSpaceCast:
878 FlowsToReturn.insert(RVI->getOperand(0));
880 case Instruction::Select: {
881 SelectInst *SI = cast<SelectInst>(RVI);
882 FlowsToReturn.insert(SI->getTrueValue());
883 FlowsToReturn.insert(SI->getFalseValue());
886 case Instruction::PHI: {
887 PHINode *PN = cast<PHINode>(RVI);
888 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
889 FlowsToReturn.insert(PN->getIncomingValue(i));
892 case Instruction::Call:
893 case Instruction::Invoke: {
895 Function *Callee = CS.getCalledFunction();
896 // A call to a node within the SCC is assumed to return null until
898 if (Callee && SCCNodes.count(Callee)) {
905 return false; // Unknown source, may be null
907 llvm_unreachable("should have either continued or returned");
913 /// Deduce nonnull attributes for the SCC.
914 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
915 SmallPtrSet<Function *, 8> SCCNodes;
917 // Fill SCCNodes with the elements of the SCC. Used for quickly
918 // looking up whether a given CallGraphNode is in this SCC.
919 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
920 SCCNodes.insert((*I)->getFunction());
922 // Speculative that all functions in the SCC return only nonnull
923 // pointers. We may refute this as we analyze functions.
924 bool SCCReturnsNonNull = true;
926 bool MadeChange = false;
928 // Check each function in turn, determining which functions return nonnull
930 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
931 Function *F = (*I)->getFunction();
933 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
934 // External node or node we don't want to optimize - skip it;
938 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
942 // Definitions with weak linkage may be overridden at linktime, so
943 // treat them like declarations.
944 if (F->isDeclaration() || F->mayBeOverridden())
947 // We annotate nonnull return values, which are only applicable to
949 if (!F->getReturnType()->isPointerTy())
952 bool Speculative = false;
953 if (ReturnsNonNull(F, SCCNodes, Speculative)) {
955 // Mark the function eagerly since we may discover a function
956 // which prevents us from speculating about the entire SCC
957 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
958 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
964 // At least one function returns something which could be null, can't
965 // speculate any more.
966 SCCReturnsNonNull = false;
969 if (SCCReturnsNonNull) {
970 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
971 Function *F = (*I)->getFunction();
972 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
973 Attribute::NonNull) ||
974 !F->getReturnType()->isPointerTy())
977 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
978 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
987 /// Analyze the name and prototype of the given function and set any applicable
990 /// Returns true if any attributes were set and false otherwise.
991 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
992 if (F.hasFnAttribute(Attribute::OptimizeNone))
995 FunctionType *FTy = F.getFunctionType();
996 LibFunc::Func TheLibFunc;
997 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
1000 switch (TheLibFunc) {
1001 case LibFunc::strlen:
1002 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1004 setOnlyReadsMemory(F);
1006 setDoesNotCapture(F, 1);
1008 case LibFunc::strchr:
1009 case LibFunc::strrchr:
1010 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1011 !FTy->getParamType(1)->isIntegerTy())
1013 setOnlyReadsMemory(F);
1016 case LibFunc::strtol:
1017 case LibFunc::strtod:
1018 case LibFunc::strtof:
1019 case LibFunc::strtoul:
1020 case LibFunc::strtoll:
1021 case LibFunc::strtold:
1022 case LibFunc::strtoull:
1023 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1026 setDoesNotCapture(F, 2);
1027 setOnlyReadsMemory(F, 1);
1029 case LibFunc::strcpy:
1030 case LibFunc::stpcpy:
1031 case LibFunc::strcat:
1032 case LibFunc::strncat:
1033 case LibFunc::strncpy:
1034 case LibFunc::stpncpy:
1035 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1038 setDoesNotCapture(F, 2);
1039 setOnlyReadsMemory(F, 2);
1041 case LibFunc::strxfrm:
1042 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1043 !FTy->getParamType(1)->isPointerTy())
1046 setDoesNotCapture(F, 1);
1047 setDoesNotCapture(F, 2);
1048 setOnlyReadsMemory(F, 2);
1050 case LibFunc::strcmp: // 0,1
1051 case LibFunc::strspn: // 0,1
1052 case LibFunc::strncmp: // 0,1
1053 case LibFunc::strcspn: // 0,1
1054 case LibFunc::strcoll: // 0,1
1055 case LibFunc::strcasecmp: // 0,1
1056 case LibFunc::strncasecmp: //
1057 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1058 !FTy->getParamType(1)->isPointerTy())
1060 setOnlyReadsMemory(F);
1062 setDoesNotCapture(F, 1);
1063 setDoesNotCapture(F, 2);
1065 case LibFunc::strstr:
1066 case LibFunc::strpbrk:
1067 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1069 setOnlyReadsMemory(F);
1071 setDoesNotCapture(F, 2);
1073 case LibFunc::strtok:
1074 case LibFunc::strtok_r:
1075 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1078 setDoesNotCapture(F, 2);
1079 setOnlyReadsMemory(F, 2);
1081 case LibFunc::scanf:
1082 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1085 setDoesNotCapture(F, 1);
1086 setOnlyReadsMemory(F, 1);
1088 case LibFunc::setbuf:
1089 case LibFunc::setvbuf:
1090 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1093 setDoesNotCapture(F, 1);
1095 case LibFunc::strdup:
1096 case LibFunc::strndup:
1097 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1098 !FTy->getParamType(0)->isPointerTy())
1101 setDoesNotAlias(F, 0);
1102 setDoesNotCapture(F, 1);
1103 setOnlyReadsMemory(F, 1);
1106 case LibFunc::statvfs:
1107 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1108 !FTy->getParamType(1)->isPointerTy())
1111 setDoesNotCapture(F, 1);
1112 setDoesNotCapture(F, 2);
1113 setOnlyReadsMemory(F, 1);
1115 case LibFunc::sscanf:
1116 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1117 !FTy->getParamType(1)->isPointerTy())
1120 setDoesNotCapture(F, 1);
1121 setDoesNotCapture(F, 2);
1122 setOnlyReadsMemory(F, 1);
1123 setOnlyReadsMemory(F, 2);
1125 case LibFunc::sprintf:
1126 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1127 !FTy->getParamType(1)->isPointerTy())
1130 setDoesNotCapture(F, 1);
1131 setDoesNotCapture(F, 2);
1132 setOnlyReadsMemory(F, 2);
1134 case LibFunc::snprintf:
1135 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1136 !FTy->getParamType(2)->isPointerTy())
1139 setDoesNotCapture(F, 1);
1140 setDoesNotCapture(F, 3);
1141 setOnlyReadsMemory(F, 3);
1143 case LibFunc::setitimer:
1144 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1145 !FTy->getParamType(2)->isPointerTy())
1148 setDoesNotCapture(F, 2);
1149 setDoesNotCapture(F, 3);
1150 setOnlyReadsMemory(F, 2);
1152 case LibFunc::system:
1153 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1155 // May throw; "system" is a valid pthread cancellation point.
1156 setDoesNotCapture(F, 1);
1157 setOnlyReadsMemory(F, 1);
1159 case LibFunc::malloc:
1160 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1163 setDoesNotAlias(F, 0);
1165 case LibFunc::memcmp:
1166 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1167 !FTy->getParamType(1)->isPointerTy())
1169 setOnlyReadsMemory(F);
1171 setDoesNotCapture(F, 1);
1172 setDoesNotCapture(F, 2);
1174 case LibFunc::memchr:
1175 case LibFunc::memrchr:
1176 if (FTy->getNumParams() != 3)
1178 setOnlyReadsMemory(F);
1182 case LibFunc::modff:
1183 case LibFunc::modfl:
1184 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1187 setDoesNotCapture(F, 2);
1189 case LibFunc::memcpy:
1190 case LibFunc::memccpy:
1191 case LibFunc::memmove:
1192 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1195 setDoesNotCapture(F, 2);
1196 setOnlyReadsMemory(F, 2);
1198 case LibFunc::memalign:
1199 if (!FTy->getReturnType()->isPointerTy())
1201 setDoesNotAlias(F, 0);
1203 case LibFunc::mkdir:
1204 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1207 setDoesNotCapture(F, 1);
1208 setOnlyReadsMemory(F, 1);
1210 case LibFunc::mktime:
1211 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1214 setDoesNotCapture(F, 1);
1216 case LibFunc::realloc:
1217 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1218 !FTy->getReturnType()->isPointerTy())
1221 setDoesNotAlias(F, 0);
1222 setDoesNotCapture(F, 1);
1225 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1227 // May throw; "read" is a valid pthread cancellation point.
1228 setDoesNotCapture(F, 2);
1230 case LibFunc::rewind:
1231 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1234 setDoesNotCapture(F, 1);
1236 case LibFunc::rmdir:
1237 case LibFunc::remove:
1238 case LibFunc::realpath:
1239 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1242 setDoesNotCapture(F, 1);
1243 setOnlyReadsMemory(F, 1);
1245 case LibFunc::rename:
1246 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1247 !FTy->getParamType(1)->isPointerTy())
1250 setDoesNotCapture(F, 1);
1251 setDoesNotCapture(F, 2);
1252 setOnlyReadsMemory(F, 1);
1253 setOnlyReadsMemory(F, 2);
1255 case LibFunc::readlink:
1256 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1257 !FTy->getParamType(1)->isPointerTy())
1260 setDoesNotCapture(F, 1);
1261 setDoesNotCapture(F, 2);
1262 setOnlyReadsMemory(F, 1);
1264 case LibFunc::write:
1265 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1267 // May throw; "write" is a valid pthread cancellation point.
1268 setDoesNotCapture(F, 2);
1269 setOnlyReadsMemory(F, 2);
1271 case LibFunc::bcopy:
1272 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1273 !FTy->getParamType(1)->isPointerTy())
1276 setDoesNotCapture(F, 1);
1277 setDoesNotCapture(F, 2);
1278 setOnlyReadsMemory(F, 1);
1281 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1282 !FTy->getParamType(1)->isPointerTy())
1285 setOnlyReadsMemory(F);
1286 setDoesNotCapture(F, 1);
1287 setDoesNotCapture(F, 2);
1289 case LibFunc::bzero:
1290 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1293 setDoesNotCapture(F, 1);
1295 case LibFunc::calloc:
1296 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1299 setDoesNotAlias(F, 0);
1301 case LibFunc::chmod:
1302 case LibFunc::chown:
1303 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1306 setDoesNotCapture(F, 1);
1307 setOnlyReadsMemory(F, 1);
1309 case LibFunc::ctermid:
1310 case LibFunc::clearerr:
1311 case LibFunc::closedir:
1312 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1315 setDoesNotCapture(F, 1);
1320 case LibFunc::atoll:
1321 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1324 setOnlyReadsMemory(F);
1325 setDoesNotCapture(F, 1);
1327 case LibFunc::access:
1328 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1331 setDoesNotCapture(F, 1);
1332 setOnlyReadsMemory(F, 1);
1334 case LibFunc::fopen:
1335 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1336 !FTy->getParamType(0)->isPointerTy() ||
1337 !FTy->getParamType(1)->isPointerTy())
1340 setDoesNotAlias(F, 0);
1341 setDoesNotCapture(F, 1);
1342 setDoesNotCapture(F, 2);
1343 setOnlyReadsMemory(F, 1);
1344 setOnlyReadsMemory(F, 2);
1346 case LibFunc::fdopen:
1347 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1348 !FTy->getParamType(1)->isPointerTy())
1351 setDoesNotAlias(F, 0);
1352 setDoesNotCapture(F, 2);
1353 setOnlyReadsMemory(F, 2);
1357 case LibFunc::fseek:
1358 case LibFunc::ftell:
1359 case LibFunc::fgetc:
1360 case LibFunc::fseeko:
1361 case LibFunc::ftello:
1362 case LibFunc::fileno:
1363 case LibFunc::fflush:
1364 case LibFunc::fclose:
1365 case LibFunc::fsetpos:
1366 case LibFunc::flockfile:
1367 case LibFunc::funlockfile:
1368 case LibFunc::ftrylockfile:
1369 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1372 setDoesNotCapture(F, 1);
1374 case LibFunc::ferror:
1375 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1378 setDoesNotCapture(F, 1);
1379 setOnlyReadsMemory(F);
1381 case LibFunc::fputc:
1382 case LibFunc::fstat:
1383 case LibFunc::frexp:
1384 case LibFunc::frexpf:
1385 case LibFunc::frexpl:
1386 case LibFunc::fstatvfs:
1387 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1390 setDoesNotCapture(F, 2);
1392 case LibFunc::fgets:
1393 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1394 !FTy->getParamType(2)->isPointerTy())
1397 setDoesNotCapture(F, 3);
1399 case LibFunc::fread:
1400 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1401 !FTy->getParamType(3)->isPointerTy())
1404 setDoesNotCapture(F, 1);
1405 setDoesNotCapture(F, 4);
1407 case LibFunc::fwrite:
1408 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1409 !FTy->getParamType(3)->isPointerTy())
1412 setDoesNotCapture(F, 1);
1413 setDoesNotCapture(F, 4);
1415 case LibFunc::fputs:
1416 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1417 !FTy->getParamType(1)->isPointerTy())
1420 setDoesNotCapture(F, 1);
1421 setDoesNotCapture(F, 2);
1422 setOnlyReadsMemory(F, 1);
1424 case LibFunc::fscanf:
1425 case LibFunc::fprintf:
1426 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1427 !FTy->getParamType(1)->isPointerTy())
1430 setDoesNotCapture(F, 1);
1431 setDoesNotCapture(F, 2);
1432 setOnlyReadsMemory(F, 2);
1434 case LibFunc::fgetpos:
1435 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1436 !FTy->getParamType(1)->isPointerTy())
1439 setDoesNotCapture(F, 1);
1440 setDoesNotCapture(F, 2);
1443 case LibFunc::getlogin_r:
1444 case LibFunc::getc_unlocked:
1445 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1448 setDoesNotCapture(F, 1);
1450 case LibFunc::getenv:
1451 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1454 setOnlyReadsMemory(F);
1455 setDoesNotCapture(F, 1);
1458 case LibFunc::getchar:
1461 case LibFunc::getitimer:
1462 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1465 setDoesNotCapture(F, 2);
1467 case LibFunc::getpwnam:
1468 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1471 setDoesNotCapture(F, 1);
1472 setOnlyReadsMemory(F, 1);
1474 case LibFunc::ungetc:
1475 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1478 setDoesNotCapture(F, 2);
1480 case LibFunc::uname:
1481 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1484 setDoesNotCapture(F, 1);
1486 case LibFunc::unlink:
1487 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1490 setDoesNotCapture(F, 1);
1491 setOnlyReadsMemory(F, 1);
1493 case LibFunc::unsetenv:
1494 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1497 setDoesNotCapture(F, 1);
1498 setOnlyReadsMemory(F, 1);
1500 case LibFunc::utime:
1501 case LibFunc::utimes:
1502 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1503 !FTy->getParamType(1)->isPointerTy())
1506 setDoesNotCapture(F, 1);
1507 setDoesNotCapture(F, 2);
1508 setOnlyReadsMemory(F, 1);
1509 setOnlyReadsMemory(F, 2);
1512 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1515 setDoesNotCapture(F, 2);
1518 case LibFunc::printf:
1519 case LibFunc::perror:
1520 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1523 setDoesNotCapture(F, 1);
1524 setOnlyReadsMemory(F, 1);
1526 case LibFunc::pread:
1527 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1529 // May throw; "pread" is a valid pthread cancellation point.
1530 setDoesNotCapture(F, 2);
1532 case LibFunc::pwrite:
1533 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1535 // May throw; "pwrite" is a valid pthread cancellation point.
1536 setDoesNotCapture(F, 2);
1537 setOnlyReadsMemory(F, 2);
1539 case LibFunc::putchar:
1542 case LibFunc::popen:
1543 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1544 !FTy->getParamType(0)->isPointerTy() ||
1545 !FTy->getParamType(1)->isPointerTy())
1548 setDoesNotAlias(F, 0);
1549 setDoesNotCapture(F, 1);
1550 setDoesNotCapture(F, 2);
1551 setOnlyReadsMemory(F, 1);
1552 setOnlyReadsMemory(F, 2);
1554 case LibFunc::pclose:
1555 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1558 setDoesNotCapture(F, 1);
1560 case LibFunc::vscanf:
1561 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1564 setDoesNotCapture(F, 1);
1565 setOnlyReadsMemory(F, 1);
1567 case LibFunc::vsscanf:
1568 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1569 !FTy->getParamType(2)->isPointerTy())
1572 setDoesNotCapture(F, 1);
1573 setDoesNotCapture(F, 2);
1574 setOnlyReadsMemory(F, 1);
1575 setOnlyReadsMemory(F, 2);
1577 case LibFunc::vfscanf:
1578 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1579 !FTy->getParamType(2)->isPointerTy())
1582 setDoesNotCapture(F, 1);
1583 setDoesNotCapture(F, 2);
1584 setOnlyReadsMemory(F, 2);
1586 case LibFunc::valloc:
1587 if (!FTy->getReturnType()->isPointerTy())
1590 setDoesNotAlias(F, 0);
1592 case LibFunc::vprintf:
1593 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1596 setDoesNotCapture(F, 1);
1597 setOnlyReadsMemory(F, 1);
1599 case LibFunc::vfprintf:
1600 case LibFunc::vsprintf:
1601 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1602 !FTy->getParamType(1)->isPointerTy())
1605 setDoesNotCapture(F, 1);
1606 setDoesNotCapture(F, 2);
1607 setOnlyReadsMemory(F, 2);
1609 case LibFunc::vsnprintf:
1610 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1611 !FTy->getParamType(2)->isPointerTy())
1614 setDoesNotCapture(F, 1);
1615 setDoesNotCapture(F, 3);
1616 setOnlyReadsMemory(F, 3);
1619 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1621 // May throw; "open" is a valid pthread cancellation point.
1622 setDoesNotCapture(F, 1);
1623 setOnlyReadsMemory(F, 1);
1625 case LibFunc::opendir:
1626 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1627 !FTy->getParamType(0)->isPointerTy())
1630 setDoesNotAlias(F, 0);
1631 setDoesNotCapture(F, 1);
1632 setOnlyReadsMemory(F, 1);
1634 case LibFunc::tmpfile:
1635 if (!FTy->getReturnType()->isPointerTy())
1638 setDoesNotAlias(F, 0);
1640 case LibFunc::times:
1641 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1644 setDoesNotCapture(F, 1);
1646 case LibFunc::htonl:
1647 case LibFunc::htons:
1648 case LibFunc::ntohl:
1649 case LibFunc::ntohs:
1651 setDoesNotAccessMemory(F);
1653 case LibFunc::lstat:
1654 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1655 !FTy->getParamType(1)->isPointerTy())
1658 setDoesNotCapture(F, 1);
1659 setDoesNotCapture(F, 2);
1660 setOnlyReadsMemory(F, 1);
1662 case LibFunc::lchown:
1663 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1666 setDoesNotCapture(F, 1);
1667 setOnlyReadsMemory(F, 1);
1669 case LibFunc::qsort:
1670 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1672 // May throw; places call through function pointer.
1673 setDoesNotCapture(F, 4);
1675 case LibFunc::dunder_strdup:
1676 case LibFunc::dunder_strndup:
1677 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1678 !FTy->getParamType(0)->isPointerTy())
1681 setDoesNotAlias(F, 0);
1682 setDoesNotCapture(F, 1);
1683 setOnlyReadsMemory(F, 1);
1685 case LibFunc::dunder_strtok_r:
1686 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1689 setDoesNotCapture(F, 2);
1690 setOnlyReadsMemory(F, 2);
1692 case LibFunc::under_IO_getc:
1693 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1696 setDoesNotCapture(F, 1);
1698 case LibFunc::under_IO_putc:
1699 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1702 setDoesNotCapture(F, 2);
1704 case LibFunc::dunder_isoc99_scanf:
1705 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1708 setDoesNotCapture(F, 1);
1709 setOnlyReadsMemory(F, 1);
1711 case LibFunc::stat64:
1712 case LibFunc::lstat64:
1713 case LibFunc::statvfs64:
1714 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1715 !FTy->getParamType(1)->isPointerTy())
1718 setDoesNotCapture(F, 1);
1719 setDoesNotCapture(F, 2);
1720 setOnlyReadsMemory(F, 1);
1722 case LibFunc::dunder_isoc99_sscanf:
1723 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1724 !FTy->getParamType(1)->isPointerTy())
1727 setDoesNotCapture(F, 1);
1728 setDoesNotCapture(F, 2);
1729 setOnlyReadsMemory(F, 1);
1730 setOnlyReadsMemory(F, 2);
1732 case LibFunc::fopen64:
1733 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1734 !FTy->getParamType(0)->isPointerTy() ||
1735 !FTy->getParamType(1)->isPointerTy())
1738 setDoesNotAlias(F, 0);
1739 setDoesNotCapture(F, 1);
1740 setDoesNotCapture(F, 2);
1741 setOnlyReadsMemory(F, 1);
1742 setOnlyReadsMemory(F, 2);
1744 case LibFunc::fseeko64:
1745 case LibFunc::ftello64:
1746 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1749 setDoesNotCapture(F, 1);
1751 case LibFunc::tmpfile64:
1752 if (!FTy->getReturnType()->isPointerTy())
1755 setDoesNotAlias(F, 0);
1757 case LibFunc::fstat64:
1758 case LibFunc::fstatvfs64:
1759 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1762 setDoesNotCapture(F, 2);
1764 case LibFunc::open64:
1765 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1767 // May throw; "open" is a valid pthread cancellation point.
1768 setDoesNotCapture(F, 1);
1769 setOnlyReadsMemory(F, 1);
1771 case LibFunc::gettimeofday:
1772 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1773 !FTy->getParamType(1)->isPointerTy())
1775 // Currently some platforms have the restrict keyword on the arguments to
1776 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1779 setDoesNotCapture(F, 1);
1780 setDoesNotCapture(F, 2);
1783 // Didn't mark any attributes.
1790 /// Adds attributes to well-known standard library call declarations.
1791 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1792 bool MadeChange = false;
1794 // Check each function in turn annotating well-known library function
1795 // declarations with attributes.
1796 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1797 Function *F = (*I)->getFunction();
1799 if (F && F->isDeclaration())
1800 MadeChange |= inferPrototypeAttributes(*F);
1806 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1807 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1809 bool Changed = annotateLibraryCalls(SCC);
1810 Changed |= AddReadAttrs(SCC);
1811 Changed |= AddArgumentAttrs(SCC);
1812 Changed |= AddNoAliasAttrs(SCC);
1813 Changed |= AddNonNullAttrs(SCC);