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/CallGraph.h"
28 #include "llvm/Analysis/CallGraphSCCPass.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
40 #define DEBUG_TYPE "functionattrs"
42 STATISTIC(NumReadNone, "Number of functions marked readnone");
43 STATISTIC(NumReadOnly, "Number of functions marked readonly");
44 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
45 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
46 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
47 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
48 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
49 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
52 struct FunctionAttrs : public CallGraphSCCPass {
53 static char ID; // Pass identification, replacement for typeid
54 FunctionAttrs() : CallGraphSCCPass(ID), AA(nullptr) {
55 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
58 // runOnSCC - Analyze the SCC, performing the transformation if possible.
59 bool runOnSCC(CallGraphSCC &SCC) override;
61 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
62 bool AddReadAttrs(const CallGraphSCC &SCC);
64 // AddArgumentAttrs - Deduce nocapture attributes for the SCC.
65 bool AddArgumentAttrs(const CallGraphSCC &SCC);
67 // IsFunctionMallocLike - Does this function allocate new memory?
68 bool IsFunctionMallocLike(Function *F,
69 SmallPtrSet<Function*, 8> &) const;
71 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
72 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
74 /// \brief Does this function return null?
75 bool ReturnsNonNull(Function *F, SmallPtrSet<Function*, 8> &,
76 bool &Speculative) const;
78 /// \brief Deduce nonnull attributes for the SCC.
79 bool AddNonNullAttrs(const CallGraphSCC &SCC);
81 // Utility methods used by inferPrototypeAttributes to add attributes
82 // and maintain annotation statistics.
84 void setDoesNotAccessMemory(Function &F) {
85 if (!F.doesNotAccessMemory()) {
86 F.setDoesNotAccessMemory();
91 void setOnlyReadsMemory(Function &F) {
92 if (!F.onlyReadsMemory()) {
93 F.setOnlyReadsMemory();
98 void setDoesNotThrow(Function &F) {
99 if (!F.doesNotThrow()) {
105 void setDoesNotCapture(Function &F, unsigned n) {
106 if (!F.doesNotCapture(n)) {
107 F.setDoesNotCapture(n);
112 void setOnlyReadsMemory(Function &F, unsigned n) {
113 if (!F.onlyReadsMemory(n)) {
114 F.setOnlyReadsMemory(n);
119 void setDoesNotAlias(Function &F, unsigned n) {
120 if (!F.doesNotAlias(n)) {
121 F.setDoesNotAlias(n);
126 // inferPrototypeAttributes - Analyze the name and prototype of the
127 // given function and set any applicable attributes. Returns true
128 // if any attributes were set and false otherwise.
129 bool inferPrototypeAttributes(Function &F);
131 // annotateLibraryCalls - Adds attributes to well-known standard library
132 // call declarations.
133 bool annotateLibraryCalls(const CallGraphSCC &SCC);
135 void getAnalysisUsage(AnalysisUsage &AU) const override {
136 AU.setPreservesCFG();
137 AU.addRequired<AliasAnalysis>();
138 AU.addRequired<TargetLibraryInfoWrapperPass>();
139 CallGraphSCCPass::getAnalysisUsage(AU);
144 TargetLibraryInfo *TLI;
148 char FunctionAttrs::ID = 0;
149 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
150 "Deduce function attributes", false, false)
151 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
152 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
153 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
154 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
155 "Deduce function attributes", false, false)
157 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
160 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
161 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
162 SmallPtrSet<Function*, 8> SCCNodes;
164 // Fill SCCNodes with the elements of the SCC. Used for quickly
165 // looking up whether a given CallGraphNode is in this SCC.
166 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
167 SCCNodes.insert((*I)->getFunction());
169 // Check if any of the functions in the SCC read or write memory. If they
170 // write memory then they can't be marked readnone or readonly.
171 bool ReadsMemory = false;
172 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
173 Function *F = (*I)->getFunction();
175 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
176 // External node or node we don't want to optimize - assume it may write
177 // memory and give up.
180 FunctionModRefBehavior MRB = AA->getModRefBehavior(F);
181 if (MRB == FMRB_DoesNotAccessMemory)
185 // Definitions with weak linkage may be overridden at linktime with
186 // something that writes memory, so treat them like declarations.
187 if (F->isDeclaration() || F->mayBeOverridden()) {
188 if (!AliasAnalysis::onlyReadsMemory(MRB))
189 // May write memory. Just give up.
196 // Scan the function body for instructions that may read or write memory.
197 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
198 Instruction *I = &*II;
200 // Some instructions can be ignored even if they read or write memory.
201 // Detect these now, skipping to the next instruction if one is found.
202 CallSite CS(cast<Value>(I));
204 // Ignore calls to functions in the same SCC.
205 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
207 FunctionModRefBehavior MRB = AA->getModRefBehavior(CS);
208 // If the call doesn't access arbitrary memory, we may be able to
209 // figure out something.
210 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
211 // If the call does access argument pointees, check each argument.
212 if (AliasAnalysis::doesAccessArgPointees(MRB))
213 // Check whether all pointer arguments point to local memory, and
214 // ignore calls that only access local memory.
215 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
218 if (Arg->getType()->isPointerTy()) {
220 I->getAAMetadata(AAInfo);
222 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
223 if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
225 // Writes non-local memory. Give up.
228 // Ok, it reads non-local memory.
235 // The call could access any memory. If that includes writes, give up.
238 // If it reads, note it.
242 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
243 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
244 if (!LI->isVolatile()) {
245 MemoryLocation Loc = MemoryLocation::get(LI);
246 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
249 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
250 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
251 if (!SI->isVolatile()) {
252 MemoryLocation Loc = MemoryLocation::get(SI);
253 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
256 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
257 // Ignore vaargs on local memory.
258 MemoryLocation Loc = MemoryLocation::get(VI);
259 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
263 // Any remaining instructions need to be taken seriously! Check if they
264 // read or write memory.
265 if (I->mayWriteToMemory())
266 // Writes memory. Just give up.
269 // If this instruction may read memory, remember that.
270 ReadsMemory |= I->mayReadFromMemory();
274 // Success! Functions in this SCC do not access memory, or only read memory.
275 // Give them the appropriate attribute.
276 bool MadeChange = false;
277 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
278 Function *F = (*I)->getFunction();
280 if (F->doesNotAccessMemory())
284 if (F->onlyReadsMemory() && ReadsMemory)
290 // Clear out any existing attributes.
292 B.addAttribute(Attribute::ReadOnly)
293 .addAttribute(Attribute::ReadNone);
294 F->removeAttributes(AttributeSet::FunctionIndex,
295 AttributeSet::get(F->getContext(),
296 AttributeSet::FunctionIndex, B));
298 // Add in the new attribute.
299 F->addAttribute(AttributeSet::FunctionIndex,
300 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
312 // For a given pointer Argument, this retains a list of Arguments of functions
313 // in the same SCC that the pointer data flows into. We use this to build an
314 // SCC of the arguments.
315 struct ArgumentGraphNode {
316 Argument *Definition;
317 SmallVector<ArgumentGraphNode*, 4> Uses;
320 class ArgumentGraph {
321 // We store pointers to ArgumentGraphNode objects, so it's important that
322 // that they not move around upon insert.
323 typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
325 ArgumentMapTy ArgumentMap;
327 // There is no root node for the argument graph, in fact:
328 // void f(int *x, int *y) { if (...) f(x, y); }
329 // is an example where the graph is disconnected. The SCCIterator requires a
330 // single entry point, so we maintain a fake ("synthetic") root node that
331 // uses every node. Because the graph is directed and nothing points into
332 // the root, it will not participate in any SCCs (except for its own).
333 ArgumentGraphNode SyntheticRoot;
336 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
338 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
340 iterator begin() { return SyntheticRoot.Uses.begin(); }
341 iterator end() { return SyntheticRoot.Uses.end(); }
342 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
344 ArgumentGraphNode *operator[](Argument *A) {
345 ArgumentGraphNode &Node = ArgumentMap[A];
347 SyntheticRoot.Uses.push_back(&Node);
352 // This tracker checks whether callees are in the SCC, and if so it does not
353 // consider that a capture, instead adding it to the "Uses" list and
354 // continuing with the analysis.
355 struct ArgumentUsesTracker : public CaptureTracker {
356 ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
357 : Captured(false), SCCNodes(SCCNodes) {}
359 void tooManyUses() override { Captured = true; }
361 bool captured(const Use *U) override {
362 CallSite CS(U->getUser());
363 if (!CS.getInstruction()) { Captured = true; return true; }
365 Function *F = CS.getCalledFunction();
366 if (!F || !SCCNodes.count(F)) { Captured = true; return true; }
369 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
370 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
371 PI != PE; ++PI, ++AI) {
373 assert(F->isVarArg() && "More params than args in non-varargs call");
383 assert(Found && "Capturing call-site captured nothing?");
388 bool Captured; // True only if certainly captured (used outside our SCC).
389 SmallVector<Argument*, 4> Uses; // Uses within our SCC.
391 const SmallPtrSet<Function*, 8> &SCCNodes;
396 template<> struct GraphTraits<ArgumentGraphNode*> {
397 typedef ArgumentGraphNode NodeType;
398 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorType;
400 static inline NodeType *getEntryNode(NodeType *A) { return A; }
401 static inline ChildIteratorType child_begin(NodeType *N) {
402 return N->Uses.begin();
404 static inline ChildIteratorType child_end(NodeType *N) {
405 return N->Uses.end();
408 template<> struct GraphTraits<ArgumentGraph*>
409 : public GraphTraits<ArgumentGraphNode*> {
410 static NodeType *getEntryNode(ArgumentGraph *AG) {
411 return AG->getEntryNode();
413 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
416 static ChildIteratorType nodes_end(ArgumentGraph *AG) {
422 // Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
423 static Attribute::AttrKind
424 determinePointerReadAttrs(Argument *A,
425 const SmallPtrSet<Argument*, 8> &SCCNodes) {
427 SmallVector<Use*, 32> Worklist;
428 SmallSet<Use*, 32> Visited;
430 // inalloca arguments are always clobbered by the call.
431 if (A->hasInAllocaAttr())
432 return Attribute::None;
435 // We don't need to track IsWritten. If A is written to, return immediately.
437 for (Use &U : A->uses()) {
439 Worklist.push_back(&U);
442 while (!Worklist.empty()) {
443 Use *U = Worklist.pop_back_val();
444 Instruction *I = cast<Instruction>(U->getUser());
447 switch (I->getOpcode()) {
448 case Instruction::BitCast:
449 case Instruction::GetElementPtr:
450 case Instruction::PHI:
451 case Instruction::Select:
452 case Instruction::AddrSpaceCast:
453 // The original value is not read/written via this if the new value isn't.
454 for (Use &UU : I->uses())
455 if (Visited.insert(&UU).second)
456 Worklist.push_back(&UU);
459 case Instruction::Call:
460 case Instruction::Invoke: {
461 bool Captures = true;
463 if (I->getType()->isVoidTy())
466 auto AddUsersToWorklistIfCapturing = [&] {
468 for (Use &UU : I->uses())
469 if (Visited.insert(&UU).second)
470 Worklist.push_back(&UU);
474 if (CS.doesNotAccessMemory()) {
475 AddUsersToWorklistIfCapturing();
479 Function *F = CS.getCalledFunction();
481 if (CS.onlyReadsMemory()) {
483 AddUsersToWorklistIfCapturing();
486 return Attribute::None;
489 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
490 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
491 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
494 assert(F->isVarArg() &&
495 "More params than args in non-varargs call.");
496 return Attribute::None;
498 Captures &= !CS.doesNotCapture(A - B);
499 if (SCCNodes.count(AI))
501 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
502 return Attribute::None;
503 if (!CS.doesNotAccessMemory(A - B))
507 AddUsersToWorklistIfCapturing();
511 case Instruction::Load:
515 case Instruction::ICmp:
516 case Instruction::Ret:
520 return Attribute::None;
524 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
527 /// AddArgumentAttrs - Deduce nocapture attributes for the SCC.
528 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
529 bool Changed = false;
531 SmallPtrSet<Function*, 8> SCCNodes;
533 // Fill SCCNodes with the elements of the SCC. Used for quickly
534 // looking up whether a given CallGraphNode is in this SCC.
535 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
536 Function *F = (*I)->getFunction();
537 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
538 !F->hasFnAttribute(Attribute::OptimizeNone))
545 B.addAttribute(Attribute::NoCapture);
547 // Check each function in turn, determining which pointer arguments are not
549 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
550 Function *F = (*I)->getFunction();
552 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
553 // External node or function we're trying not to optimize - only a problem
554 // for arguments that we pass to it.
557 // Definitions with weak linkage may be overridden at linktime with
558 // something that captures pointers, so treat them like declarations.
559 if (F->isDeclaration() || F->mayBeOverridden())
562 // Functions that are readonly (or readnone) and nounwind and don't return
563 // a value can't capture arguments. Don't analyze them.
564 if (F->onlyReadsMemory() && F->doesNotThrow() &&
565 F->getReturnType()->isVoidTy()) {
566 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
568 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
569 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
577 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
579 if (!A->getType()->isPointerTy()) continue;
580 bool HasNonLocalUses = false;
581 if (!A->hasNoCaptureAttr()) {
582 ArgumentUsesTracker Tracker(SCCNodes);
583 PointerMayBeCaptured(A, &Tracker);
584 if (!Tracker.Captured) {
585 if (Tracker.Uses.empty()) {
586 // If it's trivially not captured, mark it nocapture now.
587 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo()+1, B));
591 // If it's not trivially captured and not trivially not captured,
592 // then it must be calling into another function in our SCC. Save
593 // its particulars for Argument-SCC analysis later.
594 ArgumentGraphNode *Node = AG[A];
595 for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
596 UE = Tracker.Uses.end(); UI != UE; ++UI) {
597 Node->Uses.push_back(AG[*UI]);
599 HasNonLocalUses = true;
603 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
605 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
606 // Can we determine that it's readonly/readnone without doing an SCC?
607 // Note that we don't allow any calls at all here, or else our result
608 // will be dependent on the iteration order through the functions in the
610 SmallPtrSet<Argument*, 8> Self;
612 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
613 if (R != Attribute::None) {
616 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
618 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
624 // The graph we've collected is partial because we stopped scanning for
625 // argument uses once we solved the argument trivially. These partial nodes
626 // show up as ArgumentGraphNode objects with an empty Uses list, and for
627 // these nodes the final decision about whether they capture has already been
628 // made. If the definition doesn't have a 'nocapture' attribute by now, it
631 for (scc_iterator<ArgumentGraph*> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
632 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
633 if (ArgumentSCC.size() == 1) {
634 if (!ArgumentSCC[0]->Definition) continue; // synthetic root node
636 // eg. "void f(int* x) { if (...) f(x); }"
637 if (ArgumentSCC[0]->Uses.size() == 1 &&
638 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
639 Argument *A = ArgumentSCC[0]->Definition;
640 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
647 bool SCCCaptured = false;
648 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
649 I != E && !SCCCaptured; ++I) {
650 ArgumentGraphNode *Node = *I;
651 if (Node->Uses.empty()) {
652 if (!Node->Definition->hasNoCaptureAttr())
656 if (SCCCaptured) continue;
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(),
669 UE = N->Uses.end(); UI != UE; ++UI) {
670 Argument *A = (*UI)->Definition;
671 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
677 if (SCCCaptured) continue;
679 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
680 Argument *A = ArgumentSCC[i]->Definition;
681 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
686 // We also want to compute readonly/readnone. With a small number of false
687 // negatives, we can assume that any pointer which is captured isn't going
688 // to be provably readonly or readnone, since by definition we can't
689 // analyze all uses of a captured pointer.
691 // The false negatives happen when the pointer is captured by a function
692 // that promises readonly/readnone behaviour on the pointer, then the
693 // pointer's lifetime ends before anything that writes to arbitrary memory.
694 // Also, a readonly/readnone pointer may be returned, but returning a
695 // pointer is capturing it.
697 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
698 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
699 Argument *A = ArgumentSCC[i]->Definition;
700 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
701 if (K == Attribute::ReadNone)
703 if (K == Attribute::ReadOnly) {
704 ReadAttr = Attribute::ReadOnly;
711 if (ReadAttr != Attribute::None) {
713 B.addAttribute(ReadAttr);
714 R.addAttribute(Attribute::ReadOnly)
715 .addAttribute(Attribute::ReadNone);
716 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
717 Argument *A = ArgumentSCC[i]->Definition;
718 // Clear out existing readonly/readnone attributes
719 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
720 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
721 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
730 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
731 /// or a pointer that doesn't alias any other pointer visible to the caller.
732 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
733 SmallPtrSet<Function*, 8> &SCCNodes) const {
734 SmallSetVector<Value *, 8> FlowsToReturn;
735 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
736 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
737 FlowsToReturn.insert(Ret->getReturnValue());
739 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
740 Value *RetVal = FlowsToReturn[i];
742 if (Constant *C = dyn_cast<Constant>(RetVal)) {
743 if (!C->isNullValue() && !isa<UndefValue>(C))
749 if (isa<Argument>(RetVal))
752 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
753 switch (RVI->getOpcode()) {
754 // Extend the analysis by looking upwards.
755 case Instruction::BitCast:
756 case Instruction::GetElementPtr:
757 case Instruction::AddrSpaceCast:
758 FlowsToReturn.insert(RVI->getOperand(0));
760 case Instruction::Select: {
761 SelectInst *SI = cast<SelectInst>(RVI);
762 FlowsToReturn.insert(SI->getTrueValue());
763 FlowsToReturn.insert(SI->getFalseValue());
766 case Instruction::PHI: {
767 PHINode *PN = cast<PHINode>(RVI);
768 for (Value *IncValue : PN->incoming_values())
769 FlowsToReturn.insert(IncValue);
773 // Check whether the pointer came from an allocation.
774 case Instruction::Alloca:
776 case Instruction::Call:
777 case Instruction::Invoke: {
779 if (CS.paramHasAttr(0, Attribute::NoAlias))
781 if (CS.getCalledFunction() &&
782 SCCNodes.count(CS.getCalledFunction()))
786 return false; // Did not come from an allocation.
789 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
796 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
797 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
798 SmallPtrSet<Function*, 8> SCCNodes;
800 // Fill SCCNodes with the elements of the SCC. Used for quickly
801 // looking up whether a given CallGraphNode is in this SCC.
802 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
803 SCCNodes.insert((*I)->getFunction());
805 // Check each function in turn, determining which functions return noalias
807 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
808 Function *F = (*I)->getFunction();
810 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
811 // External node or node we don't want to optimize - skip it;
815 if (F->doesNotAlias(0))
818 // Definitions with weak linkage may be overridden at linktime, so
819 // treat them like declarations.
820 if (F->isDeclaration() || F->mayBeOverridden())
823 // We annotate noalias return values, which are only applicable to
825 if (!F->getReturnType()->isPointerTy())
828 if (!IsFunctionMallocLike(F, SCCNodes))
832 bool MadeChange = false;
833 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
834 Function *F = (*I)->getFunction();
835 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
838 F->setDoesNotAlias(0);
846 bool FunctionAttrs::ReturnsNonNull(Function *F,
847 SmallPtrSet<Function*, 8> &SCCNodes,
848 bool &Speculative) const {
849 assert(F->getReturnType()->isPointerTy() &&
850 "nonnull only meaningful on pointer types");
853 SmallSetVector<Value *, 8> FlowsToReturn;
854 for (BasicBlock &BB : *F)
855 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
856 FlowsToReturn.insert(Ret->getReturnValue());
858 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
859 Value *RetVal = FlowsToReturn[i];
861 // If this value is locally known to be non-null, we're good
862 if (isKnownNonNull(RetVal, TLI))
865 // Otherwise, we need to look upwards since we can't make any local
867 Instruction *RVI = dyn_cast<Instruction>(RetVal);
870 switch (RVI->getOpcode()) {
871 // Extend the analysis by looking upwards.
872 case Instruction::BitCast:
873 case Instruction::GetElementPtr:
874 case Instruction::AddrSpaceCast:
875 FlowsToReturn.insert(RVI->getOperand(0));
877 case Instruction::Select: {
878 SelectInst *SI = cast<SelectInst>(RVI);
879 FlowsToReturn.insert(SI->getTrueValue());
880 FlowsToReturn.insert(SI->getFalseValue());
883 case Instruction::PHI: {
884 PHINode *PN = cast<PHINode>(RVI);
885 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
886 FlowsToReturn.insert(PN->getIncomingValue(i));
889 case Instruction::Call:
890 case Instruction::Invoke: {
892 Function *Callee = CS.getCalledFunction();
893 // A call to a node within the SCC is assumed to return null until
895 if (Callee && SCCNodes.count(Callee)) {
902 return false; // Unknown source, may be null
904 llvm_unreachable("should have either continued or returned");
910 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
911 SmallPtrSet<Function*, 8> SCCNodes;
913 // Fill SCCNodes with the elements of the SCC. Used for quickly
914 // looking up whether a given CallGraphNode is in this SCC.
915 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
916 SCCNodes.insert((*I)->getFunction());
918 // Speculative that all functions in the SCC return only nonnull
919 // pointers. We may refute this as we analyze functions.
920 bool SCCReturnsNonNull = true;
922 bool MadeChange = false;
924 // Check each function in turn, determining which functions return nonnull
926 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
927 Function *F = (*I)->getFunction();
929 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
930 // External node or node we don't want to optimize - skip it;
934 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
938 // Definitions with weak linkage may be overridden at linktime, so
939 // treat them like declarations.
940 if (F->isDeclaration() || F->mayBeOverridden())
943 // We annotate nonnull return values, which are only applicable to
945 if (!F->getReturnType()->isPointerTy())
948 bool Speculative = false;
949 if (ReturnsNonNull(F, SCCNodes, Speculative)) {
951 // Mark the function eagerly since we may discover a function
952 // which prevents us from speculating about the entire SCC
953 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
954 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
960 // At least one function returns something which could be null, can't
961 // speculate any more.
962 SCCReturnsNonNull = false;
965 if (SCCReturnsNonNull) {
966 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
967 Function *F = (*I)->getFunction();
968 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
969 Attribute::NonNull) ||
970 !F->getReturnType()->isPointerTy())
973 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
974 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
983 /// inferPrototypeAttributes - Analyze the name and prototype of the
984 /// given function and set any applicable attributes. Returns true
985 /// if any attributes were set and false otherwise.
986 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
987 if (F.hasFnAttribute(Attribute::OptimizeNone))
990 FunctionType *FTy = F.getFunctionType();
991 LibFunc::Func TheLibFunc;
992 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
995 switch (TheLibFunc) {
996 case LibFunc::strlen:
997 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
999 setOnlyReadsMemory(F);
1001 setDoesNotCapture(F, 1);
1003 case LibFunc::strchr:
1004 case LibFunc::strrchr:
1005 if (FTy->getNumParams() != 2 ||
1006 !FTy->getParamType(0)->isPointerTy() ||
1007 !FTy->getParamType(1)->isIntegerTy())
1009 setOnlyReadsMemory(F);
1012 case LibFunc::strtol:
1013 case LibFunc::strtod:
1014 case LibFunc::strtof:
1015 case LibFunc::strtoul:
1016 case LibFunc::strtoll:
1017 case LibFunc::strtold:
1018 case LibFunc::strtoull:
1019 if (FTy->getNumParams() < 2 ||
1020 !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 ||
1033 !FTy->getParamType(1)->isPointerTy())
1036 setDoesNotCapture(F, 2);
1037 setOnlyReadsMemory(F, 2);
1039 case LibFunc::strxfrm:
1040 if (FTy->getNumParams() != 3 ||
1041 !FTy->getParamType(0)->isPointerTy() ||
1042 !FTy->getParamType(1)->isPointerTy())
1045 setDoesNotCapture(F, 1);
1046 setDoesNotCapture(F, 2);
1047 setOnlyReadsMemory(F, 2);
1049 case LibFunc::strcmp: //0,1
1050 case LibFunc::strspn: // 0,1
1051 case LibFunc::strncmp: // 0,1
1052 case LibFunc::strcspn: //0,1
1053 case LibFunc::strcoll: //0,1
1054 case LibFunc::strcasecmp: // 0,1
1055 case LibFunc::strncasecmp: //
1056 if (FTy->getNumParams() < 2 ||
1057 !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 ||
1108 !FTy->getParamType(0)->isPointerTy() ||
1109 !FTy->getParamType(1)->isPointerTy())
1112 setDoesNotCapture(F, 1);
1113 setDoesNotCapture(F, 2);
1114 setOnlyReadsMemory(F, 1);
1116 case LibFunc::sscanf:
1117 if (FTy->getNumParams() < 2 ||
1118 !FTy->getParamType(0)->isPointerTy() ||
1119 !FTy->getParamType(1)->isPointerTy())
1122 setDoesNotCapture(F, 1);
1123 setDoesNotCapture(F, 2);
1124 setOnlyReadsMemory(F, 1);
1125 setOnlyReadsMemory(F, 2);
1127 case LibFunc::sprintf:
1128 if (FTy->getNumParams() < 2 ||
1129 !FTy->getParamType(0)->isPointerTy() ||
1130 !FTy->getParamType(1)->isPointerTy())
1133 setDoesNotCapture(F, 1);
1134 setDoesNotCapture(F, 2);
1135 setOnlyReadsMemory(F, 2);
1137 case LibFunc::snprintf:
1138 if (FTy->getNumParams() != 3 ||
1139 !FTy->getParamType(0)->isPointerTy() ||
1140 !FTy->getParamType(2)->isPointerTy())
1143 setDoesNotCapture(F, 1);
1144 setDoesNotCapture(F, 3);
1145 setOnlyReadsMemory(F, 3);
1147 case LibFunc::setitimer:
1148 if (FTy->getNumParams() != 3 ||
1149 !FTy->getParamType(1)->isPointerTy() ||
1150 !FTy->getParamType(2)->isPointerTy())
1153 setDoesNotCapture(F, 2);
1154 setDoesNotCapture(F, 3);
1155 setOnlyReadsMemory(F, 2);
1157 case LibFunc::system:
1158 if (FTy->getNumParams() != 1 ||
1159 !FTy->getParamType(0)->isPointerTy())
1161 // May throw; "system" is a valid pthread cancellation point.
1162 setDoesNotCapture(F, 1);
1163 setOnlyReadsMemory(F, 1);
1165 case LibFunc::malloc:
1166 if (FTy->getNumParams() != 1 ||
1167 !FTy->getReturnType()->isPointerTy())
1170 setDoesNotAlias(F, 0);
1172 case LibFunc::memcmp:
1173 if (FTy->getNumParams() != 3 ||
1174 !FTy->getParamType(0)->isPointerTy() ||
1175 !FTy->getParamType(1)->isPointerTy())
1177 setOnlyReadsMemory(F);
1179 setDoesNotCapture(F, 1);
1180 setDoesNotCapture(F, 2);
1182 case LibFunc::memchr:
1183 case LibFunc::memrchr:
1184 if (FTy->getNumParams() != 3)
1186 setOnlyReadsMemory(F);
1190 case LibFunc::modff:
1191 case LibFunc::modfl:
1192 if (FTy->getNumParams() < 2 ||
1193 !FTy->getParamType(1)->isPointerTy())
1196 setDoesNotCapture(F, 2);
1198 case LibFunc::memcpy:
1199 case LibFunc::memccpy:
1200 case LibFunc::memmove:
1201 if (FTy->getNumParams() < 2 ||
1202 !FTy->getParamType(1)->isPointerTy())
1205 setDoesNotCapture(F, 2);
1206 setOnlyReadsMemory(F, 2);
1208 case LibFunc::memalign:
1209 if (!FTy->getReturnType()->isPointerTy())
1211 setDoesNotAlias(F, 0);
1213 case LibFunc::mkdir:
1214 if (FTy->getNumParams() == 0 ||
1215 !FTy->getParamType(0)->isPointerTy())
1218 setDoesNotCapture(F, 1);
1219 setOnlyReadsMemory(F, 1);
1221 case LibFunc::mktime:
1222 if (FTy->getNumParams() == 0 ||
1223 !FTy->getParamType(0)->isPointerTy())
1226 setDoesNotCapture(F, 1);
1228 case LibFunc::realloc:
1229 if (FTy->getNumParams() != 2 ||
1230 !FTy->getParamType(0)->isPointerTy() ||
1231 !FTy->getReturnType()->isPointerTy())
1234 setDoesNotAlias(F, 0);
1235 setDoesNotCapture(F, 1);
1238 if (FTy->getNumParams() != 3 ||
1239 !FTy->getParamType(1)->isPointerTy())
1241 // May throw; "read" is a valid pthread cancellation point.
1242 setDoesNotCapture(F, 2);
1244 case LibFunc::rewind:
1245 if (FTy->getNumParams() < 1 ||
1246 !FTy->getParamType(0)->isPointerTy())
1249 setDoesNotCapture(F, 1);
1251 case LibFunc::rmdir:
1252 case LibFunc::remove:
1253 case LibFunc::realpath:
1254 if (FTy->getNumParams() < 1 ||
1255 !FTy->getParamType(0)->isPointerTy())
1258 setDoesNotCapture(F, 1);
1259 setOnlyReadsMemory(F, 1);
1261 case LibFunc::rename:
1262 if (FTy->getNumParams() < 2 ||
1263 !FTy->getParamType(0)->isPointerTy() ||
1264 !FTy->getParamType(1)->isPointerTy())
1267 setDoesNotCapture(F, 1);
1268 setDoesNotCapture(F, 2);
1269 setOnlyReadsMemory(F, 1);
1270 setOnlyReadsMemory(F, 2);
1272 case LibFunc::readlink:
1273 if (FTy->getNumParams() < 2 ||
1274 !FTy->getParamType(0)->isPointerTy() ||
1275 !FTy->getParamType(1)->isPointerTy())
1278 setDoesNotCapture(F, 1);
1279 setDoesNotCapture(F, 2);
1280 setOnlyReadsMemory(F, 1);
1282 case LibFunc::write:
1283 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1285 // May throw; "write" is a valid pthread cancellation point.
1286 setDoesNotCapture(F, 2);
1287 setOnlyReadsMemory(F, 2);
1289 case LibFunc::bcopy:
1290 if (FTy->getNumParams() != 3 ||
1291 !FTy->getParamType(0)->isPointerTy() ||
1292 !FTy->getParamType(1)->isPointerTy())
1295 setDoesNotCapture(F, 1);
1296 setDoesNotCapture(F, 2);
1297 setOnlyReadsMemory(F, 1);
1300 if (FTy->getNumParams() != 3 ||
1301 !FTy->getParamType(0)->isPointerTy() ||
1302 !FTy->getParamType(1)->isPointerTy())
1305 setOnlyReadsMemory(F);
1306 setDoesNotCapture(F, 1);
1307 setDoesNotCapture(F, 2);
1309 case LibFunc::bzero:
1310 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1313 setDoesNotCapture(F, 1);
1315 case LibFunc::calloc:
1316 if (FTy->getNumParams() != 2 ||
1317 !FTy->getReturnType()->isPointerTy())
1320 setDoesNotAlias(F, 0);
1322 case LibFunc::chmod:
1323 case LibFunc::chown:
1324 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1327 setDoesNotCapture(F, 1);
1328 setOnlyReadsMemory(F, 1);
1330 case LibFunc::ctermid:
1331 case LibFunc::clearerr:
1332 case LibFunc::closedir:
1333 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1336 setDoesNotCapture(F, 1);
1341 case LibFunc::atoll:
1342 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1345 setOnlyReadsMemory(F);
1346 setDoesNotCapture(F, 1);
1348 case LibFunc::access:
1349 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1352 setDoesNotCapture(F, 1);
1353 setOnlyReadsMemory(F, 1);
1355 case LibFunc::fopen:
1356 if (FTy->getNumParams() != 2 ||
1357 !FTy->getReturnType()->isPointerTy() ||
1358 !FTy->getParamType(0)->isPointerTy() ||
1359 !FTy->getParamType(1)->isPointerTy())
1362 setDoesNotAlias(F, 0);
1363 setDoesNotCapture(F, 1);
1364 setDoesNotCapture(F, 2);
1365 setOnlyReadsMemory(F, 1);
1366 setOnlyReadsMemory(F, 2);
1368 case LibFunc::fdopen:
1369 if (FTy->getNumParams() != 2 ||
1370 !FTy->getReturnType()->isPointerTy() ||
1371 !FTy->getParamType(1)->isPointerTy())
1374 setDoesNotAlias(F, 0);
1375 setDoesNotCapture(F, 2);
1376 setOnlyReadsMemory(F, 2);
1380 case LibFunc::fseek:
1381 case LibFunc::ftell:
1382 case LibFunc::fgetc:
1383 case LibFunc::fseeko:
1384 case LibFunc::ftello:
1385 case LibFunc::fileno:
1386 case LibFunc::fflush:
1387 case LibFunc::fclose:
1388 case LibFunc::fsetpos:
1389 case LibFunc::flockfile:
1390 case LibFunc::funlockfile:
1391 case LibFunc::ftrylockfile:
1392 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1395 setDoesNotCapture(F, 1);
1397 case LibFunc::ferror:
1398 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1401 setDoesNotCapture(F, 1);
1402 setOnlyReadsMemory(F);
1404 case LibFunc::fputc:
1405 case LibFunc::fstat:
1406 case LibFunc::frexp:
1407 case LibFunc::frexpf:
1408 case LibFunc::frexpl:
1409 case LibFunc::fstatvfs:
1410 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1413 setDoesNotCapture(F, 2);
1415 case LibFunc::fgets:
1416 if (FTy->getNumParams() != 3 ||
1417 !FTy->getParamType(0)->isPointerTy() ||
1418 !FTy->getParamType(2)->isPointerTy())
1421 setDoesNotCapture(F, 3);
1423 case LibFunc::fread:
1424 if (FTy->getNumParams() != 4 ||
1425 !FTy->getParamType(0)->isPointerTy() ||
1426 !FTy->getParamType(3)->isPointerTy())
1429 setDoesNotCapture(F, 1);
1430 setDoesNotCapture(F, 4);
1432 case LibFunc::fwrite:
1433 if (FTy->getNumParams() != 4 ||
1434 !FTy->getParamType(0)->isPointerTy() ||
1435 !FTy->getParamType(3)->isPointerTy())
1438 setDoesNotCapture(F, 1);
1439 setDoesNotCapture(F, 4);
1441 case LibFunc::fputs:
1442 if (FTy->getNumParams() < 2 ||
1443 !FTy->getParamType(0)->isPointerTy() ||
1444 !FTy->getParamType(1)->isPointerTy())
1447 setDoesNotCapture(F, 1);
1448 setDoesNotCapture(F, 2);
1449 setOnlyReadsMemory(F, 1);
1451 case LibFunc::fscanf:
1452 case LibFunc::fprintf:
1453 if (FTy->getNumParams() < 2 ||
1454 !FTy->getParamType(0)->isPointerTy() ||
1455 !FTy->getParamType(1)->isPointerTy())
1458 setDoesNotCapture(F, 1);
1459 setDoesNotCapture(F, 2);
1460 setOnlyReadsMemory(F, 2);
1462 case LibFunc::fgetpos:
1463 if (FTy->getNumParams() < 2 ||
1464 !FTy->getParamType(0)->isPointerTy() ||
1465 !FTy->getParamType(1)->isPointerTy())
1468 setDoesNotCapture(F, 1);
1469 setDoesNotCapture(F, 2);
1472 case LibFunc::getlogin_r:
1473 case LibFunc::getc_unlocked:
1474 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1477 setDoesNotCapture(F, 1);
1479 case LibFunc::getenv:
1480 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1483 setOnlyReadsMemory(F);
1484 setDoesNotCapture(F, 1);
1487 case LibFunc::getchar:
1490 case LibFunc::getitimer:
1491 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1494 setDoesNotCapture(F, 2);
1496 case LibFunc::getpwnam:
1497 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1500 setDoesNotCapture(F, 1);
1501 setOnlyReadsMemory(F, 1);
1503 case LibFunc::ungetc:
1504 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1507 setDoesNotCapture(F, 2);
1509 case LibFunc::uname:
1510 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1513 setDoesNotCapture(F, 1);
1515 case LibFunc::unlink:
1516 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1519 setDoesNotCapture(F, 1);
1520 setOnlyReadsMemory(F, 1);
1522 case LibFunc::unsetenv:
1523 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1526 setDoesNotCapture(F, 1);
1527 setOnlyReadsMemory(F, 1);
1529 case LibFunc::utime:
1530 case LibFunc::utimes:
1531 if (FTy->getNumParams() != 2 ||
1532 !FTy->getParamType(0)->isPointerTy() ||
1533 !FTy->getParamType(1)->isPointerTy())
1536 setDoesNotCapture(F, 1);
1537 setDoesNotCapture(F, 2);
1538 setOnlyReadsMemory(F, 1);
1539 setOnlyReadsMemory(F, 2);
1542 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1545 setDoesNotCapture(F, 2);
1548 case LibFunc::printf:
1549 case LibFunc::perror:
1550 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1553 setDoesNotCapture(F, 1);
1554 setOnlyReadsMemory(F, 1);
1556 case LibFunc::pread:
1557 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1559 // May throw; "pread" is a valid pthread cancellation point.
1560 setDoesNotCapture(F, 2);
1562 case LibFunc::pwrite:
1563 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1565 // May throw; "pwrite" is a valid pthread cancellation point.
1566 setDoesNotCapture(F, 2);
1567 setOnlyReadsMemory(F, 2);
1569 case LibFunc::putchar:
1572 case LibFunc::popen:
1573 if (FTy->getNumParams() != 2 ||
1574 !FTy->getReturnType()->isPointerTy() ||
1575 !FTy->getParamType(0)->isPointerTy() ||
1576 !FTy->getParamType(1)->isPointerTy())
1579 setDoesNotAlias(F, 0);
1580 setDoesNotCapture(F, 1);
1581 setDoesNotCapture(F, 2);
1582 setOnlyReadsMemory(F, 1);
1583 setOnlyReadsMemory(F, 2);
1585 case LibFunc::pclose:
1586 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1589 setDoesNotCapture(F, 1);
1591 case LibFunc::vscanf:
1592 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1595 setDoesNotCapture(F, 1);
1596 setOnlyReadsMemory(F, 1);
1598 case LibFunc::vsscanf:
1599 if (FTy->getNumParams() != 3 ||
1600 !FTy->getParamType(1)->isPointerTy() ||
1601 !FTy->getParamType(2)->isPointerTy())
1604 setDoesNotCapture(F, 1);
1605 setDoesNotCapture(F, 2);
1606 setOnlyReadsMemory(F, 1);
1607 setOnlyReadsMemory(F, 2);
1609 case LibFunc::vfscanf:
1610 if (FTy->getNumParams() != 3 ||
1611 !FTy->getParamType(1)->isPointerTy() ||
1612 !FTy->getParamType(2)->isPointerTy())
1615 setDoesNotCapture(F, 1);
1616 setDoesNotCapture(F, 2);
1617 setOnlyReadsMemory(F, 2);
1619 case LibFunc::valloc:
1620 if (!FTy->getReturnType()->isPointerTy())
1623 setDoesNotAlias(F, 0);
1625 case LibFunc::vprintf:
1626 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1629 setDoesNotCapture(F, 1);
1630 setOnlyReadsMemory(F, 1);
1632 case LibFunc::vfprintf:
1633 case LibFunc::vsprintf:
1634 if (FTy->getNumParams() != 3 ||
1635 !FTy->getParamType(0)->isPointerTy() ||
1636 !FTy->getParamType(1)->isPointerTy())
1639 setDoesNotCapture(F, 1);
1640 setDoesNotCapture(F, 2);
1641 setOnlyReadsMemory(F, 2);
1643 case LibFunc::vsnprintf:
1644 if (FTy->getNumParams() != 4 ||
1645 !FTy->getParamType(0)->isPointerTy() ||
1646 !FTy->getParamType(2)->isPointerTy())
1649 setDoesNotCapture(F, 1);
1650 setDoesNotCapture(F, 3);
1651 setOnlyReadsMemory(F, 3);
1654 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1656 // May throw; "open" is a valid pthread cancellation point.
1657 setDoesNotCapture(F, 1);
1658 setOnlyReadsMemory(F, 1);
1660 case LibFunc::opendir:
1661 if (FTy->getNumParams() != 1 ||
1662 !FTy->getReturnType()->isPointerTy() ||
1663 !FTy->getParamType(0)->isPointerTy())
1666 setDoesNotAlias(F, 0);
1667 setDoesNotCapture(F, 1);
1668 setOnlyReadsMemory(F, 1);
1670 case LibFunc::tmpfile:
1671 if (!FTy->getReturnType()->isPointerTy())
1674 setDoesNotAlias(F, 0);
1676 case LibFunc::times:
1677 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1680 setDoesNotCapture(F, 1);
1682 case LibFunc::htonl:
1683 case LibFunc::htons:
1684 case LibFunc::ntohl:
1685 case LibFunc::ntohs:
1687 setDoesNotAccessMemory(F);
1689 case LibFunc::lstat:
1690 if (FTy->getNumParams() != 2 ||
1691 !FTy->getParamType(0)->isPointerTy() ||
1692 !FTy->getParamType(1)->isPointerTy())
1695 setDoesNotCapture(F, 1);
1696 setDoesNotCapture(F, 2);
1697 setOnlyReadsMemory(F, 1);
1699 case LibFunc::lchown:
1700 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1703 setDoesNotCapture(F, 1);
1704 setOnlyReadsMemory(F, 1);
1706 case LibFunc::qsort:
1707 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1709 // May throw; places call through function pointer.
1710 setDoesNotCapture(F, 4);
1712 case LibFunc::dunder_strdup:
1713 case LibFunc::dunder_strndup:
1714 if (FTy->getNumParams() < 1 ||
1715 !FTy->getReturnType()->isPointerTy() ||
1716 !FTy->getParamType(0)->isPointerTy())
1719 setDoesNotAlias(F, 0);
1720 setDoesNotCapture(F, 1);
1721 setOnlyReadsMemory(F, 1);
1723 case LibFunc::dunder_strtok_r:
1724 if (FTy->getNumParams() != 3 ||
1725 !FTy->getParamType(1)->isPointerTy())
1728 setDoesNotCapture(F, 2);
1729 setOnlyReadsMemory(F, 2);
1731 case LibFunc::under_IO_getc:
1732 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1735 setDoesNotCapture(F, 1);
1737 case LibFunc::under_IO_putc:
1738 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1741 setDoesNotCapture(F, 2);
1743 case LibFunc::dunder_isoc99_scanf:
1744 if (FTy->getNumParams() < 1 ||
1745 !FTy->getParamType(0)->isPointerTy())
1748 setDoesNotCapture(F, 1);
1749 setOnlyReadsMemory(F, 1);
1751 case LibFunc::stat64:
1752 case LibFunc::lstat64:
1753 case LibFunc::statvfs64:
1754 if (FTy->getNumParams() < 1 ||
1755 !FTy->getParamType(0)->isPointerTy() ||
1756 !FTy->getParamType(1)->isPointerTy())
1759 setDoesNotCapture(F, 1);
1760 setDoesNotCapture(F, 2);
1761 setOnlyReadsMemory(F, 1);
1763 case LibFunc::dunder_isoc99_sscanf:
1764 if (FTy->getNumParams() < 1 ||
1765 !FTy->getParamType(0)->isPointerTy() ||
1766 !FTy->getParamType(1)->isPointerTy())
1769 setDoesNotCapture(F, 1);
1770 setDoesNotCapture(F, 2);
1771 setOnlyReadsMemory(F, 1);
1772 setOnlyReadsMemory(F, 2);
1774 case LibFunc::fopen64:
1775 if (FTy->getNumParams() != 2 ||
1776 !FTy->getReturnType()->isPointerTy() ||
1777 !FTy->getParamType(0)->isPointerTy() ||
1778 !FTy->getParamType(1)->isPointerTy())
1781 setDoesNotAlias(F, 0);
1782 setDoesNotCapture(F, 1);
1783 setDoesNotCapture(F, 2);
1784 setOnlyReadsMemory(F, 1);
1785 setOnlyReadsMemory(F, 2);
1787 case LibFunc::fseeko64:
1788 case LibFunc::ftello64:
1789 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1792 setDoesNotCapture(F, 1);
1794 case LibFunc::tmpfile64:
1795 if (!FTy->getReturnType()->isPointerTy())
1798 setDoesNotAlias(F, 0);
1800 case LibFunc::fstat64:
1801 case LibFunc::fstatvfs64:
1802 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1805 setDoesNotCapture(F, 2);
1807 case LibFunc::open64:
1808 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1810 // May throw; "open" is a valid pthread cancellation point.
1811 setDoesNotCapture(F, 1);
1812 setOnlyReadsMemory(F, 1);
1814 case LibFunc::gettimeofday:
1815 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1816 !FTy->getParamType(1)->isPointerTy())
1818 // Currently some platforms have the restrict keyword on the arguments to
1819 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1822 setDoesNotCapture(F, 1);
1823 setDoesNotCapture(F, 2);
1826 // Didn't mark any attributes.
1833 /// annotateLibraryCalls - Adds attributes to well-known standard library
1834 /// call declarations.
1835 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1836 bool MadeChange = false;
1838 // Check each function in turn annotating well-known library function
1839 // declarations with attributes.
1840 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1841 Function *F = (*I)->getFunction();
1843 if (F && F->isDeclaration())
1844 MadeChange |= inferPrototypeAttributes(*F);
1850 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1851 AA = &getAnalysis<AliasAnalysis>();
1852 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1854 bool Changed = annotateLibraryCalls(SCC);
1855 Changed |= AddReadAttrs(SCC);
1856 Changed |= AddArgumentAttrs(SCC);
1857 Changed |= AddNoAliasAttrs(SCC);
1858 Changed |= AddNonNullAttrs(SCC);